Create a Note Book App using Java in Android Studio

In this article we will learn how to create a Note Book app in android Studio. Many Note Book app in the Google Play Store. If you need to create your own note book app then this article will help to create a Note Book app. To create a Note Book app we need to learn ListView, Custom Adapter, SQLite, Intent, Dialog. This article we will learn how to use custom adapter in List View, How to add, modify, delete data into a SQLite Database. We also learn how to use google provided android matrial dialog in our application. We will learn Step by Step.

Create a Note Book App using Java in Android Studio

Step 1: Setup Resource File

We need to setup our resource file because this resource file are use in our application. We need 5 resource file into our application. 4 icon and one drawable resource file are used to our design better look.

First we setup 4 icon just using our android default image assets. You can create this from Right click on “Drawable” => “New” => “Image Asset“. Then select Action Bar and Tab Icons as Icon Type and then click on Clip Art Icon, Then you see few icons.

  1. Type add into Search Box then see a icon name add select and name it ic_plus and change HOLO_DARK as Theme finaly click next->Finish..
  2. Type more into Search Box then see a icon name more vert select and name it ic_more_vert_white and change HOLO_DARK as Theme.
  3. Type archive into Search Box then see a icon name archive select and name it archive and change HOLO_LIGHT as Theme.
  4. Type star into Search Box then see a icon name star border select and name it fav_off.

Now our final task is create new drawable resource file. You can create this from Right click on “app” => “New” => “Android Resource file“. Then select Drawble as Resource type. I named it ripple_btn.xml. This activity also show a ripple effect when user click on it.

This is the code for our ripple_btn.xml file:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#000000"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
            <corners android:radius="0dp" />
        </shape>
    </item>
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <gradient
                android:angle="90"
                android:endColor="@color/colorAccent"
                android:startColor="@color/colorPrimary"
                android:type="linear" />
            <corners android:radius="26dp" />
        </shape>
    </item>
</ripple>

I am using external color for changing the Toolbar, Fab Button color. My color.xml file look like this.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#262626</color>
    <color name="colorPrimaryDark">#000000</color>
    <color name="colorAccent">#757575</color>
</resources>

Also add some data in styles.xml file for changing the AlartDialog Button color. Here is my styles.xml file look like

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="alertDialogTheme">@style/AlertDialogTheme</item>
    </style>

    <style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
        <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
        <item name="buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
        <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    </style>

    <style name="NeutralButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">#f00</item>
    </style>

    <style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">#999</item>
    </style>

    <style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">#000</item>
    </style>

</resources>

Step 2: Building the user interface

First we create a menu that will show the right side into the Toolbar. To create menu first we create a directory under res directory name menu. Right click on res then res->new->Android Resource Directory then select Resource Type as menu finally click ok.

Then create a menu resource file name menu.xml. Right click on menu then menu->new->Menu Resource Directory then select Resource Type as menu finally click ok . Copy and paste the given bellow code into this create menu.xml file.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/overflowMenu"
        android:icon="@drawable/ic_more_vert_white"
        android:title=""
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/archive"
                android:icon="@drawable/archive"
                android:orderInCategory="100"
                android:title="Archive" />
        </menu>
    </item>
</menu>

Now we edit our activity_main.xml, In this activity we need a ListView, a Floating Action Button to add new Note Book Data and a Menu into the Toolbar. If we add Floating Action Button we need to add a gradle in build.gradle file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
	...
        ...
	...

    implementation 'com.google.android.material:material:1.0.0'
}

activity_main.xml look like this

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f5f5f5"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- Main content -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ListView
            android:id="@+id/ListView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@android:color/transparent"/>
        <TextView
            android:id="@+id/empty_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Empty"/>
    </RelativeLayout>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:contentDescription="ADD"
        app:srcCompat="@drawable/ic_plus"
        tools:ignore="VectorDrawableCompat" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Now we need to design how our ListView Item Look Like. Create a new layout resource file and name it activity_notebook_list_items.xml. Paste the bellow code into this activity.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:padding="5dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:orientation="vertical"
            android:weightSum="6">
            <TextView
                android:id="@+id/date"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:gravity="left|center"
                android:text="Date"
                android:textSize="9dp"/>
            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="#33000000"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:layout_weight="1">
                    <ImageView
                        android:id="@+id/fev"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:scaleType="fitXY"
                        android:src="@drawable/fev_off" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:layout_weight="5"
                    android:layout_marginLeft="5dp">
                    <TextView
                        android:id="@+id/title"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:text="Title"
                        android:textStyle="bold"
                        android:textSize="16dp"
                        android:fontFamily="sans-serif-condensed-light"
                        android:textColor="#000000" />
                    <TextView
                        android:id="@+id/description"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Description"
                        android:textSize="12dp"
                        android:ellipsize="end"
                        android:maxLines="2"
                        android:textColor="#99000000" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#33000000"/>
