How to Build a Sticky Notes Application in Android Studio? - GeeksforGeeks

15 Jun, 2021
We as humans tend to forget some small but important things, and to resolve this we try to write those things up and paste them somewhere, we often have eyes on. And in this digital era, the things we are most likely to see are laptop, computer, or mobile phone screens. For this, we all have once used the Sticky Notes on Windows or Stickies on Mac, today in this article we would be discussing how we can build such an application for Android. 
Now, if we think of something that is sticky i.e. which sticks to the screen, in Android, the component which comes to our mind is the Home screen Widgets. Home Screen Widgets are the best interactive components that stick to the screen and can be resized in any manner. We would be creating an application that also has its own widget. We will first write some text in the main application and save that into a file in memory. At the very moment, we will update the widget with text that the user just saved. And Horray! Our Sticky note is ready.
Here one thing to note is that in Android views are also called Widgets, so to avoid confusion we use the term Home Screen Widgets. These are the broadcast receivers that provide interactive components. They usually show some sort of information and encourage the user to interact with it. For example, it may display time, weather, or emails and once you click on them the main application hosting them would start. Widgets use RemoteViews to build its user interface. With the same permissions as the original application, a RemoteView may be run by another method. As a consequence, the widget runs with the permissions of the application that created it. A Widget’s user interface is determined by a broadcast receiver. This receiver inflates its layout into a RemoteView object.
YouTubeGeeksforGeeks502K subscribersHow to Make a Sticky Notes Android App? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 52:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qfzdZoEiZFQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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 AndroidManifest.xml file
Add the user permissions for reading and write the file from storage. Also, in order to register the widget, we have to create a broadcast receiver with an intent filter.  
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.notes">      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />      <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/Theme.Notes">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>          <!-- To register a widget, you create a broadcast receiver with             an intent filter for the android.appwidget.action.APPWIDGET_UPDATE action-->        <receiver            android:name=".AppWidget"            android:label="StickyNotes">            <intent-filter>                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />              </intent-filter>            <!-- This metadata contains the configuration of your widget,                 the resource attribute contains the layout of your widget as                 it will be seen in the list of widgets -->            <meta-data                android:name="android.appwidget.provider"                android:resource="@xml/new_app_widget_info" />        </receiver>      </application>  </manifest>
Step 3: Creating a Widget  
Follow the steps mentioned in this article Create a Basic Widget of an Android App to add the Widget to your project. The file new_app_widget_info.xml contains code that determines the look of our widget as it would appear in the Widgets list.
Step 4: Working with the AppWidget Class
This class will be formed in the previous step. Go to the AppWidget.java file and refer to the following code. Below is the code for the AppWidget.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.PendingIntent;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.content.Intent;import android.widget.RemoteViews;  // Implementation of App Widget functionalitypublic class AppWidget extends AppWidgetProvider {      // Create an Intent to launch activity    @Override    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {          // Perform this loop procedure for each App Widget        // that belongs to this provider        for (int appWidgetId : appWidgetIds) {                          // Create an Intent to launch MainActivity            Intent launchActivity = new Intent(context, MainActivity.class);                          // Attaching a Pending Intent             // to trigger it when            // application is not alive            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0);                          // Get the layout for the App Widget and attach            // an on-click listener to the button            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);            remoteViews.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);              // Tell the AppWidgetManager to perform an            // update on the current app widget            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);        }    }}
Step 5: Creating the StickyNote Class
This is a helper class that provides the functionality of saving, updating, and retrieving the contents to and from the file. Go to the StickyNote .java file and refer to the following code. Below is the code for the StickyNote .java file. Comments are added inside the code to understand the code in more detail. 
Java
import android.content.Context;  import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;  import static android.content.Context.MODE_PRIVATE;  class StickyNote {      // this function will return    // the content from the text    // file(if any)    String getStick(Context context) {          // get the file from path        File fileEvents = new File(context.getFilesDir().getPath() + "/gfg.txt");                  // create a StringBuilder to store the text from file        StringBuilder text = new StringBuilder();                  try {            // use the BufferedReader            // to Read the file            // efficiently            BufferedReader br = new BufferedReader(new FileReader(fileEvents));            String line;                          // read a single line at a time            // append newline character after each line            while ((line = br.readLine()) != null) {                text.append(line);                text.append('\n');            }                          // close the BufferedReader            br.close();        } catch (IOException e) {            e.printStackTrace();        }          // finally return the         // string i.e. the retrieved data        // from file        return text.toString();    }      // this function saves the new     // content in the file if it    // exists or will create a new one    void setStick(String textToBeSaved, Context context) {                  String text = textToBeSaved;                  // create the FileOutputStream         // to efficiently write the file        FileOutputStream fos = null;        try {            // get the file from storage            fos = context.getApplicationContext().openFileOutput("gfg.txt", MODE_PRIVATE);                          // write to the file at once            fos.write(text.getBytes());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.widget.EditText;import android.widget.RemoteViews;import android.widget.Toast;  import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      EditText mEditText;          // creating a new note    StickyNote note = new StickyNote();      @Override    protected void    onCreate(android.os.Bundle savedInstanceState) {          setContentView(R.layout.activity_main);        super.onCreate(savedInstanceState);          // getting the reference of the EditText        mEditText = findViewById(R.id.editText);                  // retrieve the text from the saved file in        // memory(if any) and set it to the edittext        mEditText.setText(note.getStick(this));    }      // function to update the     // Widget(Sticky Note) every time    // user saves the note    public void updateWidget() {        // the AppWidgetManager helps        // us to manage all the        // widgets from this app        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);                  // the RemoteViews class allows us to inflate a        // layout resource file hierarchy and provides some        // basic operations for modifying the content of the        // inflated hierarchy        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.new_app_widget);                  // by using ComponentName class we can get specific        // application component and to identify the        // component we pass the package name and the class        // name inside of that package        ComponentName thisWidget = new ComponentName(this, AppWidget.class);          // update the text of the textview of the widget        remoteViews.setTextViewText(R.id.appwidget_text, mEditText.getText().toString());                  // finally us the AppWidgetManager instance to        // update all the widgets        appWidgetManager.updateAppWidget(thisWidget, remoteViews);    }      // this function saves     // the current status     // of the EditText    public void saveButton(android.view.View v) {        // update the content of file stored in the memory        note.setStick(mEditText.getText().toString(), this);        updateWidget();        Toast.makeText(this, "Updated Successfully!!", Toast.LENGTH_SHORT).show();    }}
Step 7: Layout file of our Widget
Since we only want our widget to hold the text, we just add the TextView in the layout resource file which would be updated from time to time. 
XML
<FrameLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/widgetLayout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#FDD835"    android:orientation="horizontal"    android:padding="8dp">      <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">                  <TextView            android:id="@+id/appwidget_text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Text"            android:textColor="#ffffff"            android:textSize="20sp"            tools:layout_editor_absoluteX="1dp"            tools:layout_editor_absoluteY="1dp" />              </LinearLayout>      </FrameLayout>
Output:
Github Project Link
For all the drawable resource files please refer to the following GitHub kink: https://github.com/raghavtilak/StickyNotes
You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc.You can make some UI improvements.You can create multiple Sticky Notes, by saving the data into the database and fetching the same.Also, you can try adding some different views to the Widget.
You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc.
You can make some UI improvements.
You can create multiple Sticky Notes, by saving the data into the database and fetching the same.
Also, you can try adding some different views to the Widget.
Android-Studio
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java