Indoensia Tanah Airku

Monday 1 June 2015

Android Dasar SQLlite CRUD,Membuat button save,cari,edit dan delet

Dasar SQLlite,Membuat button save,cari,edit,dan delet

Pertama buatlah project baru
Nama Aplikasi : Note PIN
Project Name :scrool
Package Name : com.taufik
Activity name :  MainActivity
Layout Name : activity_main

1).Isikan code di pawah ini pada string.xml yang berada pada Folder “res>menu”.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Masukkan Nama dan PIN</string>
    <string name="app_name">NotePIN</string>
    <string name="btnAddtxt">Save</string>
    <string name="namaLabel">Nama</string>
    <string name="hobiLabel">PIN BB</string>
    <string name="nomorLabel">No.</string>
    <string name="btnGetRow">Cari</string>
    <string name="btnUpdateRow">Update</string>
    <string name="ketUpdate">Sebelum mengubah data,pilih dulu baris ke berapa data yang akan diubah</string>
    <string name="ketAmbilBaris">Tulis No Urut</string>
    <string name="ketDelete">Tulis No Urut</string>
    <string name="btnDel">Delete</string>

</resources>
2.Isikan code dibawah ini pada activiry_maim.xml yang berada di folder “res>layout”
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/hello" />

            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <EditText
                    android:id="@+id/inNama"
                    android:layout_width="118dp"
                    android:layout_height="wrap_content"
                    android:ems="10" />

                <requestFocus />

                <EditText
                    android:id="@+id/inHobi"
                    android:layout_width="91dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.47"
                    android:ems="10" >
                </EditText>

                <Button
                    android:id="@+id/btnAdd"
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.33"
                    android:text="Save" />
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/ketUpdate" >
            </TextView>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <LinearLayout
                android:id="@+id/linearLayout2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/ketAmbilBaris" >
                </TextView>

                <EditText
                    android:id="@+id/inGetId"
                    android:layout_width="48dp"
                    android:layout_height="wrap_content" >
                </EditText>

                <Button
                    android:id="@+id/btnGetId"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Cari" >
                </Button>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/linearLayout3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <EditText
                    android:id="@+id/inUpdateNama"
                    android:layout_width="100dip"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.16" >
                </EditText>

                <EditText
                    android:id="@+id/inUpdateHobi"
                    android:layout_width="100dip"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.65" >
                </EditText>

                <Button
                    android:id="@+id/btnUpdate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.23"
                    android:text="Update" >
                </Button>
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <LinearLayout
                android:id="@+id/linearLayout4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Delete" />

                <EditText
                    android:id="@+id/idDelete"
                    android:layout_width="47dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Delete" />
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <TableLayout
                android:id="@+id/tabel_data"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >

                    <TextView
                        android:id="@+id/no_id"
                        android:layout_width="50dip"
                        android:layout_height="wrap_content"
                        android:text="@string/nomorLabel" >
                    </TextView>

                    <TextView
                        android:id="@+id/nama_id"
                        android:layout_width="100dip"
                        android:layout_height="wrap_content"
                        android:text="@string/namaLabel" >
                    </TextView>

                    <TextView
                        android:id="@+id/hobi_id"
                        android:layout_width="100dip"
                        android:layout_height="wrap_content"
                        android:text="@string/hobiLabel" >
                    </TextView>
                </TableRow>
            </TableLayout>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

3).Isikan code dibawah ini pada MainActivity.java yang berada di folder “src”

