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

16,655

This means that you are attempting to get the length() of a String which is null.

The culprit is this line:

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

This means if the response isn't null OR it's length is greater zero.

What you want is:

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

This will fail the statement if the response is null, because if it is, you can't check the length.

Share:
16,655
nishon.tan
Author by

nishon.tan

Updated on June 05, 2022

Comments

  • nishon.tan
    nishon.tan about 2 years

    I have read 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 and a few more but I have had no luck fixing it.

    This is the error that I get from volley error listener -

    com.android.volley.VolleyError: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

    I am fairly new to android, could someone please explain to me what the cause of my problem and help me fix it?

    Below is the code for activity that makes the volley request -

    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 onErrorResponse(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 onErrorResponse(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);
    
    }
    */
    
    
    
    
    
    
    }
    

    The webservice is working.