</LinearLayout>

Now we need to create a layout resource file to use to add new Note Book data and name it activity_add_modify_notebook_data.xml . In this activity we need Two Edit Text to input Title and Description and also need a button to save the data into SQLite Database. This activity look like this,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">
    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Title"
        android:fontFamily="sans-serif-condensed-light"
        android:textStyle="bold"/>
    <EditText
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginTop="10dp"
        android:background="@android:color/transparent"
        android:hint="Description"
        android:textSize="16dp"/>
    <Button
        android:id="@+id/save_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:text="ADD"
        android:textColor="@android:color/white"
        android:background="@drawable/ripple_btn"/>
</RelativeLayout>

Now we create our last layout activity name activity_archived.xml. This activity help to show the archive list. Paste the bellow code into this activity,

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- Main content -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ListView
            android:id="@+id/ListView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@android:color/transparent"/>
        <TextView
            android:id="@+id/empty_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Empty"/>
    </RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 3: Coding the Functionality

We need 5 java class to complete your Note Book application. One for Creating SQLite Database and all database related operation, One for our home page control and show out all notes data, One for control list view, One for add and modify Note Book data, Finally last one for control archive activity. We will create one by one.

  1. First we create our SQLite Controller Database class name DBHelper.java. Copy and paste the given bellow code into this created DBHelper.java class without changing package name. You can also be able to modify as you need.
package com.andrious.notebook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.Date;


public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "NoteBookDBHelper.db";
    public static final String TABLE_NAME = "notebook";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL(
                "CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, title TEXT, description TEXT, created_at DATETIME, fevourite INTEGER, status INTEGER)"
        );
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }


    public boolean insertNoteBookData(String title, String description, String created_at) {
        Date date;
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", title);
        contentValues.put("description", description);
        contentValues.put("created_at", created_at);
        contentValues.put("fevourite", 0);
        contentValues.put("status", 0);
        db.insert(TABLE_NAME, null, contentValues);
        return true;
    }

    public boolean updateNoteBookData(String id, String title, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("title", title);
        contentValues.put("description", description);

        db.update(TABLE_NAME, contentValues, "id = ? ", new String[]{id});
        return true;
    }

    public boolean deleteNoteBookData(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, "id = ? ", new String[]{id});
        return true;
    }

    public boolean updateNoteBookFev(String id, Integer fev) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("fevourite", fev);

        db.update(TABLE_NAME, contentValues, "id = ? ", new String[]{id});
        return true;
    }

    public boolean updateNoteBookStatus(String id, Integer status) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("status", status);

        db.update(TABLE_NAME, contentValues, "id = ? ", new String[]{id});
        return true;
    }

    public Cursor getNoteBookData() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE status = '0' order by id asc", null);
        return res;

    }
    public Cursor getArchivedData() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE status = '1' order by id asc", null);
        return res;

    }

    public Cursor getSingleNoteBookData(String id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '"+id+"'", null);
        return res;

    }
}

2. Second we modify our home activity controller class name MainActivity.java. Copy and paste the given bellow code into this MainActivity.java class without changing package name.

