资讯_PullToRefreshListView,Http,圆角,本地缓存,数据库,基类,图片缓存

raymundoborders 计算机知识 33 次浏览 没有评论

依赖

implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' 

权限

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.demo100">      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />      <application         android:name=".app.App"         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <activity android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>  </manifest> 

MainActivity基类

package com.example.demo100;  import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View;  /**  * @Auther: 努力  * @Date: 2019/1/17 15:28:${卢文杰}  * @Description:  */ public abstract class BaseActivity extends AppCompatActivity {      @Override     protected void onCreate(@Nullable Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(bindlayout());         initView();         initData();         bindEvent();     }      protected abstract int bindlayout();      protected abstract void initView();      protected abstract void initData();      protected abstract void bindEvent();      protected <T extends View> T bindView(int resId) {         return (T) findViewById(resId);     }  }  

Http工具类

package com.example.demo100.http;  import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask;  import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL;  /**  * @Auther: 努力  * @Date: 2019/1/17 15:41:${卢文杰}  * @Description:  */ public class Http {      public static boolean isNetworkHttp(Context context) {          ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);          NetworkInfo info = connectivityManager.getActiveNetworkInfo();          if (info != null) {             return info.isAvailable();         }          return false;     }      public static void HttpAsyncTask(String strUrl, final CallBackS callBackS) {         new AsyncTask<String, Integer, String>() {             @Override             protected String doInBackground(String... strings) {                 return requestHttp(strings[0]);             }              @Override             protected void onPostExecute(String s) {                 super.onPostExecute(s);                 callBackS.getData(s);             }         }.execute(strUrl);     }      public interface CallBackS {         void getData(String s);     }      public static String requestHttp(String strUrl) {          try {              URL url = new URL(strUrl);              HttpURLConnection connection = (HttpURLConnection) url.openConnection();              connection.setRequestMethod("GET");              connection.setConnectTimeout(5000);              connection.setReadTimeout(5000);              int code = connection.getResponseCode();              if (code == HttpURLConnection.HTTP_OK) {                  InputStream stream = connection.getInputStream();                  BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));                  StringBuilder builder = new StringBuilder();                  String str = "";                  while ((str = reader.readLine()) != null) {                      builder.append(str);                  }                  return builder.toString();             }              connection.disconnect();          } catch (Exception e) {             e.printStackTrace();         }          return null;     }  }  

MainActivity布局

<?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=".MainActivity">        <android.support.v4.widget.DrawerLayout         android:id="@+id/drawer"         android:layout_width="match_parent"         android:layout_height="match_parent">          <LinearLayout             android:layout_width="match_parent"             android:layout_height="match_parent"             android:orientation="vertical">              <com.handmark.pulltorefresh.library.PullToRefreshListView                 android:id="@+id/pull"                 android:layout_width="match_parent"                 android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>          </LinearLayout>          <LinearLayout             android:layout_width="350dp"             android:layout_height="match_parent"             android:layout_gravity="left"             android:background="#fff"             android:orientation="vertical">              <ImageView                 android:id="@+id/image_cl"                 android:layout_width="150dp"                 android:layout_height="150dp"                 android:layout_marginLeft="95dp"                 android:src="@mipmap/ic_launcher" />              <ListView                 android:id="@+id/listview_cl"                 android:layout_width="match_parent"                 android:layout_height="match_parent"                 android:layout_marginTop="20dp" />         </LinearLayout>     </android.support.v4.widget.DrawerLayout>   </LinearLayout> 

MainActivity

