如题,有没有朋友遇到过retrofit2将请求写在一个工具类中,然后调用的,但是发现这样调用无效,
直接把请求写在activity中,就没问题。
工具类代码如下:
public class MusicData {
private SongMusic mSongMusic;
private Retrofit mRetrofit;
private static MusicData mData=new MusicData();
private MusicData(){}
public HttpApi getHttp(){
if(mRetrofit==null){
mRetrofit=new Retrofit.Builder().baseUrl("http://tingapi.ting.baidu.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return mRetrofit.create(HttpApi.class);
}
public void getListMusic(int type, int size, int off){
Call<RecommentBean> mCall=getHttp().getrecomment(type,size,off);
mCall.enqueue(new Callback<RecommentBean>() {
@Override
public void onResponse(Call<RecommentBean> call, Response<RecommentBean> response) {
mSongMusic.setAdapter(response.body().getSong_list());
}
@Override
public void onFailure(Call<RecommentBean> call, Throwable t) {
}
});
}
//设置接口实现类的对象
public void setSongServer(SongMusic song){
mSongMusic=song;
}
public static MusicData getMusicData(){
return mData;
}
}
异常报错:
Process: com.wang.mymusic, PID: 3414
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.wang.mymusic.model.RecommentBean.getSong_list()' on a null object reference
at com.wang.mymusic.data.MusicData$2.onResponse(MusicData.java:50)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
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:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)