Разбор JSON в Android Studio с использованием Volley: получение исключения NullPointerException
Я изучил основы библиотеки Volley для анализа JSON, и я попытался выполнить вход с использованием синтаксического анализа объекта JSON, указав два параметра, но в итоге я получил NullPointerException, и вот мой код:
public class MainActivity extends Activity {
// json object response url
private String urlJsonObj = "agendamaid.com/api/v1/login";
// json array response url
private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private static String TAG = MainActivity.class.getSimpleName();
private Button btnMakeObjectRequest, btnMakeArrayRequest;
// Progress dialog
private ProgressDialog pDialog;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
btnMakeObjectRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// making json object request
makeJsonObjectRequest();
}
});
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// making json array request
makeJsonArrayRequest();
}
});
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
JSONObject payload = response.getJSONObject("payload");
String key = payload.getString("key");
String userID= payload.getString("userID");
jsonResponse = "";
jsonResponse += "Key: " + key + "\n\n";
jsonResponse += "userID: " + userID + "\n\n";
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", "aldi@gmail.com");
params.put("password", "testingpassword");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
и вот ошибка, которую я получаю:
> 10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: FATAL EXCEPTION: main
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: java.lang.NullPointerException
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at com.android.volley.Request.<init>(Request.java:136)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at com.android.volley.toolbox.JsonRequest.<init>(JsonRequest.java:58)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at com.android.volley.toolbox.JsonObjectRequest.<init>(JsonObjectRequest.java:47)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at vin.cobavolley.MainActivity$5.<init>(MainActivity.java:129)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at vin.cobavolley.MainActivity.makeJsonObjectRequest(MainActivity.java:88)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at vin.cobavolley.MainActivity.access$000(MainActivity.java:29)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at vin.cobavolley.MainActivity$1.onClick(MainActivity.java:66)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.view.View.performClick(View.java:4204)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:17355)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-18 02:38:49.637 4154-4154/vin.cobavolley E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
10-18 02:43:49.673 4154-4154/? I/Process: Sending signal. PID: 4154 SIG: 9
Пожалуйста помоги! Заранее спасибо!
1 ответ
Решение
Ладно, ребята, извините за все проблемы... все произошло потому, что я не поместил "http://" в URL, он работает сейчас