package com.example.demo100;  import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast;  import com.example.demo100.adapter.MyAdapter; import com.example.demo100.app.App; import com.example.demo100.bean.JsonBean; import com.example.demo100.http.Http; import com.example.demo100.sqlite.Dao; import com.google.gson.Gson; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader;  import java.util.ArrayList; import java.util.List;  public class MainActivity extends BaseActivity {       private PullToRefreshListView pull;     private String str = "接口";     private List<JsonBean.DataBean> data;     private Dao dao;     private Cursor person;     private MyAdapter myAdapter;     private DrawerLayout drawerLayout;     private ImageView imageView;     private ListView listView;     private String sa = "http://f.expoon.com/sub/news/2016/01/21/887844_230x162_0.jpg";      @Override     protected int bindlayout() {         return R.layout.activity_main;     }      @Override     protected void initView() {         pull = bindView(R.id.pull);         drawerLayout = bindView(R.id.drawer);         imageView = bindView(R.id.image_cl);         listView = bindView(R.id.listview_cl);         dao = new Dao(MainActivity.this);     }      @Override     protected void initData() {          pull.setMode(PullToRefreshListView.Mode.BOTH);         pull.setScrollingWhileRefreshingEnabled(true);          drawerLayout.openDrawer(Gravity.LEFT);         drawerLayout.closeDrawer(Gravity.LEFT);          DisplayImageOptions options =  App.getDisplayImageOptions2();         ImageLoader.getInstance().displayImage(sa,imageView,options);          if (Http.isNetworkHttp(MainActivity.this)) {             Http.HttpAsyncTask(str, new Http.CallBackS() {                 @Override                 public void getData(String s) {                     Gson gson = new Gson();                     JsonBean jsonBean = gson.fromJson(s, JsonBean.class);                     List<JsonBean.DataBean> arraylist = jsonBean.getData();                     listView.setAdapter(new MyAdapter(MainActivity.this, arraylist));                 }             });         } else {             Toast.makeText(MainActivity.this, "没网了", Toast.LENGTH_LONG).show();         }           if (Http.isNetworkHttp(MainActivity.this)) {             Http.HttpAsyncTask(str, new Http.CallBackS() {                 @Override                 public void getData(String s) {                     gsonJx(s);                 }             });         } else {             person = dao.query("person", null, null, null, null, null, null);             data = new ArrayList<>();             if (person.moveToFirst()) {                 do {                     String news_title = person.getString(person.getColumnIndex("news_title"));                     String news_summary = person.getString(person.getColumnIndex("news_summary"));                     String pic_url = person.getString(person.getColumnIndex("pic_url"));                     data.add(new JsonBean.DataBean(news_title, news_summary, pic_url));                 } while (person.moveToNext());             }             person.close();             Toast.makeText(MainActivity.this, "没网了", Toast.LENGTH_LONG).show();             myAdapter = new MyAdapter(MainActivity.this, data);             pull.setAdapter(myAdapter);         }     }      private void gsonJx(String s) {         Gson gson = new Gson();         JsonBean jsonBean = gson.fromJson(s, JsonBean.class);         data = jsonBean.getData();         person = dao.query("person", null, null, null, null, null, null);         if (person.moveToFirst()) {          } else {              for (JsonBean.DataBean bean : data) {                 ContentValues values = new ContentValues();                 values.put("news_title", bean.getNews_title());                 values.put("news_summary", bean.getNews_summary());                 values.put("pic_url", bean.getPic_url());                 dao.add("person", null, values);             }         }         myAdapter = new MyAdapter(MainActivity.this, data);         pull.setAdapter(myAdapter);      }      @Override     protected void bindEvent() {         pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {             @Override             public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {                 if (Http.isNetworkHttp(MainActivity.this)) {                     Http.HttpAsyncTask(str, new Http.CallBackS() {                         @Override                         public void getData(String s) {                             gsonJx(s);                         }                     });                 } else {                     Toast.makeText(MainActivity.this, "没网了", Toast.LENGTH_LONG).show();                 }                 pull.onRefreshComplete();             }              @Override             public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {                 if (Http.isNetworkHttp(MainActivity.this)) {                     Http.HttpAsyncTask(str, new Http.CallBackS() {                         @Override                         public void getData(String s) {                             Gson gson = new Gson();                             JsonBean jsonBean = gson.fromJson(s, JsonBean.class);                             List<JsonBean.DataBean> list = jsonBean.getData();                             data.addAll(list);                             myAdapter.notifyDataSetChanged();                         }                     });                 } else {                     Toast.makeText(MainActivity.this, "没网了", Toast.LENGTH_LONG).show();                 }                 pull.onRefreshComplete();             }         });          drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {             @Override             public void onDrawerSlide(@NonNull View view, float v) {              }              @Override             public void onDrawerOpened(@NonNull View view) {              }              @Override             public void onDrawerClosed(@NonNull View view) {              }              @Override             public void onDrawerStateChanged(int i) {              }         });      } }  

item_01布局

<?xml version="1.0" encoding="utf-8"?> <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:id="@+id/m0"         android:layout_width="150dp"         android:layout_height="150dp"         android:src="@mipmap/ic_launcher" />      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">          <TextView             android:id="@+id/t0"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="hh"             android:textSize="16sp" />          <TextView             android:id="@+id/t1"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="hh"             android:textSize="14sp" />     </LinearLayout>  </LinearLayout> 

Myadapter页面

