Tell me what I'm doing wrong, using Retrofit2 and get the following error: "java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call com.example.com.xxx.TechNewsApi.articles(java.lang.String)' on a null object reference"

App class:

 public class App extends Application { public static TechNewsApi service; @Override public void onCreate() { super.onCreate(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://hacker-news.firebaseio.com/v0/item/") .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(TechNewsApi.class); } } 

Interface:

 public interface TechNewsApi { @GET("{articleId}.json?print=pretty") Call<List<Article>> articles(@Path("articleId") String articleId); } 

Activit, where Retrofit is called:

 public class WelcomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); // в этой строчке происходит ошибка Call<List<Article>> call = App.service.articles("1"); call.enqueue(new Callback<List<Article>>() { @Override public void onResponse(Call<List<Article>> call, Response<List<Article>> response) { Log.e("Retrofit respoce: ", response.body().toString()); } @Override public void onFailure(Call<List<Article>> call, Throwable t) { Log.e("Something went wrong:", t.getMessage()); } }); } 

}

  • one
    is your App written in the manifest? - ermak0ff
  • @ ermak0ff Oops, no - Lucky_girl
  • @ ermak0ff You are right, the problem was this - Lucky_girl

1 answer 1

Register your App class in the manifest:

 <application android:name=".App" ... </application>