com.android.volley.VolleyError:java.lang.NullPointerException

我读过了
What is a NullPointerException, and how do I fix it?
Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
还有一些,但是我没有运气修复它.

这是我从齐射错误监听器收到的错误-

com.android.volley.VolleyError:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法’int java.lang.String.length()’

我是android的新手,有人可以向我解释我的问题的原因并帮助我解决它吗?

以下是发出截击请求的活动代码-

public class CircleActivity extends AppCompatActivity  implements SwipeRefreshLayout.OnRefreshListener {

private Toolbar toolbar;
private FloatingActionButton fab;
private ArrayList<Users> listUsers = new ArrayList<>();
SessionManager sessionManager;

BroadcastReceiver broadcastReceiver;

private RecyclerView listUsersCircle;

//swipe
private SwipeRefreshLayout swipeRefreshLayout;

//volley login
//mobile hotspot
//public static final String REGISTER_URL = "http://192.168.43.181/save/user/getPeopleList";
//ghar
public final String REGISTER_URL = "http://192.168.0.10/save/user/getPeopleList";


private CircleListAdapter circleListAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    sessionManager = new SessionManager(getApplicationContext());
    if (sessionManager.isLoggedIn()) {
        setContentView(R.layout.activity_circle);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        //tell android to use my toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);

        listUsersCircle = (RecyclerView) findViewById(R.id.circle);
        listUsersCircle.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        circleListAdapter = new CircleListAdapter(getApplicationContext());
        listUsersCircle.setAdapter(circleListAdapter);


        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_circle);
        swipeRefreshLayout.setOnRefreshListener(this);


        sendJsonRequest();

        //get user_id from session
        String user_id = sessionManager.getUserDetails().get("user_id");
        //adding data to the intent
        Intent intent = new Intent(getBaseContext), LocationService.class);
        intent.putExtra("user_id", user_id);
        startService(intent);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String phoneNumber="123123123412";
                String message ="Hello sms";

                sendSMS(phoneNumber,message);


            }
        });




        //location service

        // startService(new Intent(getBaseContext(), LocationService.class));

        //swipe to refresh


   /* JSONObject obj = new JSONObject();
    try {
        obj.put("txtCircleId", "acca16d632");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.d("Nishon",obj.toString());
    RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
            URL_GET_CIRCLE_USERS,
            obj,
            new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
            Log.d("Nishon",response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void one rrorResponse(VolleyError error) {
            Log.d("Nishon", error.toString());
        }
    });
    requestQueue.add(request);*/

    } else {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

}

private void sendSMS(String phoneNumber, String message)
{

    PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, pi, null);
}

public void sendJsonRequest() {
    RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
    StringRequest request = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    listUsers = parseJsonResponse(response);
                    circleListAdapter.setCircleList(listUsers);
                    Log.d("d",response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void one rrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
                    Log.d("d", error.toString());
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            String group_key= sessionManager.getUserDetails().get("group_key");

            params.put("group_key", group_key);
            return params;
        }
    };
    requestQueue.add(request);
}

public ArrayList<Users> parseJsonResponse(String response) {
    ArrayList<Users> listUsers = new ArrayList<>();
    if (response != null || response.length() > 0) {

        Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //extracting json array from response string
        JSONArray jsonArray = null;
        try {

            if (jsonObject.has("users")) {

                jsonArray = jsonObject.getJSONArray("users");


                for (int z = 0; z < jsonArray.length(); z++) {


                    JSONObject currentUser = jsonArray.getJSONObject(z);

                    //String email = currentUser.getString("email");
                    String fname = currentUser.getString("first_name");
                    String lname = currentUser.getString("last_name");

                    Users user = new Users();

                    user.setFname(fname);
                    user.setLname(lname);
                    listUsers.add(user);

                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
       /* JSONObject jsonRow = null;
        try {
            jsonRow = jsonArray.getJSONObject(1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //get value from jsonRow
        try {
            String resultStr = jsonRow.getString("email");
            Log.d("Nishon", resultStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
    }
    return listUsers;
}

@Override
protected void onPause() {
    super.onPause();
    finish();
}

public void showNotification(View view) {

}

@Override
public void onRefresh() {
    swipeRefreshLayout.setRefreshing(true);
    sendJsonRequest();
    swipeRefreshLayout.setRefreshing(false);
}

/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {
        // Do something here...
        event.startTracking(); // Needed to track long presses
        return true;
    }

    return super.onKeyDown(keyCode, event);

}
*/






}

Web服务正在运行.

解决方法:

这意味着您正在尝试获取null的String的length().

罪魁祸首是这条线:

if (response != null || response.length() > 0) {

这意味着如果响应不为null或长度大于零.

您想要的是:

if (response != null && response.length() > 0) {

如果响应为null,则该语句将失败,因为如果为null,则无法检查长度.

上一篇:java-onPostExecute()中的ArrayList空指针异常


下一篇:java-Android NumberPicker NullPointer为什么?