mmaxpo
7/10/2019 - 5:23 PM

Room Databace




    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"
    implementation 'com.android.support:recyclerview-v7:28.0.0'

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_sharedPref:
                startActivity(new Intent(MainActivity.this, PersonalInfoActivity.class));
                break;
            case R.id.btn_main_room:
                startActivity(new Intent(MainActivity.this, NotesActivity.class));
                break;
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btn_main_sharedPref"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Shared Pref"
        android:onClick="onClick" />

    <Button
        android:id="@+id/btn_main_room"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Room"
        android:onClick="onClick" />
    <Button
        android:id="@+id/btn_main_broadcastReceiver"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Broadcast Receiver"
        android:onClick="onClick" />

</LinearLayout>

@Database(entities = {Note.class}, version = 1, exportSchema = true)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase appDatabase;

    public abstract NoteDao noteDao();

    public static AppDatabase getInstance(Context context){
        if (appDatabase==null){
            appDatabase= Room.databaseBuilder(context,AppDatabase.class,"db_7learn").allowMainThreadQueries().build();
        }
        return appDatabase;
    }
}

public class EditNoteDialog extends DialogFragment {
    private OnNoteEdit onNoteEdit;
    private Note note;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
            note = getArguments().getParcelable("note");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnNoteEdit) {
            onNoteEdit = (OnNoteEdit) context;
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_edit_note, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(view);
        final EditText titleEt = view.findViewById(R.id.et_editNote_title);
        final EditText descEt = view.findViewById(R.id.et_editNote_desc);
        if (note != null) {
            titleEt.setText(note.getTitle());
            descEt.setText(note.getDescripion());
        }
        Button saveNoteBtn = view.findViewById(R.id.btn_editNote_save);
        saveNoteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (titleEt.length() > 0 && descEt.length() > 0) {

                    if (note != null) {
                        note.setTitle(titleEt.getText().toString());
                        note.setDescripion(descEt.getText().toString());
                        onNoteEdit.onEdit(note);
                    } else {
                        Note note = new Note();
                        note.setTitle(titleEt.getText().toString());
                        note.setDescripion(descEt.getText().toString());
                        onNoteEdit.onEdit(note);
                    }
                    dismiss();

                }
            }
        });
        return builder.create();
    }

    public static EditNoteDialog newInstance(Note note) {

        Bundle args = new Bundle();
        args.putParcelable("note", note);
        EditNoteDialog fragment = new EditNoteDialog();
        fragment.setArguments(args);
        return fragment;
    }

    public interface OnNoteEdit {
        void onEdit(Note note);
    }
}

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> {
    private NoteUiCallback noteUiCallback;
    private List<Note> notes = new ArrayList<>();

    public NoteAdapter(NoteUiCallback noteUiCallback) {
        this.noteUiCallback = noteUiCallback;
    }

    public void addNotes(List<Note> notes) {
        this.notes.addAll(notes);
        notifyDataSetChanged();
    }

    public void addNote(Note note) {
        this.notes.add(0, note);
        notifyItemInserted(0);
    }

    public void clear(){
        this.notes.clear();
        notifyDataSetChanged();
    }

    public void updateNote(Note note) {
        for (int i = 0; i < notes.size(); i++) {
            if (notes.get(i).getId() == note.getId()) {
                notes.set(i, note);
                notifyItemChanged(i);
                return;
            }
        }
    }


    @NonNull
    @Override
    public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new NoteViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_note, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NoteViewHolder noteViewHolder, int i) {
        noteViewHolder.bindNote(notes.get(i));
    }

    @Override
    public int getItemCount() {
        return notes.size();
    }

    public class NoteViewHolder extends RecyclerView.ViewHolder {
        private TextView titleTv;
        private TextView descTv;
        private Button deleteButton;
        private Button editButton;

        public NoteViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTv = itemView.findViewById(R.id.tv_note_title);
            descTv = itemView.findViewById(R.id.tv_note_desc);
            deleteButton = itemView.findViewById(R.id.btn_note_delete);
            editButton = itemView.findViewById(R.id.btn_note_edit);
        }

        public void bindNote(final Note note) {
            titleTv.setText(note.getTitle());
            descTv.setText(note.getDescripion());
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noteUiCallback.onDeleteBtnClick(note, getAdapterPosition());
                }
            });
            editButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noteUiCallback.onEditBtnClick(note, getAdapterPosition());
                }
            });
        }
    }

    public void deleteNote(int position) {
        notes.remove(position);
        notifyItemRemoved(position);
    }

    public interface NoteUiCallback {
        void onDeleteBtnClick(Note note, int position);

        void onEditBtnClick(Note note, int position);
    }
}

