Membuat Aplikasi CRUD Sederhana dengan database SQLite di Android Studio

Juni 20, 2019 , , , 0 Comments

Halo sobat blogger sudah lama admin tidak membuat postingan artikel dikarenakan sibuk dengan urusan di dunia nyata. pada kesempatan kali ini admin akan memberikan tutorial cara membuat aplikasi CRUD (Create Read Update Delete) di Android dengan Database SQLite. SQLite ini adalah database yang portable karena data-datanya akan tersimpan pada memori handhone kalian masing-masing, tidak disimpan di server. namun jika di perlukan bisa juga database ini disinkronkan ke server kita akan membahasnya pada kesempatan yang lain. Pada kesempatan kali ini kita akan membuat Aplikasi CRUD yang sederhana kedepanya kita akan bahas membuat CRUD dengan Content Provider.



Ok langsung saja untuk membuatnya kita buat desain tampilanya dulu.
<?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:theme="@android:style/Theme.NoTitleBar"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
   
android:background="#ddd"
   
android:padding="10dp"
   
tools:context="giviews.id.splash.MainActivity">

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Name"/>

        <EditText
           
android:id="@+id/editText_name"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Name"
           
android:inputType="textPersonName" />
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
            
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Surname"/>

        <EditText
           
android:id="@+id/editText_surname"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
            
android:hint="Surname"
           
android:inputType="textPersonName" />
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Marks"/>

        <EditText
           
android:id="@+id/editText_marks"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Marks"
           
android:inputType="textPersonName"/>
    </LinearLayout>

    <LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20dp"
       
android:orientation="horizontal">

        <TextView
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="3"
           
android:textColor="#000"
           
android:text="Id"/>

        <EditText
           
android:id="@+id/editTextId"
           
style="@android:style/Widget.Material.Light.EditText"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:ems="10"
           
android:hint="Id"
           
android:inputType="textPersonName" />
    </LinearLayout>

        <LinearLayout
           
android:layout_marginTop="20dp"
            
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:orientation="horizontal">

            <Button
               
android:id="@+id/button_add"
               
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
                
android:text="Add Data"
               
android:textAppearance="@android:style/TextAppearance.Material.Button"
               
android:layout_weight="1" />

            <Button
               
android:id="@+id/button_view"
               
style="@android:style/Widget.Material.Light.Button"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:background="@color/colorAccent"
               
android:layout_weight="1"
                
android:text="view all"
               
android:textAppearance="@android:style/TextAppearance.Material.Button"
               
android:textColor="@android:color/background_light" />
        </LinearLayout>

        <LinearLayout
           
android:layout_marginTop="20dp"
           
android:layout_width="match_parent"
           
android:orientation="horizontal"
           
android:layout_height="wrap_content">

            <Button
               
android:id="@+id/button_update"
               
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:layout_weight="1"
               
android:text="Update"
               
android:textAppearance="@style/TextAppearance.AppCompat.Button" />

            <Button
               
android:id="@+id/button_delete"
                
style="@android:style/Widget.Material.Light.Button"
               
android:background="@color/colorAccent"
               
android:textColor="@android:color/background_light"
               
android:layout_width="match_parent"
               
android:layout_height="wrap_content"
               
android:layout_weight="1"
               
android:text="Delete"
               
android:textAppearance="@style/TextAppearance.AppCompat.Button" />
        </LinearLayout>
    </LinearLayout>

Selanjutnya buat class DatabaseHelper di java, class ini berfungsi untuk membuat database, table, metode untuk menambah, mengupdate, menampilkan dan menghapus data.

package giviews.id.splash;



import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;



/**

 * Created by asus on 02/04/2017.

 */



public class DatabaseHelper extends SQLiteOpenHelper{

    //nama database

    public static final String DATABASE_NAME = "Student.db";

    //nama table

    public static final String TABLE_NAME = "student_table";

    //versi database

    private static final int DATABASE_VERSION = 1;

    //table field

    public static final String COL_1 = "ID";

    public static final String COL_2 = "NAME";

    public static final String COL_3 = "SURNAME";

    public static final String COL_4 = "MARKS";