package com.taufik;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
                DatabaseManager dm;
                EditText nama, hobi, GetId, updateNama, updateHobi, idDel;
                Button addBtn, getIdBtn, updateBtn, delBtn;
                TableLayout tabel4data;

                // tabel for data
                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.activity_main);
                                dm = new DatabaseManager(this);
                                setupView();
                                fungsiBtn();
                                updateTable();
                }

                public void setupView() {
                                 tabel4data = (TableLayout) findViewById(R.id.tabel_data);
                                  nama = (EditText) findViewById(R.id.inNama);
                                  hobi = (EditText) findViewById(R.id.inHobi);
                                 updateNama = (EditText) findViewById(R.id.inUpdateNama);
                                  updateHobi = (EditText) findViewById(R.id.inUpdateHobi);
                                  GetId = (EditText) findViewById(R.id.inGetId);
                                  idDel=(EditText)findViewById(R.id.idDelete);
                                  addBtn = (Button) findViewById(R.id.btnAdd);
                                  getIdBtn = (Button) findViewById(R.id.btnGetId);
                                  updateBtn = (Button) findViewById(R.id.btnUpdate);
                                  delBtn = (Button) findViewById(R.id.button1);
                }

                public void fungsiBtn() {
                                addBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                                simpKamuta();
                                                                kosongkanField();
                                                }
                                });
                                getIdBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View b) {
                                                                ambilBaris();
                                                }
                                });

                                updateBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View c) {
                                                                updateBaris();
                                                                kosongkanField();
                                                }
                                });
                                delBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View d) {

                                                                // TODO Auto-generated method stub
                                                                deleteData();
                                                                kosongkanField();
                                                }
                                });
                }

                protected void kosongkanField() {
                                nama.setText("");
                                hobi.setText("");
                                updateNama.setText("");
                                updateHobi.setText("");
                                GetId.setText("");
                                idDel.setText("");
                }

                private void deleteData() {
                                dm.deleteBaris(Long.parseLong(idDel.getText().toString()));
                                updateTable();
                }

                protected void updateBaris() {
                                dm.updateBaris(Long.parseLong(GetId.getText().toString()), updateNama
                                                                .getText().toString(), updateHobi.getText().toString());
                                updateTable();
                }

                private void ambilBaris() {
                                try {
                                                ArrayList<Object> baris;
                                                baris = dm.ambilBaris(Long.parseLong(GetId.getText().toString()));
                                                updateNama.setText((String) baris.get(1));
                                                updateHobi.setText((String) baris.get(2));
                                } catch (NumberFormatException e) {
                                                e.printStackTrace();
                                                Log.e("eror db", e.toString());
                                                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                                                                                .show();
                                }
                }

                protected void simpKamuta() {
                                try {
                                                dm.addRow(nama.getText().toString(), hobi.getText().toString());
                                                updateTable();
                                } catch (Exception e) {

                                                e.printStackTrace();
                                                Toast.makeText(getBaseContext(), "gagal simpan," + e.toString(),
                                                                                Toast.LENGTH_LONG).show();
                                }
                }

                protected void updateTable() {
                                while (tabel4data.getChildCount() > 1) {
                                                tabel4data.removeViewAt(1);
                                }
                                ArrayList<ArrayList<Object>> data = dm.ambilSemuaBaris();
                                //
                                for (int posisi = 0; posisi < data.size();

                                posisi++) {
                                                TableRow tabelBaris = new TableRow(this);
                                                ArrayList<Object> baris = data.get(posisi);
                                                TextView idTxt = new TextView(this);
                                                idTxt.setText(baris.get(0).toString());
                                                tabelBaris.addView(idTxt);
                                                TextView namaTxt = new TextView(this);
                                                namaTxt.setText(baris.get(1).toString());
                                                tabelBaris.addView(namaTxt);
                                                TextView hobiTxt = new TextView(this);
                                                hobiTxt.setText(baris.get(2).toString());
                                                tabelBaris.addView(hobiTxt);
                                                tabel4data.addView(tabelBaris);
                                }
                }
}

4.Kemudin buat class baru dengan nama DatabaseManager.java,dan isiskan code di bawah ini

