Android数据库--Sqlcipher的使用(一)

时间:2022-06-21 22:14:14

1、下载官方支持包:https://s3.amazonaws.com/sqlcipher/3.2.0/sqlcipher-for-android-community-v3.2.0.zip

Github地址:https://github.com/sqlcipher/android-database-sqlcipher

2、本博客使用Android Studio开发,Eclipse怎样使用Sqlcipher大家可以到网上搜索。

3、需要导入以下包及文件。如何导入Jar包可以参考我的博客http://www.cnblogs.com/begin1949/p/4966542.html。

Android数据库--Sqlcipher的使用(一)

4、我们重写一下SqliteOpenHelper类。这里注意一下引用的类来自于net.sqlcipher.database而不是谷歌官方的sqlite包。

import android.content.Context;

import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper; public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_TABLE = "create table Book(name text,pages integer)"; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory
factory, int version) {
super(context, name, factory, version);
} @Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
} @Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}

5、接下来即可使用了。

import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import com.sqlcipher.R; import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase; public class Use1Activity extends FragmentActivity implements View.OnClickListener { private SQLiteDatabase db;
private MyDatabaseHelper dbHelper; private Button mBtnAdd;
private Button mBtnQuery;
private TextView mTvShow; private String result; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_use1); initView();
} private void initView() {
SQLiteDatabase.loadLibs(this);
dbHelper = new MyDatabaseHelper(this, "demo.db", null, 1);
db = dbHelper.getWritableDatabase("secret_key"); mBtnAdd = (Button) findViewById(R.id.add_data);
mBtnQuery = (Button) findViewById(R.id.query_data);
mTvShow = (TextView) findViewById(R.id.tv_show); mBtnAdd.setOnClickListener(this);
mBtnQuery.setOnClickListener(this);
} @Override
public void onClick(View v) {
if (v == mBtnAdd) {
ContentValues values = new ContentValues();
values.put("name", "密码");
values.put("pages", 566);
db.insert("Book", null, values);
} else if (v == mBtnQuery) {
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
result += "book name is " + name + "\n";
result += "book pages is " + pages + "\n";
}
}
cursor.close(); mTvShow.setText(result);
result = "";
}
}
}

6、参考博文:https://discuss.zetetic.net/t/android-studio-integration/65

http://blog.csdn.net/sziicool/article/details/18728153