    public DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        SQLiteDatabase db = this.getWritableDatabase();

    }



    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table student_table(id integer primary key autoincrement," +

                "name text null," +

                "surname text null," +

                "marks integer null);");

    }



    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);

        onCreate(db);

    }



    //metode untuk tambah data

    public boolean insertData(String name, String surname, String marks) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(COL_2,name);

        contentValues.put(COL_3,surname);

        contentValues.put(COL_4,marks);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1)

            return false;

        else

            return true;

    }



    //metode untuk mengambil data

    public Cursor getAllData() {

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor res = db.rawQuery("select * from student_table", null);

        return res;

    }



    //metode untuk merubah data

    public boolean updateData(String id,String name,String surname,String marks) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(COL_1,id);

        contentValues.put(COL_2,name);

        contentValues.put(COL_3,surname);

        contentValues.put(COL_4,marks);

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

        return true;

    }



    //metode untuk menghapus data

    public int deleteData (String id) {

        SQLiteDatabase db = this.getWritableDatabase();

        return db.delete(TABLE_NAME, "ID = ?", new String[] {id});

    }

}
Terakhir kita buat script untuk memfungsikan tombol add, edit, view dan delete yang telah kita desain tadi, kodenya seperti berikut:

package giviews.id.splash;



import android.database.Cursor;

import android.os.Bundle;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

    DatabaseHelper myDb;

    EditText editName,editSurname,editMarks,editTextId;

    Button btnAddData;

    Button btnViewAll;

    Button btnUpdate;

    Button btnDelete;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        myDb = new DatabaseHelper(this);

        editName = (EditText)findViewById(R.id.editText_name);

        editSurname = (EditText)findViewById(R.id.editText_surname);

        editMarks = (EditText)findViewById(R.id.editText_marks);

        editTextId = (EditText)findViewById(R.id.editTextId);

        btnAddData = (Button)findViewById(R.id.button_add);

        btnViewAll = (Button)findViewById(R.id.button_view);

        btnUpdate = (Button)findViewById(R.id.button_update);

        btnDelete = (Button)findViewById(R.id.button_delete);

        AddData();

        viewAll();

        UpdateData();

        deleteData();

    }



    //fungsi hapus

    public void deleteData() {

        btnDelete.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        Integer deletedRows = myDb.deleteData(editTextId.getText().toString());

                        if (deletedRows > 0)

                            Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Failed to Deleted!",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi update

    public void UpdateData() {

        btnUpdate.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        boolean isUpdate = myDb.updateData(editTextId.getText().toString(),

                                editName.getText().toString(),

                                editSurname.getText().toString(),

                                editMarks.getText().toString());

                        if(isUpdate == true)

                            Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Failed to Update",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi tambah

    public void AddData() {

        btnAddData.setOnClickListener(

                new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {

                        boolean isInserted = myDb.insertData(editName.getText().toString(),

                                editSurname.getText().toString(),

                                editMarks.getText().toString() );

                        if(isInserted == true)

                            Toast.makeText(MainActivity.this,"Data Iserted",Toast.LENGTH_LONG).show();

                        else

                            Toast.makeText(MainActivity.this,"Data Not Iserted",Toast.LENGTH_LONG).show();

                    }

                }

        );

    }



    //fungsi menampilkan data

    public void viewAll() {

        btnViewAll.setOnClickListener(

            new View.OnClickListener(){

                 @Override

                     public void onClick(View v) {

                     Cursor res = myDb.getAllData();

                     if(res.getCount() == 0) {

                     // show message

                         showMessage("Error","Noting Found");

                     return;

                 }



                 StringBuffer buffer = new StringBuffer();

                     while (res.moveToNext() ) {

                         buffer.append("Id :"+ res.getString(0)+"\n");

                         buffer.append("Name :"+ res.getString(1)+"\n");

                         buffer.append("Surname :"+ res.getString(2)+"\n");

                         buffer.append("Marks :"+ res.getString(3)+"\n\n");

                     }



                     // show all data

                     showMessage("Data",buffer.toString());

                }

            }

        );

    }



    //membuat alert dialog

    public void showMessage(String title, String Message){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setCancelable(true);

        builder.setTitle(title);

        builder.setMessage(Message);

        builder.show();

    }

}





Sekarang jalankan program crud anda, selamat mencoba semoga berhasil. jika ada yang kurang jelas bisa ditanyakan pada komentar dibawah, jika artikel ini bermanfaat silakan share. pada postingan selanjutnya kita akan membuat Aplikasi CRUD dengan menggunakan Content Provider dan Circular Reveal Animation

Juanas Smith Shared

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 komentar :