How to Build a Simple Notes App in Android? - GeeksforGeeks

13 Oct, 2020
Notes app is used for making short text notes, update when you need them, and trash when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick access to the notes. Likewise, here let’s create an Android App to learn how to create a simple NotesApp. So in this article let’s build a Notes App in which the user can add any data, remove any data as well as edit any data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
In the activity_main.xml file add a ListView and a TextView. ListView is added to display the list of auto-saved notes and TextView is used to simply display the GFG text. Below is the complete code for the activity_main.xml file. 
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     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=".MainActivity">      <!--Adding a ListView -->    <ListView        android:id="@+id/listView"        android:layout_width="409dp"        android:layout_height="601dp"        android:layout_marginTop="80dp"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />      <!--Adding a TextView -->    <TextView        android:id="@+id/textView2"        android:layout_width="0dp"        android:layout_height="0dp"        android:gravity="center_horizontal"        android:text="GFG"        android:textColor="@android:color/holo_green_dark"        android:textSize="30sp"        app:layout_constraintBottom_toTopOf="@+id/listView"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Step 3: Create a new layout to show the menu
Go to app > res > right-click > New > Directory and named it as menu. Then click on app > res > menu > New > Menu resource file and name the file as add_note_menu.  Below is the code for the add_note_menu.xml file. 
XML
<?xml version="1.0" encoding="utf-8"?><!--Adding Menu to show the function to     User to delete and edit the data--><menu xmlns:android="http://schemas.android.com/apk/res/android">        <item android:id="@+id/add_note" android:title="Add note"></item>    </menu>
Step 4: Create a new empty activity
Go to app > java > right-click > New > Activity > Empty Activity and name it as NoteEditorActivity. In this activity, we are going to type our notes. So in the activity_note_editor.xml file add an EditText to add data to ListView. Below is the code for the activity_note_editor.xml file. 
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     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=".NoteEditorActivity">      <!--Adding Edit Text To add data to List View-->    <EditText        android:id="@+id/editText"        android:layout_width="0dp"        android:layout_height="0dp"        android:ems="10"        android:gravity="top|left"        android:inputType="textMultiLine"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />    </androidx.constraintlayout.widget.ConstraintLayout>
Now in the NoteEditorActivity.java file write code to store data. Add SharedPreference into the App to store the data in the Phone Memory. Setting Values in SharedPreference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(“name”, “Elena”);
editor.putInt(“idName”, 12);
editor.apply();
Retrieve data from SharedPreference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);  
// No name defined is the default value.
String name = prefs.getString(“name”, “No name defined”);
// 0 is the default value.
int idName = prefs.getInt(“idName”, 0);
Below is the complete code for the NoteEditorActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;import java.util.HashSet;  public class NoteEditorActivity extends AppCompatActivity {    int noteId;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_note_editor);          EditText editText = findViewById(R.id.editText);          // Fetch data that is passed from MainActivity        Intent intent = getIntent();          // Accessing the data using key and value        noteId = intent.getIntExtra("noteId", -1);        if (noteId != -1) {            editText.setText(MainActivity.notes.get(noteId));        } else {              MainActivity.notes.add("");            noteId = MainActivity.notes.size() - 1;            MainActivity.arrayAdapter.notifyDataSetChanged();          }          editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {                // add your code here            }              @Override            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {                MainActivity.notes.set(noteId, String.valueOf(charSequence));                MainActivity.arrayAdapter.notifyDataSetChanged();                // Creating Object of SharedPreferences to store data in the phone                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);                HashSet<String> set = new HashSet(MainActivity.notes);                sharedPreferences.edit().putStringSet("notes", set).apply();            }              @Override            public void afterTextChanged(Editable editable) {                // add your code here            }        });    }}
Step 5: Working with the MainAtivity.java file
Now set up all the things in the MainActivity.java file. Calling the NoteEditorActivity.java code, join all the XML code to java and run the app. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.annotation.NonNull;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashSet;  public class MainActivity extends AppCompatActivity {      static ArrayList<String> notes = new ArrayList<>();    static ArrayAdapter arrayAdapter;      @Override    public boolean onCreateOptionsMenu(Menu menu) {          MenuInflater menuInflater = getMenuInflater();        menuInflater.inflate(R.menu.add_note_menu, menu);          return super.onCreateOptionsMenu(menu);    }      @Override    public boolean onOptionsItemSelected(@NonNull MenuItem item) {        super.onOptionsItemSelected(item);          if (item.getItemId() == R.id.add_note) {              // Going from MainActivity to NotesEditorActivity            Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);            startActivity(intent);            return true;        }          return false;    }      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          ListView listView = findViewById(R.id.listView);        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);        HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);          if (set == null) {              notes.add("Example note");        } else {            notes = new ArrayList(set);        }          // Using custom listView Provided by Android Studio        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes);          listView.setAdapter(arrayAdapter);          listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {                  // Going from MainActivity to NotesEditorActivity                Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);                intent.putExtra("noteId", i);                startActivity(intent);              }        });          listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {            @Override            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {                  final int itemToDelete = i;                // To delete the data from the App                new AlertDialog.Builder(MainActivity.this)                        .setIcon(android.R.drawable.ic_dialog_alert)                        .setTitle("Are you sure?")                        .setMessage("Do you want to delete this note?")                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {                            @Override                            public void onClick(DialogInterface dialogInterface, int i) {                                notes.remove(itemToDelete);                                arrayAdapter.notifyDataSetChanged();                                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);                                HashSet<String> set = new HashSet(MainActivity.notes);                                sharedPreferences.edit().putStringSet("notes", set).apply();                            }                        }).setNegativeButton("No", null).show();                return true;            }        });    }}
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Services in Android with Example
CardView in Android With Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples