传递字符串和整数多个活动和databasehelper [英] Passing strings and ints to multiple activities and databasehelper

查看:302
本文介绍了传递字符串和整数多个活动和databasehelper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有8个孩子的活动的主要活动的应用程序。在主要活动我从数据库中读取,因为我不必查询数据库中的onCreate方法有关选择(通过微调)项目基本信息加载到束(这样,每个活动可以加载速度更快活动创建视图)。一旦视图中的新活动创建我查询数据库为需要的特定活动的剩余数据。现在摆在我使用的公共变量,这让我databasehelper类知道寻找到哪个表来获取数据。我知道这是不是你应该怎么编程,所以我在转换我的应用程序使用捆绑包(不知道它的最好办法不是,但我相信它在正确的方向迈出的一步)。

I have an app with a "Main" activity that has 8 child activities. In the main activity I read from a database and load basic info about an item that was selected (via a spinner) into a bundle (this way each activity can load faster because I am not having to query the DB in the onCreate method of that activity to create the view). Once the view is created in the new activity I query the DB for the remaining data needed for that specific activity. Before now I used public variables which allowed my databasehelper class to know which table to look into to get the data. I know that is not how you should program so I am converting my app over to using a bundle (not sure if its the best way either but I believe its a step in the right direction).

我现在能够访问所有的8子活动保存成捆的数据,但我无法从我的databasehelper类访问它。

I am currently able to access the data saved into that bundle in all of my 8 child activities but I cannot access it from my databasehelper class.

我的包,我的主要活动是:

my bundle that I use in the main activity:

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

我的databasehelper类

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

另外,我还有其他的方法来读/写/更新数据库。

Plus I have other methods to read/write/update the database.

在我的孩子我的活动通过调用访问包:

in my child activities I access the bundle by calling:

String tableName = getIntent().getExtras().getString("KEY_tableName");
int numOne = getIntent().getExtras().getString("KEY_numOne");
...

在该活动的onCreate方法,以便能够使用该数据

in the onCreate method of that activity to be able to use the data

然而,当我使用code在我的我的databasehelper类的方法,我得到一个错误的位置:getIntent(),它不会在Android Studio中进行编译。该错误是:

However when I use that code in my methods of my databasehelper class I get an error at: getIntent() and it will not compile in android studio. The error is:

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

感谢您的帮助。

推荐答案

getIntent() Avctivity 方法活性类 - ,因此它不能在非使用。

getIntent() is an Avctivity method so it can't be used in a non-Activity class.

从文档

返回开始这活动的意图

但你不是在活动,因此无法识别

but you are not in an Activity so it is not recognized

您需要或者创建一个构造函数来接受您需要为您的数据库中的值,或创建一个接受这些值的方法,并从送他们活动

You need to either create a constructor to accept the values you need for your DB or create methods that accept these values and send them from your Activities

这篇关于传递字符串和整数多个活动和databasehelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