資料庫 快取資料
阿新 • • 發佈:2018-12-11
package helper; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private static final String TABLENAME="News"; private static final int VERSION = 1; public DBHelper(Context context) { super( context, TABLENAME, null, VERSION ); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table news(id Integer primary key autoincrement,data text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
//dao層 package com.example.dell.ykmoni01; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.google.gson.Gson; import java.util.List; import bean.NewsBean; import helper.DBHelper; public class Dao { private SQLiteDatabase db; private static final String TABLENAME = "news"; private static final String DATA = "data"; public Dao(Context context) { DBHelper dbHelper = new DBHelper( context ); db = dbHelper.getWritableDatabase(); } //新增 public long insert(String data){ ContentValues values = new ContentValues(); values.put( DATA, data ); return db.insert( TABLENAME,null, values); } //查詢 public List<NewsBean.ResultBean.DataBean> queryAll(){ String dataSql=""; try { Cursor cursor = db.rawQuery("select data from news", null); while(cursor.moveToNext()){ dataSql = cursor.getString( cursor.getColumnIndex( DATA ) ); } NewsBean newsList = new Gson().fromJson( dataSql, NewsBean.class ); return newsList.getResult().getData(); }catch (Exception e){ } return null; } }
//點選收藏存入資料庫 呼叫insert方法 public void onClick(View v) { Dao dao = new Dao( News.this ); dao.insert( data ); Toast.makeText( News.this,"收藏成功",Toast.LENGTH_SHORT ).show(); }
//查詢我的收藏 查詢資料庫放入listview集合 listView = findViewById( R.id.listview_sc ); Dao dao = new Dao( Sc.this ); List<NewsBean.ResultBean.DataBean> newsBeans = dao.queryAll(); MyScAdapter myScAdapter = new MyScAdapter( Sc.this, newsBeans ); listView.setAdapter( myScAdapter );