package com.example.demo100.adapter;  import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView;  import com.example.demo100.R; import com.example.demo100.app.App; import com.example.demo100.bean.JsonBean; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader;  import java.util.List;  /**  * @Auther: 努力  * @Date: 2019/1/17 19:36:${卢文杰}  * @Description:  */ public class MyAdapter extends BaseAdapter {      private Context context;     private List<JsonBean.DataBean> list;      public MyAdapter(Context context, List<JsonBean.DataBean> list) {         this.context = context;         this.list = list;     }      @Override     public int getCount() {         return list.size();     }      @Override     public Object getItem(int position) {         return null;     }      @Override     public long getItemId(int position) {         return 0;     }      @Override     public View getView(int position, View convertView, ViewGroup parent) {         ViewHolder holder;         if (convertView == null){             convertView = LayoutInflater.from(context).inflate(R.layout.item_01,null);             holder = new ViewHolder();             holder.t0 = convertView.findViewById(R.id.t0);             holder.t1 = convertView.findViewById(R.id.t1);             holder.m0 = convertView.findViewById(R.id.m0);             convertView.setTag(holder);         }else{             holder = (ViewHolder) convertView.getTag();         }         JsonBean.DataBean dataBean = list.get(position);         holder.t0.setText(dataBean.getNews_title());         holder.t1.setText(dataBean.getNews_summary());         DisplayImageOptions options = new App().getDisplayImageOptions();         ImageLoader.getInstance().displayImage(dataBean.getPic_url(),holder.m0,options);         return convertView;     }     static class ViewHolder{         TextView t0,t1;         ImageView m0;     } }  

SQLite页面

package com.example.demo100.sqlite;          import android.content.Context;         import android.database.sqlite.SQLiteDatabase;         import android.database.sqlite.SQLiteOpenHelper;  /**  * @Auther: 努力  * @Date: 2019/1/17 15:57:${卢文杰}  * @Description:  */ public class Mysqlite extends SQLiteOpenHelper {     public Mysqlite(Context context) {         super(context, "news.db", null, 1);     }          @Override     public void onCreate(SQLiteDatabase db) {         db.execSQL("create table person(id INTEGER PRIMARY KEY AUTOINCREMENT,news_title text,news_summary text,pic_url text)");     }      @Override     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {      } }  

Dao

package com.example.demo100.sqlite;  import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;  /**  * @Auther: 努力  * @Date: 2019/1/17 16:00:${卢文杰}  * @Description:  */ public class Dao {      private final SQLiteDatabase db;      public Dao(Context context) {         Mysqlite mysqlite = new Mysqlite(context);         db = mysqlite.getWritableDatabase();     }      public long add(String table, String nullColumnHack, ContentValues values) {         return db.insert(table, nullColumnHack, values);     }      public long delete(String table, String whereClause, String[] whereArgs){         return db.delete(table,whereClause,whereArgs);     }      public long update(String table, ContentValues values, String whereClause, String[] whereArgs){         return db.update(table,values,whereClause,whereArgs);     }      public Cursor query(String table, String[] columns, String selection,                         String[] selectionArgs, String groupBy, String having,                         String orderBy) {         return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);     }  }  

App页面

package com.example.demo100.app;  import android.app.Application; import android.os.Environment;  import com.example.demo100.R; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;  import java.io.File;  /**  * @Auther: 努力  * @Date: 2019/1/17 20:32:${卢文杰}  * @Description:  */ public class App extends Application {     @Override     public void onCreate() {         super.onCreate();         String path = Environment.getExternalStorageDirectory().getPath() + "/RiKao13";         File file = new File(path);          ImageLoaderConfiguration loader = new ImageLoaderConfiguration.Builder(this)                 .memoryCacheExtraOptions(200, 200)//配置内存缓存图片的尺寸                 .memoryCacheSize(2 * 1024 * 1024)//配置内存缓存的大小                 .threadPoolSize(3)//配置加载图片的线程数                 .threadPriority(1000)//配置线程的优先级                 .diskCache(new UnlimitedDiskCache(file))//UnlimitedDiskCache 限制这个图片的缓存路径                 .diskCacheFileCount(50)//配置sdcard缓存文件的数量                 .diskCacheFileNameGenerator(new Md5FileNameGenerator())//MD5这种方式生成缓存文件的名字                 .diskCacheSize(50 * 1024 * 1024)//在sdcard缓存50MB                 .build();          //获得实例         ImageLoader imageLoader = ImageLoader.getInstance();          ImageLoader.getInstance().init(loader);      }      public static DisplayImageOptions getDisplayImageOptions() {         DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()                 .showImageOnLoading(R.mipmap.zhan)                 .showImageForEmptyUri(R.mipmap.zhaobudao)                 .showImageOnFail(R.mipmap.shibai)                 .build();         return displayImageOptions;     }      public static DisplayImageOptions getDisplayImageOptions2() {         DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()                 .showImageOnLoading(R.mipmap.zhan)                 .showImageForEmptyUri(R.mipmap.zhaobudao)                 .showImageOnFail(R.mipmap.shibai)                 .displayer(new RoundedBitmapDisplayer(360))                 .build();         return displayImageOptions;     }  }  

效果图
资讯_PullToRefreshListView,Http,圆角,本地缓存,数据库,基类,图片缓存
资讯_PullToRefreshListView,Http,圆角,本地缓存,数据库,基类,图片缓存
资讯_PullToRefreshListView,Http,圆角,本地缓存,数据库,基类,图片缓存

内容如有侵犯你的权益,请联系删除

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Go