Android SQL基于用户的数据库

时间:2019-01-15 17:45:47

标签: android database sqlite

(SQL / java的新功能)我正在尝试实现一个接受用户登录并将数据保存在本地SQL数据库上的应用程序。

到目前为止,我所看到的所有实现都将数据库名称定义为 数据库帮助程序类中的私有静态最终String。我需要能够将具有用户名的字符串从MainActivity传递到Database helper类,并使用该字符串名创建/打开数据库。

当我尝试在以下声明中包括非最终字符串作为DATABASE_NAME时,它将无法运行:

    public class DBHelper extends SQLiteOpenHelper {
       public DBHelper(){
          super(context,DATABASE_NAME,null,1);
   }

我不确定是否有可能。如果不可能的话,那么我将对如何在同一应用程序中存储由不同用户分隔的数据提供任何建议。

谢谢大家!

根据要求提供更多详细信息。 (通过几次实验,代码有点混乱。...)

这是我在Helper类中拥有的:

//DATABASE NAME
SQLiteDatabase data;

//TABLE_NAME
private String TABLE_NAME;

//COLUMN ID's
private static final String KEY_ID = "ID";
private static final String KEY_Name = "name";
private static final String KEY_Gender = "gender";


public DatabaseHelper(Context context, String DATABASE_NAME) { //tried to pass DATABASE name here
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) { //Could not pass TABLE_NAME here so created the "createTable" below

}

public void createTable(String TABLE_NAME){
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            KEY_Name +" TEXT, "+KEY_Gender+" TEXT)";
    data.execSQL(createTable); //Code runs up to here on DEBUG
}

在MainActivity中,我有这个:

public class MainActivity extends AppCompatActivity {

    DatabaseHelper mDatabaseHelper;

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

        mDatabaseHelper = new DatabaseHelper(this, "USER1");
        mDatabaseHelper.createTable("People");

    }
}

事件记录器不显示任何错误,但是布局不显示在模拟器上。如果我不执行最后一条命令:

mDatabaseHelper.createTable("People");

然后布局完美。如果我调试并逐行执行,程序将进入ActivityThread.java中的try / catch:

if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
            }
            r.setState(ON_CREATE);

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }

当我执行以下代码行时会发生这种情况:

data.execSQL(createTable);

1 个答案:

答案 0 :(得分:0)

使用

String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_Name +" TEXT, "+KEY_Gender+" TEXT)";

在首次运行该应用程序时将工作一次。然后,您将遇到一个错误,因为该应用程序将尝试创建已经存在的表。

更改为

String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_Name +" TEXT, "+KEY_Gender+" TEXT)";

将避免这种失败。这很可能是您遇到的问题。