简体   繁体   中英

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. My particular username is currently saved in Shared Preferences. Please show me the appropriate solution for this.

DB Helper:

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). Assuming that a Note will have just one user (who owns the note). Then you could add a column to the table where you store the 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)). It will be an integer value (potentially long in 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

+ NOTE_COLUMN_USERMAP + " INTEGER "; //<<<<<<<<<comma if needed after INTEGER

Or, if you may want to introduce FOREIGN KEY constraints and use

+ 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. You should also have a constructor that includes the id of the user for use when retrieving a Note from the database.

You would then need to make changes to the DBHelper's methods to cater for the extra column. eg

The insertNote method could become :-

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 :-

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;
}
  • Note the above assumes the constructor has the value for the user mapping as the last.
  • Note checking a Cursor for null is useless, it will never be null when returned from an SQliteDatabase method. Hence the above uses the result from the moveToFirst method to determing if a row exists or not.
  • Note the above will return null (rather than failing) should the Note not be found.

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.

eg getNotesByUser could be :-

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 simpler while loop ie as the moveToNext method returns false when the move cannot be made (ie when at after last row) then there is no need to moveToFirst as it will do that for the first row.

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.

Working Example

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. It then extracts all notes and then all notes for Fred and then for Mary. The 3 sets of extracted output are then output to the log.

Resulting in :-

For All Notes for All users:-

 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 

For Fred (user'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 

For Mary (user's ID is 2):-

 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 

The code

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;
    }
}
  • Note the addition that overides the onConfigure method, this turns ForeignKey support on (otherwise the Foreign Key definitions are ignored).
  • Note AUTOINCREMENT has been removed, it is not necessary and has overheads.
  • Note the addition of the name column for the name table and that it has a unqiue constraint.

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()));
    }
}
  • Note that the above is only intended to be run once. If subsequently run both the id's for Fred and Mary will be -1 as the rows will not be added due to the duplicate name and hence there will be no notes extracted into fredsnotes and marynotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM