[英]How to store and retrieve data for a particular user using SQlite in android
我想保存用戶憑據(名稱),然后在該名稱上我想為該特定用戶保存一些數據。 我正在使用SQlite並且我已成功保存數據但我無法為特定用戶制作它現在它正在為所有用戶顯示。 我的特定用戶名目前保存在共享首選項中。 請告訴我適當的解決方案。
DB助手:
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NOTES";
public static final String USER_COLUMN_ID = "idu";
public static final String TABLE_USER_NAME = "name";
public static final String CREATE_TABLE_USER =
"CREATE TABLE " + TABLE_USER_NAME + "("
+ USER_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT"
+ ")";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Notes.CREATE_TABLE_NOTE);
db.execSQL(CREATE_TABLE_USER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER_NAME);
onCreate(db);
}
public long insertNote(String note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Notes.COLUMN_NOTE, note);
long id = db.insert(TABLE_NAME, null, values);
db.close();
return id;
}
public Notes getNote(long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,
new String[]{Notes.NOTE_COLUMN_ID, Notes.COLUMN_NOTE},
Notes.NOTE_COLUMN_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Notes notes = new Notes(
cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)));
cursor.close();
return notes;
}
public List<Notes> getAllNotes() {
List<Notes> notes = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY " +
Notes.NOTE_COLUMN_ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Notes note = new Notes();
note.setId(cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)));
note.setNote(cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)));
notes.add(note);
} while (cursor.moveToNext());
}
db.close();
return notes;
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
}
筆記:
public class Notes {
public static final String NOTE_COLUMN_ID = "id";
public static final String COLUMN_NOTE = "note";
public static final String TABLE_NAME = "notes";
private int id;
private String note;
public static final String CREATE_TABLE_NOTE =
"CREATE TABLE " + TABLE_NAME + "("
+ NOTE_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NOTE + " TEXT"
+ ")";
public Notes() {
}
public Notes(int id, String note) {
this.id = id;
this.note = note;
}
public int getId() {
return id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public void setId(int id) {
this.id = id;
}
}
分段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notes, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
noNotesView = view.findViewById(R.id.empty_notes_view);
logout = view.findViewById(R.id.button_logout);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(getActivity(), gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getActivity());
mUser = acct.getDisplayName().trim();
LoggedInSharedPreference.setGoogleUserId(getActivity(), mUser);
db = new DBHelper(getActivity());
user = db.insertUser(mUser);
notesList.addAll(db.getNotesByUser(user));
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showNoteDialog(false, null, -1);
}
});
mAdapter = new NotesAdapter(getActivity(), notesList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
recyclerView.addOnItemTouchListener(new NotesItemListener(getActivity(),
recyclerView, new NotesItemListener.ClickListener() {
@Override
public void onClick(View view, final int position) {
}
@Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
return view;
}
private void createNote(String note, long user) {
long id = db.insertNote(note, user);
Notes n = db.getNote(id);
if (n != null) {
notesList.add(0, n);
mAdapter.notifyDataSetChanged();
toggleEmptyNotes();
}
}
private void updateNote(String note, int position) {
Notes n = notesList.get(position);
n.setNote(note);
db.updateNote(n);
notesList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyNotes();
}
private void deleteNote(int position) {
db.deleteNote(notesList.get(position));
notesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyNotes();
}
private void showActionsDialog(final int position) {
CharSequence charSequences[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select");
builder.setItems(charSequences, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showNoteDialog(true, notesList.get(position), position);
} else {
deleteNote(position);
}
}
});
builder.show();
}
private void showNoteDialog(final boolean shouldUpdate, final Notes notes, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getContext());
View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(getActivity());
alertDialogBuilderUserInput.setView(view);
final EditText inputNote = view.findViewById(R.id.notes);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.new_note) : getString(R.string.edit_note));
if (shouldUpdate && notes != null) {
inputNote.setText(notes.getNote());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(inputNote.getText().toString())) {
Toast.makeText(getActivity(), "Add Note", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
if (shouldUpdate && notes != null) {
updateNote(inputNote.getText().toString(), position);
} else {
createNote(inputNote.getText().toString(), user);
}
}
});
}
}
您似乎需要Note(子)和它的用戶(父)之間的關系。 假設一個Note只有一個用戶(誰擁有該筆記)。 然后,您可以在存儲Notes的表中添加一列。
由於User表具有使用INTEGER PRIMARY KEY
定義的id列,因此該列是關系的理想候選者(它是索引的,也是唯一的(隱式))。 它將是一個整數值(在java中可能很長)。
為了保持一致,你需要為列名定義一個常量,所以添加: -
public static final String NOTE_COLUMN_USERMAP = "usermap";
然后,您可以定義更改CREATE_TABLE_NOTE常量以包含
+ NOTE_COLUMN_USERMAP + " INTEGER "; //<<<<<<<<<comma if needed after INTEGER
或者,如果您可能想要引入FOREIGN KEY約束並使用
+ NOTE_COLUMN_USERMAP + "INTEGER REFERENCES " + DBHelper.TABLE_USER_NAME + "(" + USER_COLUMN_ID + ") ON DELETE CASCADE ON UPDATE CASCADE "; //<<<<<<<<<comma if needed after 2nd CASCADE
您將對Notes類/對象進行免費更改,以存儲類中擁有用戶的用戶ID(地圖/關系)(最好是長),並為id的id添加一個getter和setter。用戶。 您還應該有一個構造函數,其中包含從數據庫中檢索Note時要使用的用戶ID。
然后,您需要更改DBHelper的方法以滿足額外的列。 例如
insertNote方法可能變成: -
public long insertNote(String note, long userMap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Notes.COLUMN_NOTE, note);
values.put(Notes.NOTE_COLUMN_USERMAP,userMap);
long id = db.insert(TABLE_NAME, null, values);
db.close();
return id;
}
getNotes方法可能變為: -
public Notes getNote(long id) {
Notes notes;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,
new String[]{Notes.NOTE_COLUMN_ID, Notes.COLUMN_NOTE,Notes.NOTE_COLUMN_USERMAP},
Notes.NOTE_COLUMN_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor.moveToFirst()) {
notes = new Notes(
cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)),
cursor.getLong(cursor.getColumnIndex(Notes.NOTE_COLUMN_USERMAP))
);
}
cursor.close();
return notes;
}
但我無法為特定用戶制作它現在它正在為所有用戶顯示
在上面之后,您可以編寫一個包含基於usermap列的WHERE子句的查詢。
例如getNotesByUser可能是: -
public List<Notes> getNotesByUser(long usermap) {
List<Notes> notes = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,
new String[]{Notes.NOTE_COLUMN_ID, Notes.COLUMN_NOTE,Notes.NOTE_COLUMN_USERMAP},
Notes.NOTE_COLUMN_USERMAP + "=?",
new String[]{String.valueOf(usermap)}, null, null, null, null);
while(cursor.moveToNext()) {
notes.add(new Notes(cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)),
cursor.getLong(cursor.getColumnIndex(Notes.NOTE_COLUMN_USERMAP)))
);
}
cursor.close();
return notes;
}
注意以上是原則上的代碼。 它尚未經過測試,也未被運行,因此可能包含一些錯誤。 它已作為指南提供。
以下是基於您的代碼和上述答案的基本工作示例。 此外,還在名稱表中添加了一個用於名稱的附加列。
該應用程序添加了兩個用戶(Fred和Mary),然后為每個用戶添加了2個備注。 然后它會提取所有音符,然后是Fred的所有音符,然后是Mary。 然后將3組提取的輸出輸出到日志。
導致 :-
06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEALL: Note isMy Second Note ID is 4 Owned by User who's ID is 2 06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEALL: Note isMy Second Note ID is 3 Owned by User who's ID is 1 06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEALL: Note isMy First Note ID is 2 Owned by User who's ID is 2 06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEALL: Note isMy First Note ID is 1 Owned by User who's ID is 1
06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEFRED: Note isMy First Note ID is 1 Owned by User who's ID is 1 06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEFRED: Note isMy Second Note ID is 3 Owned by User who's ID is 1
06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEMARY: Note isMy First Note ID is 2 Owned by User who's ID is 2 06-20 12:29:22.901 2401-2401/seso56674777notes D/LOGNOTEMARY: Note isMy Second Note ID is 4 Owned by User who's ID is 2
Notes.java
public class Notes {
public static final String TABLE_NAME = "notes";
public static final String NOTE_COLUMN_ID = BaseColumns._ID;
public static final String COLUMN_NOTE = "note";
public static final String NOTE_COLUMN_USERMAP = "usermap";
public static final String CREATE_TABLE_NOTE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
NOTE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_NOTE + " TEXT, " +
NOTE_COLUMN_USERMAP + " INTEGER " +
"REFERENCES " + DBHelper.TABLE_USER_NAME + "(" + DBHelper.USER_COLUMN_ID + ") " +
"ON DELETE CASCADE ON UPDATE CASCADE" +
")";
public Notes(int id, String note, long usermap) {
this.id = id;
this.note = note;
this.usermap = usermap;
}
public Notes() {}
private int id;
private String note;
private long usermap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public long getUsermap() {
return usermap;
}
public void setUsermap(long usermap) {
this.usermap = usermap;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NOTES";
public static final String USER_COLUMN_ID = "idu";
public static final String TABLE_USER_NAME = "name";
public static final String USER_COLUMN_NAME = TABLE_USER_NAME;
public static final String CREATE_TABLE_USER =
"CREATE TABLE " + TABLE_USER_NAME + "("
+ USER_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ USER_COLUMN_NAME + " TEXT UNIQUE "
+ ")";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Notes.CREATE_TABLE_NOTE);
db.execSQL(CREATE_TABLE_USER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Notes.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER_NAME);
onCreate(db);
}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
public long insertUser(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(USER_COLUMN_NAME,username);
return db.insert(TABLE_USER_NAME,null,cv);
}
public long insertNote(String note, long usermap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Notes.COLUMN_NOTE, note);
values.put(Notes.NOTE_COLUMN_USERMAP,usermap);
long id = db.insert(Notes.TABLE_NAME, null, values);
db.close();
return id;
}
public Notes getNote(long id) {
Notes notes = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Notes.TABLE_NAME,
new String[]{Notes.NOTE_COLUMN_ID, Notes.COLUMN_NOTE, Notes.NOTE_COLUMN_USERMAP},
Notes.NOTE_COLUMN_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null
);
if (cursor.moveToFirst()) {
notes = new Notes(
cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)),
cursor.getLong(cursor.getColumnIndex(Notes.NOTE_COLUMN_USERMAP))
);
}
cursor.close();
return notes;
}
public List<Notes> getAllNotes() {
List<Notes> notes = new ArrayList<>();
String selectQuery = "SELECT * FROM " + Notes.TABLE_NAME + " ORDER BY " +
Notes.NOTE_COLUMN_ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
while (cursor.moveToNext()) {
Notes note = new Notes();
note.setId(cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)));
note.setNote(cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)));
note.setUsermap(cursor.getLong(cursor.getColumnIndex(Notes.NOTE_COLUMN_USERMAP)));
notes.add(note);
}
db.close();
return notes;
}
public List<Notes> getNotesByUser(long usermap) {
List<Notes> notes = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Notes.TABLE_NAME,
new String[]{Notes.NOTE_COLUMN_ID, Notes.COLUMN_NOTE,Notes.NOTE_COLUMN_USERMAP},
Notes.NOTE_COLUMN_USERMAP + "=?",
new String[]{String.valueOf(usermap)}, null, null, null, null);
while(cursor.moveToNext()) {
notes.add(new Notes(cursor.getInt(cursor.getColumnIndex(Notes.NOTE_COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Notes.COLUMN_NOTE)),
cursor.getLong(cursor.getColumnIndex(Notes.NOTE_COLUMN_USERMAP)))
);
}
cursor.close();
return notes;
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + Notes.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
}
MainActivity.java
這將所有這些結合在一起
public class MainActivity extends AppCompatActivity {
DBHelper mDBHlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DBHelper(this);
long user1 = mDBHlpr.insertUser("Fred");
long user2 = mDBHlpr.insertUser("Mary");
Notes n1 = new Notes(-1,"My First Note",-1);
Notes n2 = new Notes(-1,"My Second Note",-1);
if (mDBHlpr.getNotesCount() < 1) {
mDBHlpr.insertNote(n1.getNote(), user1);
mDBHlpr.insertNote(n1.getNote(), user2);
mDBHlpr.insertNote(n2.getNote(), user1);
mDBHlpr.insertNote(n2.getNote(), user2);
}
List<Notes> allusers = mDBHlpr.getAllNotes();
List<Notes> fredsnotes = mDBHlpr.getNotesByUser(user1);
List<Notes> marysnotes = mDBHlpr.getNotesByUser(user2);
for (Notes n: allusers) {
logNote("ALL",n);
}
for (Notes n: fredsnotes) {
logNote("FRED",n);
}
for (Notes n: marysnotes) {
logNote("MARY",n);
}
}
private void logNote(String type, Notes n) {
Log.d("LOGNOTE" + type,"Note is" + n.getNote() + "\n\t ID is " + String.valueOf(n.getId()) + "\n\t" + "Owned by User who's ID is " + String.valueOf(n.getUsermap()));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.