Note App



temen2,
pernah mencatat sesuatu di aplikasi note?
gimana rasanya kalo kita buat aplikasi note sendiri...
wih hebat banget kan??

yuk kita buat...

1. langkah pertama kita membuat projek dengan menggunakan basic activity..

2. langkah kedua kita membuat database di app kita, dengan membuat package database..

3. di dalam package database kita membuat 3 class..

kelas pertama adalah DatabaseContract

package com.example.noteapp.database;

import android.provider.BaseColumns;

public class DatabaseContract {
    public static String TABLE_NOTE = "note";

    public static final class NoteColumns implements BaseColumns{
        public static String TITLE = "title";
        public static String DESCRIPTION = "description";
        public static String DATE = "date";

    }
}


kelas kedua kita membuat  DatabaseHelper

package com.example.noteapp.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "dbnote";
    public static int DATABASE_VERSION = 1;

    public static final String SQL_CREATE_TABLE = String.format("CREATE TABLE %s"
                                                                + "(%s INTEGER PRIMARY KEY AUTOINCREMENT,"
                                                                + "%s TEXT NOT NULL,"
                                                                + "%s TEXT NOT NULL,"
                                                                + "%s TEXT NUT NULL)",
                                                                DatabaseContract.TABLE_NOTE,
                                                                DatabaseContract.NoteColumns._ID,
                                                                DatabaseContract.NoteColumns.TITLE,
                                                                DatabaseContract.NoteColumns.DESCRIPTION,
                                                                DatabaseContract.NoteColumns.DATE);

    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DatabaseContract.TABLE_NOTE);
        onCreate(db);
    }
}


kemudian kelas ketiga adalah NoteHelper

package com.example.noteapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.example.noteapp.Note;

import java.util.ArrayList;

import static android.provider.BaseColumns._ID;
import static com.example.noteapp.database.DatabaseContract.NoteColumns.DATE;
import static com.example.noteapp.database.DatabaseContract.NoteColumns.DESCRIPTION;
import static com.example.noteapp.database.DatabaseContract.NoteColumns.TITLE;
import static com.example.noteapp.database.DatabaseContract.TABLE_NOTE;

public class NoteHelper  {
    private static DatabaseHelper databaseHelper;
    private static NoteHelper noteHelper;
    private static SQLiteDatabase sqLiteDatabase;
    private static String DATABASE_TABLE = TABLE_NOTE;


    public NoteHelper(Context context){
        databaseHelper = new DatabaseHelper(context);
    }

    public static NoteHelper getInstance(Context context){
        if (noteHelper == null){
            synchronized (SQLiteDatabase.class){
                if (noteHelper == null){
                    noteHelper = new NoteHelper(context);
                }
            }
        }
        return noteHelper;
    }

    public void open() throws SQLException{
        sqLiteDatabase = databaseHelper.getWritableDatabase();
    }

    public void close(){
        databaseHelper.close();
        if (sqLiteDatabase.isOpen()){
            sqLiteDatabase.close();
        }
    }

    public ArrayList<Note> getAllNote(){
        ArrayList<Note> arrayList = new ArrayList<>();
        Cursor cursor = sqLiteDatabase.query(DATABASE_TABLE,
                                            null, null, null, null, null, _ID + " ASC", null);
        cursor.moveToFirst();

        Note note;
        if (cursor.getCount() > 0){
            do {
                note = new Note();
                note.setId(cursor.getInt(cursor.getColumnIndexOrThrow(_ID)));
                note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(TITLE)));
                note.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(DESCRIPTION)));
                note.setDate(cursor.getString(cursor.getColumnIndexOrThrow(DATE)));

                arrayList.add(note);
                cursor.moveToNext();
            } while (!cursor.isAfterLast());
        }
        cursor.close();
        return arrayList;
    }

    public long insertNote(Note note){
        ContentValues contentValues = new ContentValues();
        contentValues.put(TITLE, note.getTitle());
        contentValues.put(DESCRIPTION, note.getDescription());
        contentValues.put(DATE, note.getDate());
        return sqLiteDatabase.insert(DATABASE_TABLE, null, contentValues);
    }

    public int updateNote(Note note) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(TITLE, note.getTitle());
        contentValues.put(DESCRIPTION, note.getDescription());
        contentValues.put(DATE, note.getDate());
        return sqLiteDatabase.update(DATABASE_TABLE, contentValues, _ID + "= '", null);
    }

    public int deleteNote(int id){
        return sqLiteDatabase.delete(TABLE_NOTE, _ID + " = '" + id + "'", null );
    }
}

