Here I am retrieving data from an API everything works fine but 1. Suces is showing on Toast then App crashes
public class MainActivity extends AppCompatActivity {
public TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview);
MyWebService myWebService = MyWebService.retrofit.create(MyWebService.class);
Call<Train> call = myWebService.getTrain();
call.enqueue(new Callback<Train>() {
@Override
public void onResponse(Call<Train> call, Response<Train> response) {
if(response.isSuccessful() && response.body()!=null)
{
Train train = response.body();
Toast.makeText(getApplicationContext(),"Sucess",Toast.LENGTH_LONG).show();
textView.setText(train.getTrain2().getName());
}
}
@Override
public void onFailure(Call<Train> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
I am getting error at this line
textView.setText(train.getTrain2().getName());
But I initialize the textview and also checking response!=null
Error is
02-14 22:41:40.003 1557-1557/? E/Zygote: v2
02-14 22:41:40.003 1557-1557/? E/Zygote: accessInfo : 0
02-14 22:41:41.963 1557-1557/com.piyushjaiswal121.rail E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.piyushjaiswal121.rail, PID: 1557
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.piyushjaiswal121.rail.Train2.getName()' on a null object reference
at com.piyushjaiswal121.rail.MainActivity$1.onResponse(MainActivity.java:36)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)