package com.andrious.notebook;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
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.ListView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    DBHelper mydb;
    ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
    ListView simpleList;
    FloatingActionButton add_button;
    TextView empty_text;

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

        mydb = new DBHelper(this);
        empty_text = (TextView) findViewById(R.id.empty_text);
        simpleList = (ListView) findViewById(R.id.ListView);
        simpleList.setEmptyView(empty_text);
        add_button = findViewById(R.id.add_button);
        add_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this,AddAndModifyNoteBookData.class);
                i.putExtra("action","add");
                startActivity(i);
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //respond to menu item selection
        switch (item.getItemId()) {
            case R.id.archive:
                startActivity(new Intent(MainActivity.this, ArchivedActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        populateData();
    }

    public void populateData() {
        mydb = new DBHelper(this);

        runOnUiThread(new Runnable() {
            public void run() {
                fetchDataFromDB();
            }
        });
    }

    public void fetchDataFromDB() {
        dataList.clear();

        Cursor cursor = mydb.getNoteBookData();
        loadDataList(cursor, dataList);
    }

    public void loadDataList(Cursor cursor, final ArrayList<HashMap<String, String>> List) {
        if (cursor != null) {
            cursor.moveToFirst();
            while (cursor.isAfterLast() == false) {

                HashMap<String, String> mapData = new HashMap<String, String>();
                mapData.put("id", cursor.getString(0).toString());
                mapData.put("title", cursor.getString(1).toString());
                mapData.put("description", cursor.getString(2).toString());
                mapData.put("date", cursor.getString(3).toString());
                mapData.put("fevourite", cursor.getString(4).toString());
                mapData.put("status", cursor.getString(5).toString());
                List.add(mapData);
                cursor.moveToNext();
            }
            ListNoteBookAdapter adapter = new ListNoteBookAdapter(this, List, mydb);
            simpleList.setAdapter(adapter);
            simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(List.get(+position).get("title"));
                    builder.setMessage(List.get(+position).get("description"));
                    builder.setNeutralButton("ARCHIVE", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.updateNoteBookStatus(List.get(+position).get("id"), 1);
                            populateData();
                        }
                    });

                    builder.setNegativeButton("EDIT", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            Intent i = new Intent(MainActivity.this,AddAndModifyNoteBookData.class);
                            i.putExtra("id",List.get(+position).get("id"));
                            i.putExtra("title",List.get(+position).get("title"));
                            i.putExtra("description",List.get(+position).get("description"));
                            i.putExtra("action","edit");
                            startActivity(i);
                        }
                    });
                    builder.setPositiveButton("CANCEL", null);
                    builder.show();
                }
            });
        }
    }


}

3. Third we create our custom adapter class name ListNoteBookAdapter.java that will help to modify the List View Items. Copy and paste the given bellow code into this created ListNoteBookAdapter.java class without changing package name.

package com.andrious.notebook;


import android.app.Activity;
import android.database.Cursor;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;


public class ListNoteBookAdapter extends BaseAdapter {
    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private DBHelper database;

    public ListNoteBookAdapter(Activity a, ArrayList<HashMap<String, String>> d, DBHelper mydb) {
        activity = a;
        data = d;
        database = mydb;
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ListTaskViewHolder holder = null;
        if (convertView == null) {
            holder = new ListTaskViewHolder();
            convertView = LayoutInflater.from(activity).inflate(R.layout.activity_notebook_list_items, parent, false);
            holder.title = convertView.findViewById(R.id.title);
            holder.description = convertView.findViewById(R.id.description);
            holder.date = convertView.findViewById(R.id.date);
            holder.fevourite = convertView.findViewById(R.id.fev);
            convertView.setTag(holder);
        } else {
            holder = (ListTaskViewHolder) convertView.getTag();
        }


        final HashMap<String, String> singleTask = data.get(position);
        final ListTaskViewHolder tmpHolder = holder;

        holder.title.setId(position);
        holder.description.setId(position);
        holder.date.setId(position);
        holder.fevourite.setId(position);

        try {

            holder.title.setText(Html.fromHtml(singleTask.get("title")));
            holder.description.setText(Html.fromHtml(singleTask.get("description")));
            holder.date.setText(Html.fromHtml(singleTask.get("date")));
            if(singleTask.get("fevourite").trim().contentEquals("0")){
                holder.fevourite.setImageResource(R.drawable.fev_off);
            }else{
                holder.fevourite.setImageResource(R.drawable.fev_on);
            }

            holder.fevourite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor cursor = database.getSingleNoteBookData(singleTask.get("id"));
                    cursor.moveToFirst();
                    if(cursor.getString(4).toString().contentEquals("0")){
                        database.updateNoteBookFev(singleTask.get("id"),1);
                        tmpHolder.fevourite.setImageResource(R.drawable.fev_on);
                    }else{
                        database.updateNoteBookFev(singleTask.get("id"),0);
                        tmpHolder.fevourite.setImageResource(R.drawable.fev_off);
                    }
                }
            });


        } catch (Exception e) {
        }
        return convertView;
    }
}

class ListTaskViewHolder {
    TextView title;
    TextView description;
    TextView date;
    ImageView fevourite;
}

4. Fourth we create our add and modify List View Data controller class name AddAndModifyNoteBookData.java. Copy and paste the given bellow code into this created AddAndModifyNoteBookData.java class without changing package name.

