[英]How to store and retrieve data for a particular user using SQlite in android
I want to save user credential(name) and then on that name i want to save some data for that particular user. 我想保存用户凭据(名称),然后在该名称上我想为该特定用户保存一些数据。 I am using SQlite for this and I have successfully saving the data but i can't make it for the particular user as of Now it is showing for all the user.
我正在使用SQlite并且我已成功保存数据但我无法为特定用户制作它现在它正在为所有用户显示。 My particular username is currently saved in Shared Preferences.
我的特定用户名目前保存在共享首选项中。 Please show me the appropriate solution for this.
请告诉我适当的解决方案。
DB Helper: 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;
}
}
Notes: 笔记:
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;
}
}
Fragment 分段
@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);
}
}
});
}
}
You appear to need a relationship between a Note (child) and it's user (parent). 您似乎需要Note(子)和它的用户(父)之间的关系。 Assuming that a Note will have just one user (who owns the note).
假设一个Note只有一个用户(谁拥有该笔记)。 Then you could add a column to the table where you store the Notes.
然后,您可以在存储Notes的表中添加一列。
As the User table has the id column defined using INTEGER PRIMARY KEY
this column is an ideal candidate for the relationship (it is indexed and also unique (implicitly)). 由于User表具有使用
INTEGER PRIMARY KEY
定义的id列,因此该列是关系的理想候选者(它是索引的,也是唯一的(隐式))。 It will be an integer value (potentially long in java). 它将是一个整数值(在java中可能很长)。
To be consistent you'd want to define a constant for the column name so add :- 为了保持一致,你需要为列名定义一个常量,所以添加: -
public static final String NOTE_COLUMN_USERMAP = "usermap";
You could then define change the CREATE_TABLE_NOTE constant to include 然后,您可以定义更改CREATE_TABLE_NOTE常量以包含
+ NOTE_COLUMN_USERMAP + " INTEGER "; //<<<<<<<<<comma if needed after INTEGER
Or, if you may want to introduce FOREIGN KEY constraints and use 或者,如果您可能想要引入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
You would make a complimentary change to the Notes class/object to store the id of the user (the map/relationship) (preferably as a long) of the owning user in the class and add a getter and a setter for the id of the user. 您将对Notes类/对象进行免费更改,以存储类中拥有用户的用户ID(地图/关系)(最好是长),并为id的id添加一个getter和setter。用户。 You should also have a constructor that includes the id of the user for use when retrieving a Note from the database.
您还应该有一个构造函数,其中包含从数据库中检索Note时要使用的用户ID。
You would then need to make changes to the DBHelper's methods to cater for the extra column. 然后,您需要更改DBHelper的方法以满足额外的列。 eg
例如
The insertNote method could become :- 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;
}
The getNotes method could become :- 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;
}
but i can't make it for the particular user as of Now it is showing for all the user
但我无法为特定用户制作它现在它正在为所有用户显示
After the above then you can write a query that includes a WHERE clause based upon the usermap column. 在上面之后,您可以编写一个包含基于usermap列的WHERE子句的查询。
eg getNotesByUser could be :- 例如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;
}
Note the above is in-principle code. 注意以上是原则上的代码。 It has not been tested nor has it been run, it may therefore contain some errors.
它尚未经过测试,也未被运行,因此可能包含一些错误。 It has been provided as a guide.
它已作为指南提供。
The following is a basic working example based upon your code and the above answer. 以下是基于您的代码和上述答案的基本工作示例。 Additionally an additional column has been added to the name table for the name of the user.
此外,还在名称表中添加了一个用于名称的附加列。
The App adds two users (Fred and Mary) and then adds 2 notes for each user. 该应用程序添加了两个用户(Fred和Mary),然后为每个用户添加了2个备注。 It then extracts all notes and then all notes for Fred and then for Mary.
然后它会提取所有音符,然后是Fred的所有音符,然后是Mary。 The 3 sets of extracted output are then output to the log.
然后将3组提取的输出输出到日志。
Resulting in :- 导致 :-
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 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 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 MainActivity.java
This brings it all together 这将所有这些结合在一起
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.