public class NotesActivity extends AppCompatActivity implements EditNoteDialog.OnNoteEdit, NoteAdapter.NoteUiCallback {
    private NoteDao noteDao;
    private NoteAdapter noteAdapter;
    private boolean isInEditMode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        AppDatabase appDatabase = AppDatabase.getInstance(this);
        noteDao = appDatabase.noteDao();
        List<Note> notes = noteDao.getAll();
        RecyclerView recyclerView = findViewById(R.id.rv_notes);
        recyclerView.setLayoutManager(new LinearLayoutManager(
                this, LinearLayoutManager.VERTICAL, false
        ));
        noteAdapter = new NoteAdapter(this);
        recyclerView.setAdapter(noteAdapter);
        noteAdapter.addNotes(notes);

        Button addNoteBtn = findViewById(R.id.btn_notes_addNewNote);
        addNoteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isInEditMode = false;
                EditNoteDialog dialog = new EditNoteDialog();
                dialog.show(getSupportFragmentManager(), null);
            }
        });


        Button deleteBtn = findViewById(R.id.btn_notes_deleteAll);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noteDao.deleteAll();
                noteAdapter.clear();
            }
        });
    }

    @Override
    public void onEdit(Note note) {
        if (isInEditMode) {
            noteDao.update(note);
            noteAdapter.updateNote(note);
        } else {
            noteDao.save(note);
            noteAdapter.addNote(note);
        }

    }

    @Override
    public void onDeleteBtnClick(Note note, int position) {
        noteDao.delete(note);
        noteAdapter.deleteNote(position);
    }

    @Override
    public void onEditBtnClick(Note note, int position) {
        isInEditMode = true;
        EditNoteDialog editNoteDialog = EditNoteDialog.newInstance(note);
        editNoteDialog.show(getSupportFragmentManager(), null);
    }
}

public class AppSetting {
    private SharedPreferences sharedPreferences;
    private static final String KEY_FIRST_NAME = "first_name";
    private static final String KEY_LAST_NAME = "last_name";
    private static final String KEY_AGE = "age";
    private static final String KEY_RATE = "rate";

    public AppSetting(Context context) {
        sharedPreferences = context.getSharedPreferences("setting", Context.MODE_PRIVATE);
    }


    public void saveUserInfo(String firstName, String lastName, int age, float rate) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_FIRST_NAME, firstName);
        editor.putString(KEY_LAST_NAME, lastName);
        editor.putInt(KEY_AGE, age);
        editor.putFloat(KEY_RATE, rate);
        editor.apply();
    }


    public String getFirstName() {
        return sharedPreferences.getString(KEY_FIRST_NAME, "");
    }

    public String getLastName() {
        return sharedPreferences.getString(KEY_LAST_NAME, "");
    }

    public int getAge() {
        return sharedPreferences.getInt(KEY_AGE, 0);
    }

    public float getRate() {
        return sharedPreferences.getFloat(KEY_RATE, 0);
    }
}

public class PersonalInfoActivity extends AppCompatActivity {
    private AppSetting setting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        setting = new AppSetting(this);
        final EditText firstNameEt = findViewById(R.id.et_main_firstName);
        final EditText lastNameEt = findViewById(R.id.et_main_lastName);
        final EditText ageEt = findViewById(R.id.et_main_age);
        final EditText rateEt = findViewById(R.id.et_main_rate);

        Button saveBtn = findViewById(R.id.btn_main_save);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setting.saveUserInfo(firstNameEt.getText().toString(),
                        lastNameEt.getText().toString(),
                        Integer.parseInt(ageEt.getText().toString()),
                        Float.parseFloat(rateEt.getText().toString()));
            }
        });

        firstNameEt.setText(setting.getFirstName());
        lastNameEt.setText(setting.getLastName());
        ageEt.setText(String.valueOf(setting.getAge()));
        rateEt.setText(String.valueOf(setting.getRate()));
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".notes.NotesActivity">

    <Button
        android:id="@+id/btn_notes_addNewNote"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Add new note" />

    <Button
        android:id="@+id/btn_notes_deleteAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/btn_notes_addNewNote"
        android:text="Delete All" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_notes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/btn_notes_deleteAll">

    </android.support.v7.widget.RecyclerView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".sharedpref.PersonalInfoActivity">

    <EditText
        android:id="@+id/et_main_firstName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="First Name" />

    <EditText
        android:id="@+id/et_main_lastName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Last Name" />

    <EditText
        android:id="@+id/et_main_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age" />

    <EditText
        android:id="@+id/et_main_rate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Rate" />

    <Button
        android:id="@+id/btn_main_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save" />


</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/et_editNote_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter title"/>

    <EditText
        android:id="@+id/et_editNote_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter description"/>

    <Button
        android:id="@+id/btn_editNote_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_note_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/tv_note_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_note_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Edit"/>

        <Button
            android:id="@+id/btn_note_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"/>
    </LinearLayout>
</LinearLayout>