拦截器——okhttp(post)+recyclerView显示数据

来源:互联网 发布:网络宣传要会什么 编辑:程序博客网 时间:2024/05/29 12:52

Activity布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_order"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

</LinearLayout>

item_order布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/ll_orer_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:orientation="vertical">

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

        <Button
            android:id="@+id/btn_see_order"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查看订单" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/ll_orer_status"
        android:orientation="vertical">

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

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

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


    </LinearLayout>


</RelativeLayout>
分装的okhttp(post)请求

public class OkHttpUtils {
    private static volatile OkHttpUtils instance;

    private OkHttpClient client;

    private Handler handler = new Handler();

    private OkHttpUtils() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new MyInterceptor())
                .build();
    }

    public static OkHttpUtils getInstance() {
        if (null == instance) {
            synchronized (OkHttpUtils.class) {
                if (instance == null) {
                    instance = new OkHttpUtils();
                }
            }
        }
        return instance;
    }

    public void post(String url, Map<String, Object> map, final CallBack callBack, final Class cls) {
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                builder.add(entry.getKey(), (String) entry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();

                final Object o = GsonUtils.getInstance().fromJson(result, cls);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onSuccess(o);
                    }
                });
            }
        });
    }
}

====================================
public class GsonUtils {
    private static Gson instance;

    private GsonUtils() {

    }

    public static Gson getInstance() {
        if (instance == null) {
            instance = new Gson();
        }

        return instance;
    }
}
=====================

public interface CallBack {
    void onSuccess(Object o);

    void onFailed(Exception e);
}

======================

自定义拦截器


public class MyInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        Request newRequest = chain.request().newBuilder()
                .addHeader("source", "android")
                .url(request.url())
                .build();


        return chain.proceed(newRequest);
    }
}

=======================

适配器类


public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
    private Context context;
    private List<Order> list;

    public OrderAdapter(Context context, List<Order> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = View.inflate(context, R.layout.item_order, null);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        int status = list.get(position).getStatus();

        switch (status) {
            case 0:
                holder.txtStatus.setText("已取消");
                break;

            case 1:
                holder.txtStatus.setText("待支付");

                break;

            case 2:
                holder.txtStatus.setText("已支付");

                break;
        }
        holder.txtTitle.setText(list.get(position).getTitle());
        holder.txtPrice.setText(list.get(position).getPrice() + "");
        holder.txtTime.setText(list.get(position).getCreatetime());
    }

    @Override
    public int getItemCount() {
        if (list == null) {
            return 0;
        }
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView txtStatus;
        private TextView txtTitle;
        private TextView txtPrice;
        private TextView txtTime;
        private Button btnSee;


        public ViewHolder(View itemView) {
            super(itemView);

            txtStatus = (TextView) itemView.findViewById(R.id.txt_order_status);
            txtTitle = (TextView) itemView.findViewById(R.id.txt_order_title);
            txtPrice = (TextView) itemView.findViewById(R.id.txt_order_price);
            txtTime = (TextView) itemView.findViewById(R.id.txt_order_time);
            btnSee = (Button) itemView.findViewById(R.id.btn_see_order);

        }
    }
}

=========================


public interface IView {
    void success(List<Order> orders);

    void failed(Exception e);
}

=====================

presenter


public class OrderPresenter {
    private IView iv;

    public void attachView(IView iv) {
        this.iv = iv;
    }

    public void getOrders(String id) {
        String url = "https://www.zhaoapi.cn/product/getOrders";

        Map<String, Object> map = new HashMap<>();

        map.put("uid", id);
        OkHttpUtils.getInstance().post(url, map, new CallBack() {
            @Override
            public void onSuccess(Object o) {
                MessageBean bean = (MessageBean) o;
                List<Order> data = bean.getData();
                if (null != data) {
                    iv.success(data);
                }
            }

            @Override
            public void onFailed(Exception e) {
                iv.failed(e);
            }
        }, MessageBean.class);
    }

    public void detachView() {
        if (null != iv) {
            iv = null;
        }
    }
}

==========================

mainActivity


public class MainActivity extends AppCompatActivity implements IView {
    private RecyclerView rvOrder;

    private OrderAdapter adapter;
    private List<Order> list;

    private OrderPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rvOrder = (RecyclerView) findViewById(R.id.rv_order);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvOrder.setLayoutManager(manager);

        list = new ArrayList<>();

        adapter = new OrderAdapter(this, list);

        rvOrder.setAdapter(adapter);

        presenter = new OrderPresenter();
        presenter.attachView(this);

        presenter.getOrders("71");

    }

    @Override
    public void success(List<Order> orders) {
        list.clear();
        list.addAll(orders);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void failed(Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (presenter != null) {
            presenter.detachView();
        }
    }
}


阅读全文
0 0