首页 > 解决方案 > 我想将 sqlite 数据库中的数据检索到另一个活动的 textview 中,我的数据库代码如下所示

问题描述

try {
        String qu = "CREATE TABLE IF NOT EXISTS ABOUTINST(body varchar(10000));";
        database.execSQL(qu);
    } catch (Exception e) {
        Toast.makeText(activity, "Error Occured for create table", Toast.LENGTH_LONG).show();
    }

标签: androidandroid-sqlite

解决方案


已编辑

使用此 SQLiteOpenHelper 管理您的特定数据库

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 UserDbHelper extends SQLiteOpenHelper {
    // replace constant for your database name
    private static final String DATABASE_NAME = “YOUR_DB_NAME”;
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = “abount_inst”;
    private static final String CREATE_QUERY = "CREATE TABLE IF NOT EXISTS abount_inst(id INTEGER PRIMARY KEY AUTOINCREMENT, body varchar(10000))";


    public UserDbHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.e("DATABASE OPERATION", "Database created / opened.....");

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_QUERY);
        Log.e("DATABASE OPERATION", "Table create..." + CREATE_QUERY);
    }



    // method to retrieve body using PRIMARY_KEY of the table i.e. id
    public String getBody(int id, SQLiteDatabase db) {
        Cursor cursor = null;
        String body = "";
        try {
            String selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE id = " + id;
            cursor = db.rawQuery(selectQuery, null);


            if (cursor.getCount() > 0) {

                cursor.moveToFirst();
                body = cursor.getString(cursor.getColumnIndex("body"));
            }

        } finally {

            cursor.close();
            return body;

        }


    }

}

推荐阅读