将字符串和整数传递给多个活动和databasehelper

时间:2013-09-05 19:46:42

标签: android database bundle

我有一个带有“主要”活动的应用,该活动有8个子活动。在主要活动中,我从数据库中读取并将有关所选项目(通过微调器)的基本信息加载到一个包中(这样每个活动都可以加载更快,因为我不需要在onCreate方法中查询数据库用于创建视图的活动)。在新活动中创建视图后,我向DB查询该特定活动所需的剩余数据。在此之前,我使用了公共变量,它允许我的databasehelper类知道要查看哪个表来获取数据。我知道你不应该如何编程,所以我将我的应用程序转换为使用捆绑包(不确定它是否是最佳方式,但我相信它是朝着正确方向迈出的一步)。

我目前能够在我的所有8个子活动中访问保存到该捆绑包中的数据,但我无法从我的databasehelper类访问它。

我在主要活动中使用的捆绑包:

bundle = new Bundle();
bundle.putString("KEY_tableName", tableName);
bundle.putInt("KEY_numOne", numOne);
bundle.putInt("KEY_numTwo", numTwo);
... and others

my databasehelper class

package com.myName.myAPP;

import java.io.File;
import java.io.FileOutputStream; 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {

//The Android's default system path of your application database.
static String DB_PATH = "/data/data/com.myName.myApp/databases/";
static String DB_NAME = "databasefile";
public SQLiteDatabase myDataBase;

private final Context myContext;

//version of database
private static final int version = 1;

public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "Title";
public static final String KEY_BODY = "Content";
public static final String KEY_DATE = "Date";

private static final String TAG = "NotesDbAdapter";
//private static final String DATABASE_CREATE = "create table notes (_id integer primary " +
//      "key autoincrement, " + "title text not null, body text not null);";
//private static final String DATABASE_TABLE = "notes";

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
DataBaseHelper(Context context) {
    super(context, DB_NAME, null, version);
    this.myContext = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();
    if(dbExist){
        //do nothing - database already exist
    } // end if
    else {
        //By calling this method and empty database will be created into the default system path
           //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();
        try {
            copyDataBase(myContext);
        } // end try
        catch (IOException e) {
            throw new Error("Error copying database");
        } // end catch
    } // end else
    this.close();
} // end createDataBase()

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        //checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        //File dbFile = new File(DB_PATH + DB_NAME);
        //return dbFile.exists();
    }
    catch(SQLiteException e) {
        //database does't exist yet.
    }
    if(checkDB != null) {
        checkDB.close();
    }
    return checkDB != null;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase(Context myContext) throws IOException {   

    File fileTest = myContext.getFileStreamPath(DB_NAME);
    boolean exists = fileTest.exists();
    if (!exists) {
        // Open the empty db as the output stream
        OutputStream databaseOutputStream = new FileOutputStream(DB_PATH + DB_NAME);
        InputStream databaseInputStream;

        databaseInputStream = myContext.getAssets().open(DB_NAME);
        byte[] buffer = new byte[1024];
        @SuppressWarnings("unused")
        int length;
        while ((length = databaseInputStream.read(buffer)) > 0) {
            databaseOutputStream.write(buffer);
        } // end while
        databaseInputStream.close();

        databaseInputStream = myContext.getAssets().open(DB_NAME);
        while ((length = databaseInputStream.read(buffer)) > 0) {
            databaseOutputStream.write(buffer);
        } // end while

        // Close the streams
        databaseInputStream.close();
        databaseOutputStream.flush();
        databaseOutputStream.close();
    } // end if
} // end copyDataBase

public void openDataBase() throws SQLException{     
    File f = new File(DB_PATH);
    if (!f.exists()) {
        f.mkdir();
    }
    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} // end openDataBase

@Override
public void close() {
    if(myDataBase != null) {
        myDataBase.close();
    }
    super.close();
} // end close

@Override
public void onCreate(SQLiteDatabase db) {
} // end onCreate

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion 
            + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS notes");
    onCreate(db);
} // end onUpgrade

另外,我还有其他方法可以读取/写入/更新数据库。

在我的孩子活动中,我通过调用:

来访问该包
String tableName = getIntent().getExtras().getString("KEY_tableName");
int numOne = getIntent().getExtras().getString("KEY_numOne");
...

在该活动的onCreate方法中能够使用数据

然而,当我在我的databasehelper类的方法中使用该代码时,我得到一个错误:getIntent(),它将无法在android studio中编译。错误是:

java: cannot find symbol
symbol:   method getIntent()
location: class com.myName.myAPP.DataBaseHelper

谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

getIntent()是一种Avctivity方法,因此无法在非Activity类中使用。

From the docs

  

返回启动此活动的意图

但您不在Activity,因此无法识别

您需要创建一个构造函数来接受数据库所需的值,或创建接受这些值的方法并从Activities发送它们