package com.andrious.notebook;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AddAndModifyNoteBookData extends AppCompatActivity {
    DBHelper mydb;
    String title_data, des_data,i_action,i_id;
    TextView title,description;
    Button save_btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = getIntent();
        i_action = i.getStringExtra("action");
        if(i_action.trim().contentEquals("edit")){
            getSupportActionBar().setTitle("Udpate");
        }else{
            getSupportActionBar().setTitle("Add New");
        }

        setContentView(R.layout.activity_add_modify_notebook_data);

        mydb = new DBHelper(this);
        title = findViewById(R.id.title);
        description = findViewById(R.id.description);
        save_btn = findViewById(R.id.save_btn);


        if(i_action.trim().contentEquals("edit")){
            i_id = i.getStringExtra("id");
            String i_title = i.getStringExtra("title");
            String i_des = i.getStringExtra("description");

            title.setText(i_title);
            description.setText(i_des);
            save_btn.setText("SAVE");
        }


        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title_data = title.getText().toString();
                des_data = description.getText().toString();

                if(i_action.trim().contentEquals("edit") && title_data.length() > 3){
                    if(title_data.trim().length() > 0){
                        mydb.updateNoteBookData(i_id, title_data, des_data);
                        finish();
                    }else {
                        Toast.makeText(getApplicationContext(),"Title Field is empty !!!",Toast.LENGTH_SHORT).show();
                    }

                }
                if(i_action.trim().contentEquals("add")){
                    String date = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(new Date());
                    if(title_data.trim().length() > 0){
                        mydb.insertNoteBookData(title_data, des_data, date.toString());
                        finish();
                    }else {
                        Toast.makeText(getApplicationContext(),"Title Field is empty !!!",Toast.LENGTH_SHORT).show();
                    }

                }


            }
        });


        //mydb.insertNoteBookData(title_data, des_data, date.toString());
    }
}

5. Fifth we create our archive controller class name ArchivedActivity.java. This activity will help to show our all archive data. Copy and paste the given bellow code into this created ArchivedActivity.java class without changing package name.

package com.andrious.notebook;

import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;

public class ArchivedActivity extends AppCompatActivity {
    DBHelper mydb;
    ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
    ListView simpleList;
    TextView empty_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setTitle("Archive");
        setContentView(R.layout.activity_archived);

        mydb = new DBHelper(this);
        empty_text = (TextView) findViewById(R.id.empty_text);
        simpleList = (ListView) findViewById(R.id.ListView);
        simpleList.setEmptyView(empty_text);
    }

    @Override
    public void onResume() {
        super.onResume();
        populateData();
    }

    public void populateData() {
        mydb = new DBHelper(this);

        runOnUiThread(new Runnable() {
            public void run() {
                fetchDataFromDB();
            }
        });
    }

    public void fetchDataFromDB() {
        dataList.clear();

        Cursor cursor = mydb.getArchivedData();
        loadDataList(cursor, dataList);
    }

    public void loadDataList(Cursor cursor, final ArrayList<HashMap<String, String>> List) {
        if (cursor != null) {
            cursor.moveToFirst();
            while (cursor.isAfterLast() == false) {

                HashMap<String, String> mapData = new HashMap<String, String>();
                mapData.put("id", cursor.getString(0).toString());
                mapData.put("title", cursor.getString(1).toString());
                mapData.put("description", cursor.getString(2).toString());
                mapData.put("date", cursor.getString(3).toString());
                mapData.put("fevourite", cursor.getString(4).toString());
                mapData.put("status", cursor.getString(5).toString());
                List.add(mapData);
                cursor.moveToNext();
            }
            ListNoteBookAdapter adapter = new ListNoteBookAdapter(this, List, mydb);
            simpleList.setAdapter(adapter);
            simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(ArchivedActivity.this);
                    builder.setTitle(List.get(+position).get("title"));
                    //builder.setMessage(List.get(+position).get("description"));
                    builder.setNeutralButton("DELETE", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteNoteBookData(List.get(+position).get("id"));
                            populateData();
                        }
                    });
                    builder.setNegativeButton("MOVE TO LIST", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            mydb.updateNoteBookStatus(List.get(+position).get("id"), 0);
                            populateData();

                        }
                    });
                    builder.setPositiveButton("CANCEL", null);
                    builder.show();
                }
            });
        }
    }
}

Finally add this created class into manifests file. Here is my AndroidManifest.xml file look like

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.andrious.notebook">

    <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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".AddAndModifyNoteBookData"/>
        <activity android:name=".ArchivedActivity"/>
    </application>

</manifest>

Our all task is done. Now run and enjoy the application.

Leave a Comment

(0 Comments)

Your email address will not be published. Required fields are marked *