当用户在Android中登录应用时如何保存数据?

时间:2017-04-08 14:18:16

标签: android sqlite

我已经实现了登录和注册系统,用户可以使用他们的用户名和密码进行注册和登录。现在,我不知道如何开始解决这个问题。

我希望保存数据,无论他或她在应用程序中做什么,只为那个用户存在而不与其他用户碰撞数据,如果这样做有意义的话。

所以,我的应用程序有一个主表数据库,表(USER_INFO)有3列,ID,NAME和PASSWORD。

我的问题是,如何为特定用户实现SQLite的保存方法? 我应该在我的主数据库下创建另一个表吗?如何? 如果我有第二个表应该与USER_INFO表连接?

试图从谷歌android读取,但不要在那里回答我这个问题。

1 个答案:

答案 0 :(得分:0)

您可以使用相同的表格,如下所示:

1)您的实体对象

public class UserInfo {
    int id; // will be auto-increamted
    String name;
    String password;

    public UserInfo(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
// getter/setters ...
}

2)您的Sqlite实用程序对象,(注意您可以根据需要添加更多表):

public class SQLiteDBAdapter {

    protected static final String DATABASE_NAME = "mydb";
    protected static final int DATABASE_VERSION = 1;

    protected Context context;
    protected static DatabaseHelper mDbHelper;

    public static final String TABLE_USER_INFO = "tbl_userinfo";
    // columns
    public static final String USER_ID = "_id";
    public static final String NAME = "name";
    public static final String PASSWORD = "password";
    // create table string
    private static final String CREATE_TABLE_USER_INFO =
            "CREATE TABLE if not exists " + TABLE_USER_INFO + " ( " +
                    USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    NAME + " TEXT NOT NULL, " +
                    PASSWORD + " TEXT NOT NULL);";

    public SQLiteDBAdapter(Context context) {
      context = context.getApplicationContext();
    }

    public SQLiteDatabase openDb() {
      if (mDbHelper == null) {
          mDbHelper = new DatabaseHelper(mContext);
      }
      return mDbHelper.getWritableDatabase();
    }

    protected static class DatabaseHelper extends SQLiteOpenHelper {
      // -------------------------------------------------------------------------------------------
      public DatabaseHelper(Context context) {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
      // -------------------------------------------------------------------------------------------
      @Override
      public void onCreate(SQLiteDatabase db) {
          db.execSQL(CREATE_TABLE_USER_INFO);
      }
      // -------------------------------------------------------------------------------------------
      @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 routes");
          onCreate(db);
      }
    }
}

3)扩展Sqlite对象以操作表(CRUD操作):

public class UserInfoDbAdapter extends SQLiteDBAdapter {

    private SQLiteDatabase db;

    // these are column corresponding indices
    public static final int INDEX_ID = 0;  // an auto-increment
    public static final int INDEX_NAME = 1;
    public static final int INDEX_PASSWORD = 2;

    public UserInfoDbAdapter(Context context) {
        super(context);
    }

    public void add(String name, String password) {
        db = openDb();
        ContentValues values = new ContentValues();
        values.put(NAME, name);
        values.put(PASSWORD, password);
        db.insert(TABLE_USER_INFO, null, values);
    }

    public void update(String name, String password) {
        db = openDb();
        ContentValues values = new ContentValues();
        values.put(NAME, name);
        values.put(PASSWORD, password);
        db.update(TABLE_USER_INFO, values, null);
    }

    public void deleteAll() {
        db = openDb();
        db.delete(TABLE_USER_INFO, null, null);
    }

    public boolean isEmpty() {
        db = openDb();
        boolean empty = true;
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_USER_INFO, null);
        if (cursor != null && cursor.moveToFirst()) {
            empty = (cursor.getInt (0) == 0);
        }
        cursor.close();
        return empty;
    }

    public UserInfo fetchRecord() { // only one record to fetch
        db = openDb();
        Cursor cursor = db.query(TABLE_USER_INFO, new String[]{USER_ID, NAME, PASSWORD},
                null, null, null, null, null, null);
        if (cursor != null &&
            cursor.moveToFirst()) {
            return new UserInfo(
                    cursor.getInt(INDEX_ID),
                    cursor.getString(INDEX_NAME),
                    cursor.getInt(INDEX_PASSWORD));
        }
        return null;
    }
}

4)最后,根据需要添加/更新/删除/获取用户记录...

public class MainActivity extends AppCompatActivity {
    private UserInfoDbAdapter userDB; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ... 
        // initialize user db
        userDB = new UserInfoDbAdapter(this);

        // add user if table is empty
        if (userDB.isEmpty() {
            // add user
            userDB.add(nameTextView.getText().toString(), passwordTextView.getText().toString());
// note it's always more secure to store encrypted password, rather than plain text.
        } else {
            // update
            userDB.update(nameTextView.getText().toString(), passwordTextView.getText().toString());
        }

    }
    ...
    // fetch record
    public UserInfo fetchRecord() {
        return userDB.fetchRecord();
    }
}