源码
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;
}
}
错误
E/AndroidRuntime: FATAL EXCEPTION: main
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)
描述
这块是使用retrofit2请求音乐列表,并将请求放在一个工具类中的方法里,使用接口将返回值传递给需要使用返回数据的页面,但是在编译运行时报错;但是该请求代码放在activity中的时候是正确的,可以正常获得数据,在网上着也没有搜索到解决方法,不知道是哪里出错了
在retrofit的接口文件中设置headers参数User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64)(可以通过查看浏览器在请求该地址时的头部参数,然后将该参数设置到retrofit中即可),即可解决问题