1. 程式人生 > >AsyncTask介面回撥使用(一)

AsyncTask介面回撥使用(一)

package com.bwei.day04_utils_cache;

import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import android.widget.Toast;

import com.google.gson.Gson;

import adapters.NewsAdapter; import beans.NewsBean; import databases.MyHelper; import https.HttpConfig; import utils.HttpUtils;

/**

  • 1.完善工具
  • 2.快取
  • 1.判斷網路
  • 有–直接請求
  • 沒有—載入資料庫
  • 有—拿過來資料庫的內容–json
  • 沒有 -提示
  • 思路:
  • 1.初始化頁面
  • 2.寫工具類,HttpUtils
  •      封裝get,post,流轉換等方法
    
  • 3.建立資料庫的相關類,建立表格
  • 4.在MainActivity呼叫封裝好的工具類,判斷有沒有網
  • 5.如果有網,再次呼叫工具類get請求獲取網路請求資料json
  •  將資料json解析
    
  •  建立介面卡
    
  •  將資料放入介面卡,listview設定介面卡,展示資料
    
  •  將json資料存入資料庫作為快取資料,方便下次沒網的時候獲取資料庫資料
    
  • 6.如果沒有網,去獲取資料庫的資料
  •  同樣的,獲取的json資料需要解析,展示
    

*/ public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //應用一載入就顯示網路資料
    final ListView listView = findViewById(R.id.listview);
    //初始化資料庫
    MyHelper myHelper = new MyHelper(this);
    final SQLiteDatabase database = myHelper.getReadableDatabase();
    //判斷有麼有網路
    HttpUtils httpUtils = HttpUtils.getHttpUtils();
    boolean hasNet = httpUtils.hasNet(this);
    if (hasNet) {
        //如果有網,請求網路
        httpUtils.get(HttpConfig.new_url);
        //設定監聽
        httpUtils.setOnHttpLoadListener(new HttpUtils.HttpLoadListener() {
            @Override
            public void loadSuccess(String json) {
                Gson gson = new Gson();
                NewsBean newsBean = gson.fromJson(json, NewsBean.class);
                if (newsBean.getCode() == 200) {
                    //儲存一份最新的資料
                    ContentValues values = new ContentValues();
                    values.put("content", json);
                    database.insert("mynews", null, values);
                    //關閉資料庫
                    NewsAdapter adapter = new NewsAdapter(MainActivity.this, newsBean.getNewslist());
                    listView.setAdapter(adapter);
                }
            }

// 網路載入失敗的回撥方法 @Override public void loadError(String error) {

            }
        });
    } else {

// 沒網的時候,去資料庫獲取快取資料 Toast.makeText(MainActivity.this, “沒網路了”, Toast.LENGTH_SHORT).show(); //請求資料庫 Cursor cursor = database.query(“mynews”, null, null, null, null, null, null); // 移到最後一行,獲取最新的快取資料 boolean b = cursor.moveToLast(); if (b) { String json = cursor.getString(cursor.getColumnIndex(“content”)); Gson gson = new Gson(); NewsBean newsBean = gson.fromJson(json, NewsBean.class); if (newsBean.getCode() == 200) { NewsAdapter adapter = new NewsAdapter(MainActivity.this, newsBean.getNewslist()); listView.setAdapter(adapter); } } }

}

}