80,351
社区成员
发帖
与我相关
我的任务
分享
package com.huading.hdshop;
/**
* Created by xie on 2017/7/18.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class HDSetupInfo extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "Library";
private final static int DATABASE_VERSION = 1;
private final static String TABLE_NAME = "Hdsetup";
//构造函数,创建数据库
public HDSetupInfo(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//建表
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
+ "(_id INTEGER PRIMARY KEY autoincrement,"
+ " hdkey VARCHAR(30) NOT NULL,"
+ " hdval VARCHAR(30))";
db.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
//获取游标
public Cursor select() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;
}
//建立设置值
public long insert(String hdkey,String hdvalue ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("hdkey", hdkey);
cv.put("hdval", hdvalue);
long row = db.insert(TABLE_NAME, null, cv);
return row;
}
//查询设置值
public Cursor query(String[] args) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE hdkey = ?", args);
return cursor;
}
//更新设置值
public void update(String hdkey,String hdvalue) {
SQLiteDatabase db = this.getWritableDatabase();
String where = " hdkey = ?";
String[] whereValue = { hdkey };
ContentValues cv = new ContentValues();
cv.put("hdval", hdvalue);
db.update(TABLE_NAME, cv, where, whereValue);
}
//设置KEY
public void SetKey(String hdkey,String hdvalue){
String et=hdkey;
String args[]=new String[]{et};
Cursor cursor=this.query(args);
if(cursor.getCount()>0){
this.update(hdkey,hdvalue);
}else{
this.insert(hdkey,hdvalue);
}
}
//读取KEY
public String GetKey(String hdkey){
String args[]=new String[]{hdkey};
Cursor cursor=this.query(args);
if(cursor.getCount()==1) {
cursor.moveToFirst();
return cursor.getString(2);
}else{
return "";
}
}
}
某个页面的用法 , 保存值
HDSetupInfo hd1 = new HDSetupInfo(this);
if(checkSaveLogin.isChecked()){
hd1.SetKey("SaveLogin","1");
hd1.SetKey("SaveAccount",mu);
}
取值
HDSetupInfo hd1 = new HDSetupInfo(this);
String s1 = hd1.GetKey("SaveLogin");
if(s1.equals("1")){
String s2 = hd1.GetKey("SaveAccount");
Set_Login_M(s1,s2);
}