4. langkah keempat kita membuat beberapa kelas selain database yaitu Note, NoteAdapter, AddUpdateActivity dan juga MainActivity

kita membuat kelas Note

package com.example.noteapp;

import android.os.Parcel;
import android.os.Parcelable;

public class Note implements Parcelable {
    int id;
    String title;
    String description;

    public Note(Parcel in) {
        id = in.readInt();
        title = in.readString();
        description = in.readString();
        date = in.readString();
    }

    public static final Creator<Note> CREATOR = new Creator<Note>() {
        @Override
        public Note createFromParcel(Parcel in) {
            return new Note(in);
        }

        @Override
        public Note[] newArray(int size) {
            return new Note[size];
        }
    };

    public Note() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    String date;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(id);
        parcel.writeString(title);
        parcel.writeString(description);
        parcel.writeString(date);
    }
}

kemudian kita membuat NoteAdapternya...

package com.example.noteapp;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {

    ArrayList<Note> listNote;
    Activity activity;

    public NoteAdapter(Activity activity){
        this.activity = activity;
    }

    public ArrayList<Note> getListNote(){
        return listNote;
    }

    public void setListNote(ArrayList<Note> listNote){
        this.listNote = listNote;
    }

    @NonNull
    @Override
    public NoteAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(activity).inflate(R.layout.item_note, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull NoteAdapter.ViewHolder holder, final int position) {
        holder.txtJudul.setText(getListNote().get(position).getTitle());
        holder.txtTanggal.setText(getListNote().get(position).getDate());
        holder.txtDeskripsi.setText(getListNote().get(position).getDescription());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(activity, AddUpdateActivity.class);
                intent.putExtra(AddUpdateActivity.EXTRA_POSITION, position);
                intent.putExtra(AddUpdateActivity.EXTRA_NOTE, getListNote().get(position));
                activity.startActivityForResult(intent, AddUpdateActivity.REQUEST_UPDATE);
            }
        });

    }

    @Override
    public int getItemCount() {
        if (listNote.size() > 0){
            return listNote.size();
        }
        return listNote.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView txtJudul, txtTanggal, txtDeskripsi;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txtJudul = itemView.findViewById(R.id.tv_title);
            txtTanggal = itemView.findViewById(R.id.tv_date);
            txtDeskripsi = itemView.findViewById(R.id.tv_description);
        }
    }
}

kemudian membuat kelas AddUpdateActivity

package com.example.noteapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.noteapp.database.NoteHelper;

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

public class AddUpdateActivity extends AppCompatActivity {

    public static int REQUEST_ADD = 100;
    public static int RESULT_ADD = 101;

    public static int REQUEST_UPDATE = 200;
    public static int RESULT_UPDATE = 201;

    public static int RESULT_DELETE = 301;

    public boolean isUpdate = false;

    public static String EXTRA_POSITION = "extra_position";
    public static String EXTRA_NOTE = "extra_note";

    EditText edtTitle, edtDescription;
    Button btnSave;

    Note note;
    NoteHelper noteHelper;
    int position;

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

        edtTitle = findViewById(R.id.edt_title);
        edtDescription = findViewById(R.id.edt_description);
        btnSave = findViewById(R.id.btn_save);

        noteHelper = new NoteHelper(this);
        noteHelper.open();

        note = getIntent().getParcelableExtra(EXTRA_NOTE);
        if (note != null){
            position = getIntent().getIntExtra(EXTRA_POSITION, 0);
            isUpdate = true;
        }

        String actionBarTitle, btnTitle;
        if (isUpdate){
            actionBarTitle = "update data";
            btnTitle = "update";

            edtTitle.setText(note.getTitle());
            edtDescription.setText(note.getDescription());
        }else {
            actionBarTitle = "create data";
            btnTitle = "Create";
        }

        getSupportActionBar().setTitle(actionBarTitle);
        btnSave.setText(btnTitle);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = edtTitle.getText().toString().trim();
                String description = edtDescription.getText().toString().trim();

