OkHttp+Xrecyclerview
来源:互联网 发布:c语言中整型变量 编辑:程序博客网 时间:2024/05/16 10:31
1、这篇文章主要应用的是Okhttp请求网络数据解析Gson,判断网络,没有网络跳转到设置界面,然后通过XRecyclerView展示到页面中。并且可以实现全局捕获异常,加载图片实现属性动画渐变的效果。
2、导入依赖
compile 'com.squareup.okhttp:okhttp:2.4.0'compile 'io.github.openfeign:feign-gson:9.5.1'compile 'com.github.bumptech.glide:glide:3.8.0'compile 'com.jcodecraeer:xrecyclerview:1.3.2'这四个依赖分别是okhttp的依赖、Gson的依赖、图片加载Glide的依赖、XrecyclerView的依赖
3、配置权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET"></uses-permission>这两个权限分别是编写的权限跟联网的权限
4、MainActivity中的布局,只需要布一个XrecyclerView的布局就可以了
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <com.jcodecraeer.xrecyclerview.XRecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="match_parent" ></com.jcodecraeer.xrecyclerview.XRecyclerView></RelativeLayout>5、MainActicity中的数据
import android.animation.ObjectAnimator;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.LinearLayoutManager;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import com.bumptech.glide.Glide;import com.google.gson.Gson;import com.jcodecraeer.xrecyclerview.XRecyclerView;import com.squareup.okhttp.Callback;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;import java.io.IOException;import java.util.List;public class MainActivity extends AppCompatActivity { private List<Bean.DataBean> list; private XRecyclerView recycler; private String URL = "http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=20&gender=2&ts=1871746850&page="; private int page = 1;//设置首先展示的页面是第一页 private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); String u = (String) msg.obj; Gson gson = new Gson(); Bean bean = gson.fromJson(u, Bean.class); list = bean.getData(); //设置布局管理器 recycler.setLayoutManager(new LinearLayoutManager(MainActivity.this)); //设置适配器 recycler.setAdapter(new MyAdapter()); //分页加的 recycler.setLoadingListener(new XRecyclerView.LoadingListener() { @Override //下拉刷新 public void onRefresh() { page = 1; list.clear(); jiexi(); recycler.refreshComplete(); } @Override //上拉加载 public void onLoadMore() { page++; jiexi(); Toast.makeText(MainActivity.this, "加载更多", Toast.LENGTH_LONG).show(); recycler.loadMoreComplete(); } }); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //判断网络 checkNetwork(); //找控件 initData(); //解析数据 jiexi(); if (!checkNetwork()) { Toast.makeText(this, "没有网络", Toast.LENGTH_LONG).show(); Intent intent = new Intent("android.settings.WIRELESS_SETTINGS"); startActivity(intent); return; } } private void jiexi() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(URL) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { String string = response.body().string(); Log.i("aaa", "run: " + string); Message message = new Message(); message.obj = string; handler.sendMessage(message); } }); } //找到控件 private void initData() { recycler = (XRecyclerView) findViewById(R.id.recycler); } private boolean checkNetwork() { ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo net = conn.getActiveNetworkInfo(); if (net != null && net.isConnected()) { return true; } return false; } class MyAdapter extends XRecyclerView.Adapter<MyAdapter.MyViewHolder> { @Override //绑定布局 public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.name.setText(list.get(position).getTitle()); // holder.old.setText(list.get(position).getUserAge()); Glide.with(MainActivity.this).load(list.get(position).getImg()).into(holder.image); holder.desc.setText(list.get(position).getIntroduction()); holder.job.setText(list.get(position).getOccupation()); //添加属性动画,实现渐变效果。 ObjectAnimator// .ofFloat(holder.image, "alpha",0.0F,1f)// .setDuration(2000)// .start(); } @Override public int getItemCount() { return list.size(); } class MyViewHolder extends XRecyclerView.ViewHolder { public TextView name; public TextView old; public TextView desc; public ImageView image; public TextView job; public MyViewHolder(View itemView) { super(itemView); name = itemView.findViewById(R.id.name); old = itemView.findViewById(R.id.old); desc = itemView.findViewById(R.id.desc); image = itemView.findViewById(R.id.image); job = itemView.findViewById(R.id.job); } } }}6、借助Formate建立一个Bean类
7、全局异常的获取类。记得要在Application中申明这个类
android:name=".MainApplication"
粘贴两个包进去。
7.1
import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.os.Build;import android.os.Environment;import android.os.Looper;import android.util.Log;import android.widget.Toast;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.io.Writer;import java.lang.reflect.Field;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;public class CrashHandler implements Thread.UncaughtExceptionHandler { private static final String TAG = "CrashHandler"; private Thread.UncaughtExceptionHandler mDefaultHandler;// 系统默认的UncaughtException处理类 private static CrashHandler INSTANCE = new CrashHandler();// CrashHandler实例 private Context mContext;// 程序的Context对象 private Map<String, String> info = new HashMap<String, String>();// 用来存储设备信息和异常信息 private SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss");// 用于格式化日期,作为日志文件名的一部分 /** * 保证只有一个CrashHandler实例 */ private CrashHandler() { } /** * 获取CrashHandler实例 ,单例模式 */ public static CrashHandler getInstance() { return INSTANCE; } /** * 初始化 * * @param context */ public void init(Context context) { mContext = context; mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 获取系统默认的UncaughtException处理器 Thread.setDefaultUncaughtExceptionHandler(this);// 设置该CrashHandler为程序的默认处理器 } /** * 当UncaughtException发生时会转入该重写的方法来处理 */ public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果自定义的没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000);// 如果处理了,让程序继续运行3秒再退出,保证文件保存并上传到服务器 } catch (InterruptedException e) { e.printStackTrace(); } // 退出程序 android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex 异常信息 * @return true 如果处理了该异常信息;否则返回false. */ public boolean handleException(Throwable ex) { if (ex == null) return false; new Thread() { public void run() { Looper.prepare(); Toast.makeText(mContext, "出现闪退了正在把日志保存到sdcard crash目录下", Toast.LENGTH_LONG).show(); Looper.loop(); } }.start(); // 收集设备参数信息 collectDeviceInfo(mContext); // 保存日志文件 saveCrashInfo2File(ex); return true; } /** * 收集设备参数信息 * * @param context */ public void collectDeviceInfo(Context context) { try { PackageManager pm = context.getPackageManager();// 获得包管理器 PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);// 得到该应用的信息,即主Activity if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; String versionCode = pi.versionCode + ""; info.put("versionName", versionName); info.put("versionCode", versionCode); } } catch (NameNotFoundException e) { e.printStackTrace(); } Field[] fields = Build.class.getDeclaredFields();// 反射机制 for (Field field : fields) { try { field.setAccessible(true); info.put(field.getName(), field.get("").toString()); Log.d(TAG, field.getName() + ":" + field.get("")); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } private String saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : info.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\r\n"); } Writer writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); ex.printStackTrace(pw); Throwable cause = ex.getCause(); // 循环着把所有的异常信息写入writer中 while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } pw.close();// 记得关闭 String result = writer.toString(); sb.append(result); Log.d("zzz", "错误日志key:" + result); // 保存文件 long timetamp = System.currentTimeMillis(); String time = format.format(new Date()); String fileName = "crash-" + time + "-" + timetamp + ".log"; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { try { File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "crash"); Log.i("CrashHandler", dir.toString()); if (!dir.exists()) dir.mkdir(); FileOutputStream fos = new FileOutputStream(new File(dir, fileName)); fos.write(sb.toString().getBytes()); fos.close(); return fileName; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; }}7.2
import android.app.Application;public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(this); } }8、item的布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="300dp" android:layout_weight="1" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="秦心" android:textSize="20sp" android:textColor="#D1AA47" android:padding="10dp" /> <TextView 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:orientation="horizontal" > <TextView android:id="@+id/old" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="26岁" android:textSize="20sp" android:layout_marginLeft="20dp" android:background="#94D3D6" /> <TextView android:id="@+id/job" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="银行" android:textSize="20sp" android:background="#EFBE42" android:layout_marginLeft="10dp" /> </LinearLayout> <TextView android:id="@+id/desc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="90年/天蝎座" android:textSize="18sp" android:layout_marginTop="10sp" android:layout_marginLeft="15dp" /></LinearLayout>上面就是
阅读全文
0 0
- OkHttp+Xrecyclerview
- An_MVP_模式(okhttp)解析RecyclerView/XRecyclerView
- MVP+Rxjava+Okhttp+Retrofit+XRecyclerview请求数据
- XRecyclerView
- XrecyclerView
- XRecyclerView
- xrecyclerview
- xrecyclerview
- xrecyclerview
- XRecyclerView
- Android实现xrecyclerview+MVP+okhttp一个小案例
- MVP+OKhttp,拦截器+XRecyclerView+ImageLoader(Glide)
- Android——MVP+xRecyclerView+Retrofit+OkHttp+RxJava结合应用
- MVP泛型+xRecyclerView+Retrofit+OkHttp+RxJava多条目,横向
- Mvp+OkHttp+XRecyclerView------上拉加载下拉刷新
- MVP模式的OKhttp请求网络数据,xrecyclerview上拉刷新,下拉加载
- MVP+XRecyclerView+okhttp+glide,列表或者网格显示所加载的数据
- MVP架构分包+OkHttp网络请求数据并展示到xrecyclerview上
- Django mysql数据库支持
- Xshell连接不上阿里云服务器
- 接口调用报表结果
- Python——socket TCP编程
- 计算机网络__知识点集合1
- OkHttp+Xrecyclerview
- RecyclerView侧滑菜单,滑动删除,长按拖拽,下拉刷新上拉加载
- SQL基本概念
- code tips
- 类中static成员初始化
- 奥威Power-BI 医药行业数据分析应用之厂家药品分析
- java面试——springMVC面试题
- ZigBee开发环境搭建
- 《在C#中实现Socket端口复用》 以及《 UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断。》问题