数据库 缓存数据

 
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 );

猜你喜欢

转载自blog.csdn.net/qq_42250299/article/details/82777498
今日推荐