package com.taufik;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DatabaseManager {
                private static final String ROW_ID = "_id";
                private static final String ROW_NAMA = "nama";
                private static final String ROW_HOBI = "hobi";
                private static final String NAMA_DB = "DatabaseAndroidDua";
                private static final String NAMA_TABEL = "hobiku ";
                private static final int DB_VERSION = 1;
                private static final String CREATE_TABLE = "create table " + NAMA_TABEL
                                                + " (" + ROW_ID + " integer PRIMARY KEY autoincrement," + ROW_NAMA
                                                + " text," + ROW_HOBI + " text)";
                private final Context context;
                private DatabaseOpenHelper dbHelper;
                private SQLiteDatabase db;

                public DatabaseManager(Context ctx) {
                                this.context = ctx;
                                dbHelper = new DatabaseOpenHelper(ctx);
                                db = dbHelper.getWritableDatabase();
                }

                private static class DatabaseOpenHelper extends SQLiteOpenHelper {
                                public DatabaseOpenHelper(Context context) {
                                                super(context, NAMA_DB, null, DB_VERSION);
                                }

                                @Override
                                public void onCreate(SQLiteDatabase db) {

                                                db.execSQL(CREATE_TABLE);
                                }

                                @Override
                                public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
                                                db.execSQL("DROP TABLE IF EXISTS " + NAMA_DB);
                                                onCreate(db);
                                }
                }

                public void close() {
                                dbHelper.close();
                }

                public void addRow(String nama, String hobi) {
                                ContentValues values = new ContentValues();
                                values.put(ROW_NAMA, nama);
                                values.put(ROW_HOBI, hobi);
                                try {
                                                db.insert(NAMA_TABEL, null, values);
                                } catch (Exception e) {
                                                Log.e("DB ERROR", e.toString());
                                                e.printStackTrace();
                                }
                }

                public ArrayList<ArrayList<Object>> ambilSemuaBaris() {
                                ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
                                Cursor cur;
                                try {
                                                cur = db.query(NAMA_TABEL, new String[] { ROW_ID, ROW_NAMA,
                                                                                ROW_HOBI }, null, null, null, null, null);
                                                cur.moveToFirst();
                                                if (!cur.isAfterLast()) {
                                                                do {
                                                                                ArrayList<Object> dataList = new ArrayList<Object>();
                                                                                dataList.add(cur.getLong(0));
                                                                                dataList.add(cur.getString(1));
                                                                                dataList.add(cur.getString(2));
                                                                                dataArray.add(dataList);
                                                                } while (cur.moveToNext());
                                                }
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("DEBE ERROR", e.toString());
                                                Toast.makeText(context, "gagal ambil semua baris:" + e.toString(),
                                                                                Toast.LENGTH_SHORT).show();
                                }
                                return dataArray;
                }

                public ArrayList<Object> ambilBaris(long rowId) {
                                ArrayList<Object> arrbaris = new ArrayList<Object>();
                                Cursor cursor;
                                try {
                                                cursor = db.query(NAMA_TABEL, new String[] { ROW_ID, ROW_NAMA,
                                                                                ROW_HOBI }, ROW_ID + "=" + rowId, null, null, null, null,
                                                                                null);
                                                cursor.moveToFirst();
                                                if (!cursor.isAfterLast()) {
                                                                do {
                                                                                arrbaris.add(cursor.getLong(0));
                                                                                arrbaris.add(cursor.getString(1));
                                                                                arrbaris.add(cursor.getString(2));
                                                                } while (cursor.moveToNext());
                                                                String r = String.valueOf(arrbaris);
                                                                Toast.makeText(context, "haha" + r, Toast.LENGTH_SHORT).show();
                                                }
                                                cursor.close();
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("error", e.toString());
                                                Toast.makeText(context, "hhii" + e.toString(), Toast.LENGTH_SHORT)
                                                                                .show();
                                }
                                return arrbaris;
                }

                public void updateBaris(long rowId, String nama, String hobi) {
                                ContentValues cv = new ContentValues();
                                cv.put(ROW_NAMA, nama);
                                cv.put(ROW_HOBI, hobi);
                                try {
                                                db.update(NAMA_TABEL, cv, ROW_ID + "=" + rowId, null);
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("Db Error", e.toString());
                                }
                }

                public void deleteBaris(long idBaris) {
                                try {
                                                db.delete(NAMA_TABEL, ROW_ID + "=" + idBaris, null);
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("Error", e.toString());
                                }
                }
}




5). Dan Run lah ,,taraaa lihat hasilnya akan seperti ini




0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best WordPress Themes