mvp+RecyclerView实现网络请求

Posted 小马哥(马云)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mvp+RecyclerView实现网络请求相关的知识,希望对你有一定的参考价值。

 

public class Api {
    public static final String url="http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=%s";
}

  net包下       网络请求

public class HttpUtils {
    private static HttpUtils httpUtils;
    private final OkHttpClient client;

    private HttpUtils(){
        client = new OkHttpClient.Builder()
                //设置拦截器
                .addInterceptor(new LoggingInterceptor())
                //设置操作
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .build();
    }
    public  static HttpUtils getHttpUtils(){
        if(httpUtils==null){
            synchronized (HttpUtils.class){
                if(httpUtils==null){
                    httpUtils=new HttpUtils();
                }
            }
        }
        return httpUtils;
    }
    //doget方法
    public void doGet(String url, Callback callback){
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }
    //dopost方法
   /* public void doPost(String url, Map<String, String> params, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        client.newCall(request).enqueue(callback);
    }*/
}

  拦截器

public class LoggingInterceptor implements Interceptor{
    private static final String UA = "User-Agent";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader(UA, makeUA())
                .build();
        return chain.proceed(request);
    }
    private String makeUA() {
        String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
        return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
    }
}

  成功或者失败的方法

public interface OnNetListener<T> {
    public void onSuccess(T t);
    public void onFailure(Exception e);
}

  model下   MusicModel

public class MusicModel  implements IMusicModel{
    private Handler handler = new Handler(Looper.getMainLooper());

    public void getMusic(String offset, final OnNetListener<MusicBean> onNetListener){

        String url = String.format(Api.url, offset);
        HttpUtils.getHttpUtils().doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onFailure(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final MusicBean musicBean = new Gson().fromJson(string, MusicBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(musicBean);
                    }
                });
            }
        });
    }
}

  IMusicModel

public interface IMusicModel {
    public void getMusic(String offset, final OnNetListener<MusicBean> onNetListener);
}

presenter层    MusicPresenter

public class MusicPresenter {
    private final MusicModel musicModel;
    private IMainActivity iMainActivity;


    public MusicPresenter(IMainActivity iMainActivity) {
        this.iMainActivity = iMainActivity;
         musicModel = new MusicModel();
    }
    public void getMusic(String offset){
        musicModel.getMusic(offset, new OnNetListener<MusicBean>() {
            @Override
            public void onSuccess(MusicBean musicBean) {
                iMainActivity.showBannerIv(musicBean.getBillboard().getPic_s640());
                iMainActivity.showRv(musicBean.getSong_list());
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}

 view层 MainActivity

public class MainActivity extends AppCompatActivity implements IMainActivity{
    private MusicPresenter musicPresenter;
    private ImageView mIv;
    private ImageView mIvBanner;
    private TextView mTvTitle;
    private TextView mTvTime;
    private TextView mTvContent;
    private RecyclerView mRv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        musicPresenter = new MusicPresenter(this);
        //一进页面就请求数据
        musicPresenter.getMusic(offset + "");

        mRv.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initView() {
        mIv = (ImageView) findViewById(R.id.iv);
        mIvBanner = (ImageView) findViewById(R.id.iv_banner);
        mTvTitle = (TextView) findViewById(R.id.tvTitle);
        mTvTime = (TextView) findViewById(R.id.tvTime);
        mTvContent = (TextView) findViewById(R.id.tvContent);
        mRv = (RecyclerView) findViewById(R.id.rv);
    }

    @Override
    public void showBannerIv(String imgUrl) {
        ImageLoader.getInstance().displayImage(imgUrl,mIvBanner);
    }

    @Override
    public void showRv(List<MusicBean.SongListBean> list) {
        MyAdapter myAdapter = new MyAdapter(this, list);
        mRv.setAdapter(myAdapter);
    }
}

IMainActivity

public interface IMainActivity {
    public void showBannerIv(String imgUrl);
    public void showRv(List<MusicBean.SongListBean> list);
}

  适配器adapter下    MyAdapter


public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private Context context;
    private List<MusicBean.SongListBean> list;

    public MyAdapter(Context context, List<MusicBean.SongListBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MusicBean.SongListBean songListBean = list.get(position);
        MyViewHolder myViewHolder = (MyViewHolder) holder;
        ImageLoader.getInstance().displayImage(songListBean.getPic_big(), myViewHolder.iv);
        myViewHolder.tvTop.setText(songListBean.getAuthor());
        myViewHolder.tv_bottom.setText(songListBean.getSi_proxycompany());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{
        private final ImageView iv;
        private final TextView tvTop;
        private final TextView tv_bottom;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv= (ImageView) itemView.findViewById(R.id.iv_item);
            tvTop= (TextView) itemView.findViewById(R.id.tv_top);
            tv_bottom= (TextView) itemView.findViewById(R.id.tv_bottom);
        }
    }
}

app包下 MyApp

public class MyApp extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(configuration);
    }
}

  布局layout    主界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="bwie.com.zhoukao2.view.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#ff3360">

        <ImageView
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@mipmap/ic_launcher" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@id/iv"
            android:text="百度热歌榜" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_banner"
            android:layout_width="150dp"
            android:layout_height="150dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tvTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/tvTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/tvContent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>

  item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="80dp">

    <ImageView
        android:id="@+id/iv_item"
        android:layout_width="60dp"
        android:layout_height="60dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv_bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

  AndroidManifest.xml配置

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:name=".app.MyApp"

  

 

以上是关于mvp+RecyclerView实现网络请求的主要内容,如果未能解决你的问题,请参考以下文章

MVP实战心得—封装Retrofit2.0+RxAndroid+RxBus

markdown RecyclerView最佳实践(传统,非MVP方法)

轻松搞定 android MVP 架构okHttp 网络模块封装 的 项目

轻松搞定 android MVP 架构okHttp 网络模块封装 的 项目

Kevin Learn RecyclerView--> Retrofit + RxJava + OkHttp 网络请求

Kotlin 用Retrofit+OkHttp+协程+LiveData搭建MVVM(Jetpack)来实现网络请求(网络数据JSON解析)显示在RecyclerView(更新中)