Reputation: 55
I am creating and an App using Retrofit and json from my wordpress and my some array objects which having acf array has null value.. whenever that null value fetch then the activity close and previous activity opens.. How can i handle that null object .. i mean whenever it fetches, activity needs to run as it is and i can change that null value to another value.
Debug
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.ats.sarkarijobs.MainActivity$2.onResponse(MainActivity.java:153)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Activity Code
call.enqueue(new Callback<List<WPPost>>() {
@Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.e("mainactivyt", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
for (int i=0; i<response.body().size();i++){
Log.e("main ", " title "+ response.body().get(i).getTitle().getRendered() + " "+
response.body().get(i).getId());
String tempdetails = response.body().get(i).getExcerpt().getRendered().toString();
tempdetails = tempdetails.replace("<p>","");
tempdetails = tempdetails.replace("</p>","");
tempdetails = tempdetails.replace("[…]","");
list.add( new Model( Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
tempdetails, response.body().get(i).getAcf().getName(), response.body().get(i).getLink()) );
}
adapter.notifyDataSetChanged();
progressload.setVisibility(View.GONE);
}
@Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
Upvotes: 1
Views: 6816
Reputation: 717
You have to check whether null or not before accessing object's method
Or you can use try
catch
to handle NullPointerException
exception like below.
@Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.e("mainactivyt", " response "+ response.body());
try {
mListPost = response.body();
progressBar.setVisibility(View.GONE);
for (int i=0; i<response.body().size();i++){
...
}
} catch (NullPointerException e) {
System.err.println("Null pointer exception");
}
adapter.notifyDataSetChanged();
progressload.setVisibility(View.GONE);
}
Upvotes: 3