okhttp简单请求数据,列表切换展示
来源:互联网 发布:淘宝标题优化技巧步骤 编辑:程序博客网 时间:2024/05/17 02:04
//导入需要的依赖compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.google.code.gson:gson:2.8.2' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' compile 'com.liaoinstan.springview:library:1.2.6' compile 'com.github.bumptech.glide:glide:3.7.0'//布局的切换需要使用线性布局管理器和表格布局管理器,在主方法中进行切换变更操作//因为涉及到网络请求首先把工具类okhttp封装好 添加拦截器//拦截器import java.io.IOException;import okhttp3.Interceptor;import okhttp3.Request;import okhttp3.Response;public class MyInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); String s = request.url().url().toString(); String url = s + "&source=android"; Request request1 = request.newBuilder().url(url).build(); Response response = chain.proceed(request1); return response; }}//封装okhttp并添加拦截器import java.util.Map;import java.util.concurrent.TimeUnit;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;public class OkHttpUtils { private static OkHttpUtils okHttpUtils; private static OkHttpClient client; private Request request; public OkHttpUtils(){ } public static OkHttpUtils getInstance(){ if (okHttpUtils == null){ okHttpUtils = new OkHttpUtils(); client = new OkHttpClient.Builder() .addInterceptor(new MyInterceptor()) .readTimeout(20, TimeUnit.SECONDS) .connectTimeout(20, TimeUnit.SECONDS) .build(); } return okHttpUtils; } //get请求 public void doGet(String url, Callback callback){ request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(callback); } //post请求 public void doPost(String url, Map<String,String> params,Callback callback){ if (params == null){ throw new RuntimeException("参数为空"); }else{ 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); } }}//首先是主方法布局<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="com.example.mydemo2.MainActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_marginLeft="150dp" android:gravity="center" android:layout_width="wrap_content" android:layout_height="70dp" android:text="搜索商品" android:textSize="22sp" /> <Button android:layout_marginLeft="80dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切换" android:id="@+id/btn_activity" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000" /> <LinearLayout android:layout_marginLeft="50dp" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入搜索的商品" android:id="@+id/edit_activity" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="搜索" android:id="@+id/search_activity" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000" /> <com.liaoinstan.springview.widget.SpringView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/springview" > <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recycler_activity" > </android.support.v7.widget.RecyclerView> </com.liaoinstan.springview.widget.SpringView></LinearLayout>//主方法代码import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import com.example.mydemo2.adapter.MyRecyclerAdapter;import com.example.mydemo2.bean.DataDataBean;import com.example.mydemo2.presenter.MyPresenter;import com.example.mydemo2.presenter.PresenterListener;import com.liaoinstan.springview.container.DefaultFooter;import com.liaoinstan.springview.container.DefaultHeader;import com.liaoinstan.springview.widget.SpringView;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements PresenterListener{ private Button mBtnActivity; private EditText mEditActivity; private Button mSearchActivity; private SpringView mSpringview; private RecyclerView mRecyclerActivity; private MyPresenter myPresenter; private List<DataDataBean.DataBean> list = new ArrayList<>(); boolean flag = true; String name=""; //因为涉及到添加,此处为你需要添加的查询条件 private int num = 1; private MyRecyclerAdapter myRecyclerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); myPresenter = new MyPresenter(this); String s = String.valueOf(num); myPresenter.getData(name,s); //设置适配器 setAdapter(); mSearchActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(mEditActivity.getText().toString())){ Toast.makeText(MainActivity.this,mEditActivity.getText().toString(),Toast.LENGTH_SHORT).show(); myPresenter.getData(mEditActivity.getText().toString(),"1"); setAdapter(); } } }); mBtnActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (flag == false){ flag = true; mRecyclerActivity.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,list,flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); myRecyclerAdapter.notifyDataSetChanged(); }else { flag =false; mRecyclerActivity.setLayoutManager(new GridLayoutManager(MainActivity.this,2)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,list,flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); myRecyclerAdapter.notifyDataSetChanged(); } } }); mSpringview.setHeader(new DefaultHeader(this)); mSpringview.setFooter(new DefaultFooter(this)); mSpringview.setListener(new SpringView.OnFreshListener() { @Override public void onRefresh() { myPresenter.getData(name,"1"); setAdapter(); mSpringview.onFinishFreshAndLoad(); } @Override public void onLoadmore() { num++; String s1 = String.valueOf(num); myPresenter.getData(name,s1); Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); setAdapter(); mSpringview.onFinishFreshAndLoad(); } }); } private void setAdapter() { if (myRecyclerAdapter == null){ mRecyclerActivity.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL,false)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this, list, flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); }else{ myRecyclerAdapter.notifyDataSetChanged(); } } private void initView() { mBtnActivity = findViewById(R.id.btn_activity); mEditActivity = findViewById(R.id.edit_activity); mSearchActivity = findViewById(R.id.search_activity); mSpringview = findViewById(R.id.springview); mRecyclerActivity = findViewById(R.id.recycler_activity); } @Override public void success(List<DataDataBean.DataBean> data) { for (int i = 0;i<data.size();i++){ list.add(data.get(i)); } setAdapter(); } @Override public void failed(Exception e) { } @Override protected void onDestroy() { super.onDestroy(); myPresenter.detach(); }}//因为使用的mvp 涉及到交互//p层接口 回调import com.example.mydemo2.bean.DataDataBean;import java.util.List;public interface PresenterListener { void success( List<DataDataBean.DataBean> data); void failed(Exception e);}//p层主数据import android.os.Handler;import com.example.mydemo2.bean.DataDataBean;import com.example.mydemo2.model.ModuleListeren;import com.example.mydemo2.model.MyModel;import com.google.gson.Gson;import java.util.List;public class MyPresenter { private MyModel myModel; PresenterListener presenterListener; Handler handler = new Handler(); public MyPresenter(PresenterListener presenterListener){ this.presenterListener = presenterListener; myModel = new MyModel(); } public void getData(String name,String page){ myModel.getData(name, page, new ModuleListeren() { @Override public void success(String response) { DataDataBean dataDataBean = new Gson().fromJson(response, DataDataBean.class); final List<DataDataBean.DataBean> data = dataDataBean.getData(); handler.post(new Runnable() { @Override public void run() { if (presenterListener != null){ presenterListener.success(data); } } }); } @Override public void failed(Exception e) { presenterListener = null; } }); } //内存泄漏 public void detach(){ presenterListener = null; }}//modelc层 接口 和主数据public interface ModuleListeren { //成功 void success(String response); //失败 void failed(Exception e);}//主数据import com.example.mydemo2.okhttp.OkHttpUtils;import java.io.IOException;import okhttp3.Call;import okhttp3.Callback;import okhttp3.Response;public class MyModel { public void getData(String name, String page, final ModuleListeren moduleListeren){ String url="http://120.27.23.105/product/searchProducts?keywords="+name+"&page="+page; OkHttpUtils.getInstance().doGet(url, new Callback() { @Override public void onFailure(Call call, IOException e) { if (moduleListeren != null){ moduleListeren.failed(e); } } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); if (moduleListeren != null){ moduleListeren.success(string); } } }); }}//切换需要适配器import android.content.Context;import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import com.bumptech.glide.Glide;import com.example.mydemo2.MainActivity;import com.example.mydemo2.R;import com.example.mydemo2.bean.DataDataBean;import java.util.List;public class MyRecyclerAdapter extends RecyclerView.Adapter{ List<DataDataBean.DataBean> list; Context context; boolean flag=true; public MyRecyclerAdapter(Context context, List<DataDataBean.DataBean> list,boolean flag) { this.list = list; this.flag = flag; this.context=context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if(flag){ View view = View .inflate(context, R.layout.item1,null); return new ViewHolder1(view); }else{ View view = View .inflate(context, R.layout.item2,null); return new ViewHolder2(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if(flag){ if(holder instanceof ViewHolder1){ ViewHolder1 holder1= (ViewHolder1) holder; holder1.textView01.setText(list.get(position).getTitle()); holder1.textView02.setText("价格:"+list.get(position).getPrice()); String[] split = list.get(position).getImages().split("\\|"); Glide.with(context).load(split[0]).into(holder1.imageView); } }else{ if(holder instanceof ViewHolder2){ ViewHolder2 holder2= (ViewHolder2) holder; holder2.textView01.setText(list.get(position).getTitle()); holder2.textView02.setText("价格:"+list.get(position).getPrice()); String[] split = list.get(position).getImages().split("\\|"); Glide.with(context).load(split[0]).into(holder2.imageView); } } } @Override public int getItemCount() { return list.size(); } class ViewHolder1 extends RecyclerView.ViewHolder{ ImageView imageView; TextView textView01; TextView textView02; public ViewHolder1(View itemView) { super(itemView); imageView = itemView.findViewById(R.id.image_recyclerview); textView01 = itemView.findViewById(R.id.title_recyclerview); textView02 = itemView.findViewById(R.id.price_recyclerview); } } class ViewHolder2 extends RecyclerView.ViewHolder{ ImageView imageView; TextView textView01; TextView textView02; public ViewHolder2(View itemView) { super(itemView); imageView = itemView.findViewById(R.id.image_recyclerview); textView01 = itemView.findViewById(R.id.title_recyclerview); textView02 = itemView.findViewById(R.id.price_recyclerview); } }}//适配的两条布局 Item1条目 item2表格//item<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:layout_width="100dp" android:src="@mipmap/ic_launcher" android:layout_height="100dp" android:id="@+id/image_recyclerview" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/title_recyclerview" android:text="标题" android:padding="20dp" /> <TextView android:textColor="#ff0000" android:padding="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/price_recyclerview" android:text="价格" /> </LinearLayout> //item2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:layout_width="100dp" android:src="@mipmap/ic_launcher" android:layout_height="100dp" android:id="@+id/image_recyclerview" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/title_recyclerview" android:text="标题" android:padding="10dp" /> <TextView android:textColor="#ff0000" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/price_recyclerview" android:text="价格" /> </LinearLayout></LinearLayout>//主布局<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="com.example.mydemo2.MainActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_marginLeft="150dp" android:gravity="center" android:layout_width="wrap_content" android:layout_height="70dp" android:text="搜索商品" android:textSize="22sp" /> <Button android:layout_marginLeft="80dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切换" android:id="@+id/btn_activity" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000" /> <LinearLayout android:layout_marginLeft="50dp" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:layout_width="200dp" android:layout_height="wrap_content" android:hint="请输入搜索的商品" android:id="@+id/edit_activity" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="搜索" android:id="@+id/search_activity" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000" /> <com.liaoinstan.springview.widget.SpringView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/springview" > <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recycler_activity" > </android.support.v7.widget.RecyclerView> </com.liaoinstan.springview.widget.SpringView></LinearLayout>//MainActivityimport android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import com.example.mydemo2.adapter.MyRecyclerAdapter;import com.example.mydemo2.bean.DataDataBean;import com.example.mydemo2.presenter.MyPresenter;import com.example.mydemo2.presenter.PresenterListener;import com.liaoinstan.springview.container.DefaultFooter;import com.liaoinstan.springview.container.DefaultHeader;import com.liaoinstan.springview.widget.SpringView;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements PresenterListener{ private Button mBtnActivity; private EditText mEditActivity; private Button mSearchActivity; private SpringView mSpringview; private RecyclerView mRecyclerActivity; private MyPresenter myPresenter; private List<DataDataBean.DataBean> list = new ArrayList<>(); boolean flag = true; String name=""; //因为涉及到添加,此处为你需要添加的查询条件 private int num = 1; private MyRecyclerAdapter myRecyclerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); myPresenter = new MyPresenter(this); String s = String.valueOf(num); myPresenter.getData(name,s); //设置适配器 setAdapter(); mSearchActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(mEditActivity.getText().toString())){ Toast.makeText(MainActivity.this,mEditActivity.getText().toString(),Toast.LENGTH_SHORT).show(); myPresenter.getData(mEditActivity.getText().toString(),"1"); setAdapter(); } } }); mBtnActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (flag == false){ flag = true; mRecyclerActivity.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,list,flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); myRecyclerAdapter.notifyDataSetChanged(); }else { flag =false; mRecyclerActivity.setLayoutManager(new GridLayoutManager(MainActivity.this,2)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this,list,flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); myRecyclerAdapter.notifyDataSetChanged(); } } }); mSpringview.setHeader(new DefaultHeader(this)); mSpringview.setFooter(new DefaultFooter(this)); mSpringview.setListener(new SpringView.OnFreshListener() { @Override public void onRefresh() { myPresenter.getData(name,"1"); setAdapter(); mSpringview.onFinishFreshAndLoad(); } @Override public void onLoadmore() { num++; String s1 = String.valueOf(num); myPresenter.getData(name,s1); Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); setAdapter(); mSpringview.onFinishFreshAndLoad(); } }); } private void setAdapter() { if (myRecyclerAdapter == null){ mRecyclerActivity.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL,false)); myRecyclerAdapter = new MyRecyclerAdapter(MainActivity.this, list, flag); mRecyclerActivity.setAdapter(myRecyclerAdapter); }else{ myRecyclerAdapter.notifyDataSetChanged(); } } private void initView() { mBtnActivity = findViewById(R.id.btn_activity); mEditActivity = findViewById(R.id.edit_activity); mSearchActivity = findViewById(R.id.search_activity); mSpringview = findViewById(R.id.springview); mRecyclerActivity = findViewById(R.id.recycler_activity); } @Override public void success(List<DataDataBean.DataBean> data) { for (int i = 0;i<data.size();i++){ list.add(data.get(i)); } setAdapter(); } @Override public void failed(Exception e) { } @Override protected void onDestroy() { super.onDestroy(); myPresenter.detach(); }}//因为涉及到网络 切记不要忘了网络权限
阅读全文
0 0
- okhttp简单请求数据,列表切换展示
- OkHttp请求网络数据,并listview展示
- MVP模式OKhttp请求RecyclerView展示数据
- OkHttp+RecyclerView,利用OkHttp请求数据,并RecyclerView展示
- OkHttp简单的请求数据
- 简单的表格列表切换展示
- Android---------通过OkHttp网络请求利用RecyclerView展示数据
- OkHttp请求数据到RecyclerView多条目展示
- MVP注册登录+OkHttp网络请求+展示数据
- MVP架构分包+OkHttp网络请求+RecyclerView展示数据
- MVP-简单的OkHttp网络请求数据
- 简单MVP框架(OKHTTP请求数据)
- Retrofit+RxJava+Okhttp+RecycleView+MVP简单的展示数据
- 网络请求数据添加到列表(okhttp+RecyclerView)
- 二级列表展示网络请求到的数据
- 二级列表ExpandableListView+gridview网络请求数据模拟商城展示
- RecyclerView+OkHttp展示网络数据
- OkHttp简单的请求
- 华侨城大剧院之《金面王朝》
- DrawerLayout的布局
- 查询添加用户
- 淘宝分类
- DrawerLayout的代码
- okhttp简单请求数据,列表切换展示
- 第一个综合题布局
- 第一个综合题的MainActivity
- MVP+okhttp仿搜索
- 蓝牙应用
- QQ 第三方登录
- 第一个综合题的fragment
- NAT笔记
- netty编解码之jboss marshalling