Belajar Android Studio - Cara Membuat Aplikasi Catatan Harian
Android studio adalah salah satu software guna merancang aplikasi android. Berikut cara membuat aplikasi catatan harian dengan android studio menggunakan kotlin dan SQLite.

Dalam pembuatan aplikasi noted atau catatan harian ini, saya simpulkan anda sudah dapat membuat activity baru pada android studio.
Dengan ini berikut saya akan lampirkan cara untuk membuat aplikasi catatan harian pada android studio dengan bahasa kotlin dan didukung oleh database SQLite.
1. Silahkan buka android studio, dan pilih Empty Activity.
2. Berikan nama aplikasi sesuai keinginan anda.
3. Masukkan Gradle yang akan digunakan.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:30.0.0'
implementation 'com.android.support:cardview-v7:30.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
4. Berikutnya silahkan klik kanan pada bagian folder RES > New > Pilih Android Recource Directory > pada bagian value pilih menu.
5. Setelah folder menu terbuat, silahkan klik kanan > New > value recourse file > beri nama main_menu.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_bright"
android:gravity="end"
android:padding="2dp">
<item
android:id="@+id/action_settings"
android:title="@string/settings"
android:layout_width="wrap_content" />
<item
android:id="@+id/app_bar_search"
android:icon="@drawable/ic_action_search"
android:title="@string/search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="ifRoom"
android:layout_width="match_parent" />
<item
android:id="@+id/addNote"
android:icon="@drawable/ic_action_add"
android:title="@string/add_nore"
app:showAsAction="always" />
</menu>
6. Kemudian masuk ke bagian folder values > pilih color.xml, silahkan buat warna sesuka selera.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#0488d1</color>
<color name="colorPrimaryDark">#0477bd</color>
<color name="colorAccent">#0488d1</color>
<color name="gray">#e8e8e8</color>
<color name="white">#fff</color>
<color name="black">#000</color>
</resources>
7. Pada bagian layout, silahkan tambahkan row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="3dp"
app:cardElevation="3dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="103dp"
android:layout_margin="5dp"
android:gravity="end|bottom"
android:orientation="vertical">
<TextView
android:id="@+id/titleTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title"
android:textColor="@color/colorPrimary"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/descTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/Description"
android:textSize="19sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="3dp"
android:background="@color/colorPrimaryDark" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<ImageButton
android:id="@+id/deleteBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:background="@null"
android:contentDescription="@string/Pict4"
android:src="@drawable/ic_action_delete"
android:layout_marginRight="5dp" />
<ImageButton
android:id="@+id/editBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:background="@null"
android:contentDescription="@string/Pict1"
android:src="@drawable/ic_action_edit"
android:layout_marginRight="5dp" />
<ImageButton
android:id="@+id/copyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:background="@null"
android:contentDescription="@string/Pict2"
android:src="@drawable/ic_action_copy"
android:layout_marginRight="5dp" />
<ImageButton
android:id="@+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:background="@null"
android:contentDescription="@string/Pict3"
android:src="@drawable/ic_action_share"
android:layout_marginRight="5dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
8. Berikutnya pada folder layout, tambahkan file xml baru dengan nama activity_add_note.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".AddNoteActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="3dp"
app:cardElevation="3dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/titleEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:background="@null"
android:hint="@string/title"
android:inputType="textShortMessage"
android:padding="10dp"
android:singleLine="true"
android:textStyle="bold" />
<EditText
android:id="@+id/descEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:background="@null"
android:gravity="top"
android:hint="@string/enter_description"
android:inputType="textLongMessage"
android:minHeight="100dp"
android:padding="10dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<Button
android:id="@+id/addBtn"
style="@style/Base.Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:onClick="addFunc"
android:text="@string/add"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp" />
</LinearLayout>
</ScrollView>
9. Berikut nya jangan lupa pula untuk menambahkan file activity_profile_me.xml
<?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="10dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/nameEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="textPersonName|textCapWords" />
<EditText
android:id="@+id/emailEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/passwordEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<CheckBox
android:id="@+id/rememberCb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Remember" />
<Button
android:id="@+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Save" />
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etEmail"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/btnSave"
android:text="Show Account" />
</LinearLayout>
10. Setelah semua design terbentuk, silahkan isi Drawable sesuai dengan kebutuhan, ikuti nama drawable sesuai dengan file layoutnya.
11. Berikut nya adalah pembuatan function, silahkan buat 5 file berikut untuk pembuatan function agar program aplikasi berjalan fungsinya.
MainActivity.kt
import android.app.SearchManager
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.row.view.*
class MainActivity : AppCompatActivity() {
var listNotes = ArrayList<Note>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Load from DB
LoadQuery("%")
}
override fun onResume() {
super.onResume()
LoadQuery("%")
}
private fun LoadQuery(title: String) {
var dbManager = DbManager(this)
val projections = arrayOf("ID", "Title", "Description")
val selectionArgs = arrayOf(title)
val cursor = dbManager.Query(projections, "Title like ?", selectionArgs, "Title")
listNotes.clear()
if (cursor.moveToFirst()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("ID"))
val Title = cursor.getString(cursor.getColumnIndex("Title"))
val Description = cursor.getString(cursor.getColumnIndex("Description"))
listNotes.add(Note(ID, Title, Description))
} while (cursor.moveToNext())
}
//adapter
var myNotesAdapter = MyNotesAdapter(this, listNotes)
//set adapter
notesLv.adapter = myNotesAdapter
//get total number of tasks from ListView
val total = notesLv.count
//actionbar
val mActionBar = supportActionBar
if (mActionBar != null) {
//set to actionbar as subtitle of actionbar
mActionBar.subtitle = "You have $total note(s) in list..."
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
//searchView
val sv: SearchView = menu!!.findItem(R.id.app_bar_search).actionView as SearchView
val sm = getSystemService(Context.SEARCH_SERVICE) as SearchManager
sv.setSearchableInfo(sm.getSearchableInfo(componentName))
sv.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
LoadQuery("%" + query + "%")
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
LoadQuery("%" + newText + "%")
return false
}
});
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.addNote -> {
startActivity(Intent(this, AddNoteActivity::class.java))
}
R.id.action_settings -> {
startActivity(Intent(this, ProfileMe::class.java))
}
}
return super.onOptionsItemSelected(item)
}
inner class MyNotesAdapter : BaseAdapter {
var listNotesAdapter = ArrayList<Note>()
var context: Context? = null
constructor(context: Context, listNotesAdapter: ArrayList<Note>) : super() {
this.listNotesAdapter = listNotesAdapter
this.context = context
}
@Suppress("DEPRECATION")
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
//inflate layout row.xml
var myView = layoutInflater.inflate(R.layout.row, null)
val myNote = listNotesAdapter[position]
myView.titleTv.text = myNote.nodeName
myView.descTv.text = myNote.nodeDes
//delete button click
myView.deleteBtn.setOnClickListener {
var dbManager = DbManager(this.context!!)
val selectionArgs = arrayOf(myNote.nodeID.toString())
dbManager.delete("ID=?", selectionArgs)
LoadQuery("%")
}
//edit//update button click
myView.editBtn.setOnClickListener {
GoToUpdateFun(myNote)
}
//copy btn click
myView.copyBtn.setOnClickListener {
//get title
val title = myView.titleTv.text.toString()
//get description
val desc = myView.descTv.text.toString()
//concatinate
val s = title + "n" + desc
val cb = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cb.text = s // add to clipboard
Toast.makeText(this@MainActivity, "Copied...", Toast.LENGTH_SHORT).show()
}
//share btn click
myView.shareBtn.setOnClickListener {
//get title
val title = myView.titleTv.text.toString()
//get description
val desc = myView.descTv.text.toString()
//concatenate
val s = title + "n" + desc
//share intent
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TEXT, s)
startActivity(Intent.createChooser(shareIntent, s))
}
return myView
}
override fun getItem(position: Int): Any {
return listNotesAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listNotesAdapter.size
}
}
private fun GoToUpdateFun(myNote: Note) {
var intent = Intent(this, AddNoteActivity::class.java)
intent.putExtra("ID", myNote.nodeID) //put id
intent.putExtra("name", myNote.nodeName) //ut name
intent.putExtra("des", myNote.nodeDes) //put description
startActivity(intent) //start activity
}
}
Note.kt
class Note(nodeID: Int, nodeName: String, nodeDes: String) {
var nodeID: Int? = nodeID
var nodeName: String? = nodeName
var nodeDes: String? = nodeDes
}
AddNoteActivity.kt
import android.content.ContentValues
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_add_note.*
class AddNoteActivity : AppCompatActivity() {
val dbTable = "Notes"
var id = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_note)
try {
val bundle: Bundle? = intent.extras
id = bundle!!.getInt("ID", 0)
if (id!=0){
titleEt.setText(bundle!!.getString("name"))
descEt.setText(bundle!!.getString("des"))
}
}catch (ex:Exception){}
}
fun addFunc(view:View) {
var dbManager = DbManager(this)
var values = ContentValues()
values.put("Title", titleEt.text.toString())
values.put("Description", descEt.text.toString())
if (id ==0){
val ID = dbManager.insert(values)
if (ID>0){
Toast.makeText(this, "Note is added", Toast.LENGTH_SHORT).show()
finish()
}
else{
Toast.makeText(this, "Error adding note...", Toast.LENGTH_SHORT).show()
}
}
else{
var selectionArgs = arrayOf(id.toString())
val ID = dbManager.update(values, "ID=?", selectionArgs)
if (ID>0){
Toast.makeText(this, "Note is added", Toast.LENGTH_SHORT).show()
finish()
}
else{
Toast.makeText(this, "Error adding note...", Toast.LENGTH_SHORT).show()
}
}
}
}
DbManager.kt
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.widget.Toast
class DbManager {
//database name
var dbName = "MyNotes"
//table name
var dbTable = "Notes"
//columns
var colID = "ID"
var colTitle = "Title"
var colDes = "Description"
//database version
var dbVersion = 1
//CREATE TABLE IF NOT EXISTS MyNotes (ID INTEGER PRIMARY KEY,title TEXT, Description TEXT);"
val sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + dbTable + " (" + colID + " INTEGER PRIMARY KEY," + colTitle + " TEXT, " + colDes + " TEXT);"
var sqlDB: SQLiteDatabase? = null
constructor(context: Context) {
var db = DatabaseHelperNotes(context)
sqlDB = db.writableDatabase
}
inner class DatabaseHelperNotes : SQLiteOpenHelper {
var context: Context? = null
constructor(context: Context) : super(context, dbName, null, dbVersion) {
this.context = context
}
override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL(sqlCreateTable)
Toast.makeText(this.context, "database created...", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("Drop table if Exists" + dbTable)
}
}
fun insert(values: ContentValues): Long {
val ID = sqlDB!!.insert(dbTable, "", values)
return ID
}
fun Query(projection: Array<String>, selection: String, selectionArgs: Array<String>, sorOrder: String): Cursor {
val qb = SQLiteQueryBuilder();
qb.tables = dbTable
val cursor = qb.query(sqlDB, projection, selection, selectionArgs, null, null, sorOrder)
return cursor
}
fun delete(selection: String, selectionArgs: Array<String>): Int {
val count = sqlDB!!.delete(dbTable, selection, selectionArgs)
return count
}
fun update(values: ContentValues, selection: String, selectionArgs: Array<String>): Int {
val count = sqlDB!!.update(dbTable, values, selection, selectionArgs)
return count
}
}
ProfileMe.kt
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_profile_me.*
class ProfileMe : AppCompatActivity() {
//variables
var name: String? = null
var email: String? = null
var password: String? = null
var age = 0
var isRemembered = false
//shared pref
lateinit var sharedPreferences: SharedPreferences
lateinit var spEditor: SharedPreferences.Editor
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile_me)
//init share pref
sharedPreferences = getSharedPreferences("USER_INFO_SP", Context.MODE_PRIVATE)
//get data from shared preferences
name = sharedPreferences.getString("NAME", "")
age = sharedPreferences.getInt("AGE", 0)
email = sharedPreferences.getString("EMAIL", "")
password = sharedPreferences.getString("PASSWORD", "")
isRemembered = sharedPreferences.getBoolean("REMEMBER", false)
//set data to views
nameEt.setText(name)
emailEt.setText(email)
passwordEt.setText(password)
rememberCb.setChecked(isRemembered)
//click to input data from views
saveBtn.setOnClickListener(View.OnClickListener {
//get data from views
name = "" + nameEt.getText().toString().trim()
email = "" + emailEt.getText().toString().trim()
password = "" + passwordEt.getText().toString().trim()
if (rememberCb.isChecked()) {
isRemembered = true
//save data to shared preferences
spEditor = sharedPreferences.edit()
spEditor.putString("NAME", name)
spEditor.putString("EMAIL", email)
spEditor.putString("PASSWORD", password)
spEditor.putBoolean("REMEMBER", true)
spEditor.apply()
Toast.makeText(this@ProfileMe, "Info is remembered...", Toast.LENGTH_SHORT).show()
} else {
isRemembered = false
//don't save | remove data from shared preferences
spEditor = sharedPreferences.edit()
spEditor.clear()
spEditor.apply()
Toast.makeText(this@ProfileMe, "Info is not remembered...", Toast.LENGTH_SHORT).show()
}
fun getName(): String? {
return sharedPreferences!!.getString("NAME", name)
}
fun getEmail(): String? {
return sharedPreferences!!.getString("EMAIL", email)
}
btnShow.setOnClickListener {
Toast.makeText(this, "Name : ${getName()}nEmail : ${getEmail()}",
Toast.LENGTH_LONG).show()
}
})
}
}
12. Setelah semua terselesaikan, silahkan running program, maka program akan berjalan sebagai berikut.
Itulah cara membuat aplikasi catatan kegiatan harian dengan android studio.
0 Comments
Posting Komentar
Comment Policy: Silahkan tuliskan komentar Anda yang sesuai dengan topik postingan halaman ini. Komentar yang berisi tautan tidak akan ditampilkan sebelum disetujui.