从android上的sqlcipher数据库返回数据并放入textview

时间:2018-03-23 10:39:54

标签: android sqlcipher sqlcipher-android

使用 sqlcipher getting started页面,我无法显示数据库中的数据,并且在文本视图中查看

我初始化了数据库并在点击事件中查询了数据库,但在原始查询事件期间它崩溃了。

package com.example.keystoretest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import net.sqlcipher.Cursor;
import net.sqlcipher.database.SQLiteDatabase;

import java.io.File;

public class HelloSQLCipherActivity extends Activity {

    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_sqlcipher);
        InitializeSQLCipher();
    }

    private void InitializeSQLCipher() {
        SQLiteDatabase.loadLibs(this);
        File databaseFile = getDatabasePath("demo.db");
        databaseFile.mkdirs();
        databaseFile.delete();
        db = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
        db.execSQL("create table t1(a, b)");
        db.execSQL("insert into t1(a, b) values(?, ?)", new Object[]{"one for the money",
                "two for the show"});
    }

    public void viewText(View view) { //click event on button

        String query = "SELECT * FROM t1(a, b)";

        Cursor data = db.rawQuery(query, null);

        final TextView mTextView = (TextView) findViewById(R.id.textView);
        mTextView.setText(data.toString());
    }
}

任何人都可以帮助我,因为我一直在尝试关注examples sql-lite,但他们似乎无法使用密码。

2 个答案:

答案 0 :(得分:1)

  

这很奇怪,因为它是一个有效的SQL查询?

我认为这不是一个有效的SQL查询,至少对于SQLite而言。使用SELECT * FROM t1SELECT a,b FROM t1

答案 1 :(得分:0)

未来参考的完整解决方案。 (更改名称" t"到表格)

public class HelloSQLCipherActivity extends Activity {

    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_sqlcipher);
        InitializeSQLCipher();
    }

    private void InitializeSQLCipher() {
        SQLiteDatabase.loadLibs(this);
        File databaseFile = getDatabasePath("demo.db");
        databaseFile.mkdirs();
        databaseFile.delete();
        db = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
        db.execSQL("create table table1(a, b)");
        db.execSQL("insert into table1(a, b) values(?, ?)", new Object[]{"one for the money",
                "two for the show"});
    }

    public void viewText(View view) {
        String query = "SELECT a FROM table1";

        Cursor data = db.rawQuery(query, null);

        final TextView mTextView = (TextView) findViewById(R.id.textView);

        data.moveToFirst();

        mTextView.setText(data.getString(data.getColumnIndex("a")));

        data.close();

        db.close();
    }
}