版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Haihao_micro/article/details/52074727
临时存储三种类型的数据类:
/**
* PreferenceUtil: 存储临时数据到本地内存中
*
* @author micro
*
*/
public class PreferenceUtil {
private static String PRE_APP = "app_name";
// 写----三种类型
/**
* write:
* String
* @param context
* 上下文
* @param key
* 存储的键
* @param value
* 默认值
*/
public static void write(Context context, String key, String value) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
preferences.edit().putString(key, value).commit();
}
/**
* write:
* int
* @param context
* 上下文
* @param key
* 存储的键
* @param value
* 默认值
*/
public static void write(Context context, String key, int value) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
preferences.edit().putInt(key, value).commit();
}
/**
* write:
* boolean
* @param context
* 上下文
* @param key
* 存储的键
* @param value
* 默认值
*
*/
public static void write(Context context, String key, boolean value) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
preferences.edit().putBoolean(key, value).commit();
}
// 读取----三种类型
/**
* readString:
* @param context
* @param key
* @return String
*/
public static String readString(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
return preferences.getString(key, "");
}
/**
* readInt:
* @param context
* @param key
* @return int
*/
public static int readInt(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
return preferences.getInt(key, 0);
}
/**
* readBoolean:
* @param context
* @param key
* @return boolean
*/
public static boolean readBoolean(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
// 移除数据
/**
* remove:
* 移除数据
* @param context
* @param key
*
*/
public static void remove(Context context,String key){
SharedPreferences preferences =
context.getSharedPreferences(PRE_APP, Context.MODE_PRIVATE);
preferences.edit().remove(key);
}
}
网络连接状态类:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* NetConnected:
* 判断网络连接状态
* @author micro
*
*/
public class NetConnected {
//是否连接
public static boolean netIsConnected(Context context){
boolean isWifiConnected = isWifiConnected(context);
boolean isMobileConnected = isMobileConnected(context);
if(isMobileConnected==false && isWifiConnected==false){
return false;
}
return true;
}
//wifi
public static boolean isWifiConnected(Context context){
ConnectivityManager manager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(info!=null && info.isConnected()){
return true;
}
return false;
}
//移动网络
public static boolean isMobileConnected(Context context){
ConnectivityManager manager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(info!=null && info.isConnected()){
return true;
}
return false;
}
}
文件操作类:
从网络上获取图片链接,然后转化为Bitmap:
/**HttpGetmap:
*
* 获取图片Bitmap
* 通过网络获取并最终转化为Bitmap
*
* */
public static Bitmap HttpGetmap(String url) {
HttpGet httpGet = new HttpGet(url);
Bitmap bitmap = null;
// 基本链接参数
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 3000);
//HttpClient
HttpClient httpClient;
try {
// 运行
httpClient = new DefaultHttpClient(httpParams);
//获取的结果
HttpResponse httpResponse = httpClient.execute(httpGet);
// 读入流,输出流
InputStream inputStream = httpResponse.getEntity().getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = 0;
byte[] byt = new byte[1024];
while ((len = inputStream.read(byt)) != -1) {
outputStream.write(byt, 0, len);
System.out.println("readBitmap");
outputStream.flush();
}
// 把outputStream转化为二进制
byte[] byteArray = outputStream.toByteArray();
// 获取bitmap
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
inputStream.close();
outputStream.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return bitmap;
}
包括文件流和图片Bitmap的转化及内存卡存储:
public class FileUtil {
private static String filepath = Environment.getExternalStorageDirectory()
+"/CSDNDownLoad";
/**去除给定字符串的字符,然后输出.png文件名
* */
public static String getFileName(String str){
str = str.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");
return str+".png";
}
/**文件存储
* */
public static void WriteSDcard(String name,InputStream inputStream){
try {
File file = new File(filepath);
if(!file.exists()){
file.mkdirs();
}
//写入
FileOutputStream outputStream = new FileOutputStream(file);
int len =0;
byte[] byt = new byte[1024];
while((len=inputStream.read(byt))!=-1){
outputStream.write(byt,0,len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**图片存储
* */
public static boolean WriteSDcard(String name,Bitmap bitmap){
try {
File file = new File(filepath);
if(!file.exists()){
file.mkdirs();
}
File fileImage = new File(filepath+"/"+getFileName(name));
if(fileImage.exists()){
return true;
}
//写入
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileImage));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
}
return true;
}
/**
* Bitmap转化为byte[]
* */
public static byte[] byteBitmap(Bitmap bitmap){
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
//压缩,转格式
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteout);
return byteout.toByteArray();
}
/**
* Bitmap转化为字节流InputStream
* */
public static InputStream InputStreamBitmap(Bitmap bitmap){
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteout);
InputStream in = new ByteArrayInputStream(byteout.toByteArray());
return in;
}
}
数据缓存类:
原理:定义一个数据库和一个对象类,通过数据库SQLite3存储,在异步加载数据的时候我们可以将其存储。
如果再加上一个网络判断,下一次加载在有网络时连接时刷新缓存(也就是数据库的删除和添加操作),下一次加载在没网络时直接,我们加载缓存数据(添加操作)。
例如:
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "CSDN_APP";
//构造器
public DBHelper(Context context) {
super(context,DB_NAME,null,1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql ="create table newItem(_id Integer primary key autoincrement, "
+ "title text,link text,date text,imgLink text,content text,newstype integer);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
/**NewsItem的增删查和创建数据库
* */
public class NewsItemDao {
private DBHelper dbHelper;
//创建数据库
public NewsItemDao(Context context){
dbHelper = new DBHelper(context);
}
//增删查
//添加数据
public void add(NewItem newItem){
// Log.e("database", "A");
String sql = "Insert into newItem(title,link,date,imgLink,"
+ "content,newstype)values(?,?,?,?,?,?)";
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.execSQL(sql,new Object[]{
newItem.getTitle(),newItem.getLink(),newItem.getDate()
,newItem.getImageLink(),newItem.getContent(),newItem.getNewType()});
// Log.e("database", "B");
//关闭数据库
database.close();
}
//添加一个list的数据
public void add(List<NewItem> newItems){
for(NewItem newItem:newItems){
add(newItem);
}
}
//删除新闻类型数据
public void removeAll(int newsType){
String sql = "delete from newItem where newstype=?";
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.execSQL(sql,new Object[]{newsType});
database.close();
}
//查询数据
public List<NewItem> query(int newsType,int currentPage){
List<NewItem> newItems = new ArrayList<NewItem>();
try {
//当前
int offset = 10*(currentPage-1);
String sql = "select title,link,date,imgLink,content,newstype from newItem where newstype = ? limit ?,?";
SQLiteDatabase database = dbHelper.getWritableDatabase();
//查询10条新闻信息
Cursor cursor = database.rawQuery(sql, new String[]{newsType+"",offset+"",(offset+10)+""});
NewItem newItem = null;
//title text,link text,data text,imgLink text,content text,newstype integer
while(cursor.moveToNext()){
//结果集设置到NewItem中
newItem = new NewItem();
newItem.setTitle(cursor.getString(0));
newItem.setLink(cursor.getString(1));
newItem.setDate(cursor.getString(2));
newItem.setImageLink(cursor.getString(3));
newItem.setContent(cursor.getString(4));
newItem.setNewType(cursor.getInt(5));
newItems.add(newItem);
}
//close
database.close();
cursor.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return newItems;
}
}
调用时:
/**
* LoadMore:加载更多
* 根据当前网络情况,判断是从数据库加载还是从网络中加载
*/
//加载数据
private void LoadMore(){
if(isLoadFromNetWork){
//如果是从网络加载
currentPage+=1;
try {
//从网络获取数据并加载到列表中
List<NewItem> newItems = itemProcess.getNewItems(newtype, currentPage);
//数据库存储
//注意数据库的错误,会导致加载不进来
newsItemDao.add(newItems);
itemAdapter.addAll(newItems);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e("error", e.getMessage());
}
}else{
//否则就从数据库加载
currentPage+=1;
List<NewItem> newItems = newsItemDao.query(newtype, currentPage);
itemAdapter.addAll(newItems);
}
}
异步线程加载,用于加载耗时的任务如本次客户端的网络数据获取,我们对上下拉进行监听:
/**
* LoadDatasTask:
* 线程任务
* */
class LoadDatasTask extends AsyncTask<Integer, Void, Integer>{
@Override
//先执行这个方法
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
switch (params[0]) {
case LOAD_MORE:
LoadMore();
break;
case LOAD_REFRASH:
return refreshData();
default:
break;
}
return -1;
}
//然后再执行这个方法
@Override
protected void onPostExecute(Integer result){
switch(result){
case TIP_ERROR_NO_NETWORK:
Toast.makeText(getActivity(), "没有网络!", Toast.LENGTH_SHORT).show();
itemAdapter.setDatas(datas);
itemAdapter.notifyDataSetChanged();
break;
case TIP_ERROR_SERVER:
Toast.makeText(getActivity(), "无法获取服务器数据", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
//设置时间
xListView.setRefreshTime(DateUtil.getRefreshTime(getActivity(), newtype));
xListView.stopLoadMore();
xListView.stopRefresh();
}
}
项目源码:
链接:http://pan.baidu.com/s/1eSoIALc 密码:wj3i