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

时间:2016-04-15 02:49:18

标签: android nullpointerexception android-volley

我读过 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 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);

}
*/






}

网络服务正在运作。

1 个答案:

答案 0 :(得分:3)

这意味着您尝试获取length()的{​​{1}}为空。

罪魁祸首就是这条线:

String

这意味着如果响应不为空 OR ,则其长度大于零。

你想要的是:

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

如果响应为空,这将使语句失败,因为如果是,则无法检查长度。