1. 程式人生 > >新聞客戶端功能類集合

新聞客戶端功能類集合

臨時儲存三種類型的資料類:

/**
 * 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