真的很难将我的Android应用程序连接到具有我需要的JSON的API。我的日志显示JSON进来(即我可以在Android Studio的日志中看到完整的JSON数组),但我的for循环行中出现了nullpointer错误。我知道我应该首先初始化它,但我的JSONArray确实是占位符,直到在另一个类中调用getApartmentList方法。并且直接尝试访问API以在此处为JSONArray提供实际值显然会导致networkonmainthread错误。我可能过于复杂了,但我错过了什么?
public List<Apartment> getApartmentList(JSONArray jsonArray) { //added the parameter, placeholder for "apartments" array which contains all apts in our database
List<Apartment> apartmentList = new ArrayList<>();
for(int i=0; i<jsonArray.length();i++){ //nullpointer exception here
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
Apartment apartment = new Apartment(UUID.fromString(json.getString("id") ) ); //UUID from String already converts our JSON string result into a UUID
apartment.setApartmentText(json.getInt("price") + " " + json.getInt("bedrooms") + " " + json.getInt("bathrooms") );
apartment.setApartmentLatitude(json.getJSONObject("building").getDouble("latitude"));
apartment.setApartmentLongitude(json.getJSONObject("building").getDouble("longitude"));
apartmentList.add(apartment);
} catch (JSONException e) {
e.printStackTrace();
}
}//end of for loop
return apartmentList;
}//end of getApartmentList method
这是在单独的类中调用此方法并获得实际值的地方:
public class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray> {
@Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].GetAllCustomers();
}
//the ApiConnector class is where I connect to the URL of the API, i.e. where i connect to the JSON
@Override
protected void onPostExecute(JSONArray jsonArray) {
ApartmentInventory apartmentInventory = new ApartmentInventory(getActivity() );
apartmentInventory.getApartmentList(jsonArray);
}
} // end of GetAllCustomerTask method
编辑 - 粘贴日志
11-19 22:00:22.787 24528-24528/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example, PID: 24528
java.lang.NullPointerException
at ApartmentInventory.getApartmentList(ApartmentInventory.java:118)
at ListingsFragment$GetAllCustomerTask.onPostExecute(ListingsFragment.java:79)
at ListingsFragment$GetAllCustomerTask.onPostExecute(ListingsFragment.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)