                if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description)){
                    Toast.makeText(AddUpdateActivity.this, "Fill required!", Toast.LENGTH_SHORT).show();
                }else {
                    Note newNote = new Note();
                    newNote.setTitle(title);
                    newNote.setDescription(description);

                    Intent intent = new Intent();
                    if (isUpdate){
                        newNote.setDate(note.getDate());
                        newNote.setId(note.getId());
                        noteHelper.updateNote(newNote);

                        intent.putExtra(EXTRA_POSITION, position);
                        setResult(RESULT_UPDATE, intent);
                        finish();
                    }else {
                        newNote.setDate(currentDate());
                        noteHelper.insertNote(newNote);
                        setResult(RESULT_ADD);
                        finish();
                    }
                }
            }
        });
    }

    private String currentDate(){
        SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss");
        Date date = new Date();
        return formatter.format(date);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isUpdate){
            getMenuInflater().inflate(R.menu.menu_delete, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_delete){
            noteHelper.deleteNote(note.getId());
            setResult(RESULT_DELETE);
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}


dan pastinya kita membuat main activity...

package com.example.noteapp;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import com.example.noteapp.database.NoteHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView rvNote;
    NoteHelper helper;
    NoteAdapter adapter;
    ArrayList<Note> listNote;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        rvNote = findViewById(R.id.rv_note);
        rvNote.setHasFixedSize(true);
        rvNote.setLayoutManager(new LinearLayoutManager(this));

        helper = new NoteHelper(this);
        helper.open();

        listNote = new ArrayList<>();

        adapter = new NoteAdapter(this);
        rvNote.setAdapter(adapter);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddUpdateActivity.class);
                startActivityForResult(intent, AddUpdateActivity.REQUEST_ADD);
            }
        });
        new LoadNoteAsyncTask().execute();
    }


    private class LoadNoteAsyncTask extends AsyncTask<Void, Void, ArrayList<Note>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (listNote.size() > 0){
                listNote.clear();
            }
        }

        @Override
        protected void onPostExecute(ArrayList<Note> notes) {
            super.onPostExecute(notes);
            listNote.addAll(notes);
            adapter.setListNote(listNote);
            adapter.notifyDataSetChanged();
            if (listNote.size() == 0){
                Toast.makeText(MainActivity.this, "Empty Data", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected ArrayList<Note> doInBackground(Void... voids) {
            return helper.getAllNote();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddUpdateActivity.REQUEST_ADD){
            if (resultCode == AddUpdateActivity.RESULT_ADD){
                Toast.makeText(this, "Success create data", Toast.LENGTH_SHORT).show();
                new LoadNoteAsyncTask().execute();
            }
            if (resultCode == AddUpdateActivity.RESULT_DELETE){
                Toast.makeText(this, "Success delete data", Toast.LENGTH_SHORT).show();
                new LoadNoteAsyncTask().execute();
            }
        }
    }
}


nah, sekarang saatnya membuat di dalam res, ada layout, menu dan di drawble...

di layout kita akan membuat activity_main, content_main, activity_add_update, item_note

pertama kita membuat, item note

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp"
    app:cardElevation="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="15dp">

        <TextView
            android:id="@+id/tv_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Date"/>

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Title"
            android:textStyle="bold"/>

        <TextView
            android:id="@+id/tv_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Description"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>

kemudian kita membuat , acivity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

lalu membuat content_main

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:listitem="@layout/item_note"/>

</LinearLayout>

dan terakhir kita buat, activity_add_update

<?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"
    android:padding="20dp"
    tools:context=".AddUpdateActivity">

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

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

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Save"/>



</LinearLayout>


lalu kita membuat di package menu ada, menu_main dan menu_delete

di menu_mian kita masukan kode ini

<menu 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"
    tools:context="com.example.noteapp.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>


dan kita masukan kode ini di menu_delete

<?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/action_delete"
        android:orderInCategory="100"
        android:icon="@drawable/ic_delete_black_24dp"
        android:title="Delete"
        app:showAsAction="always"/>

</menu>

dan terakhir kita pasang icon di drawable untuk menu delete,

<vector android:height="48dp" android:tint="#FFFFFF"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FF000000" android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"/>
</vector>

dan silahkan di run...



















Komentar

Postingan populer dari blog ini

Relay lampu menggunakan NodeMCU

Kode program (sketch) DHT11 di Arduino Uno

Kode program ( sketch ) sensor infrared di Arduino Uno with buzzer