Membuat SQLite Android Studio

1
621

Example SQLite: Cara membuat SQLite android pada applikasi android studio.
Pada dasarnya SQLite itu untuk menyimpan data,dan kali ini saya akan membuat Applikasi CRUD ( Create Read Update Delete).
Pada tutorial ini saya membuat dasarnya saja,untuk tampilannya memang basic saja dan kalian harus mengembangkannya sendiri.

'Contoh tampilan home applikasi'
Sqlite Android Studio

Ok langsung saja buat sebuah project pada android studio dan pilih empty,lalu pastekan kode berikut pada activity_main.xml atau main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	android:background="#0561F8">

	<Button
		android:layout_margin="30dp"
		android:id="@+id/mainButton"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:text="Add"/>

	<ListView
		android:layout_margin="10dp"
		android:id="@+id/listView1"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignParentTop="true"
		android:layout_alignParentRight="true"
		android:layout_alignParentEnd="true">

	</ListView>

</LinearLayout>

Setelah itu buat file xml dengan nama activity_buat_data.xml dan pastekan kode berikut

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:id="@+id/activity_buat_biodata"
	android:layout_width="match_parent"
	android:background="#FFFFFF"
	android:layout_height="match_parent"
	android:paddingBottom="16dp"
	android:paddingLeft="16dp"
	android:paddingRight="16dp"
	android:paddingTop="16dp">
	

	<TextView
		android:id="@+id/textView2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText1"
		android:layout_below="@+id/editText1"
		android:layout_marginTop="10dp"
		android:text="Nama"/>

	<EditText
		android:textColorHint="#eb1507"
		android:id="@+id/editText2"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView2"
		android:layout_below="@+id/textView2"
		android:inputType="textCapWords"
		android:maxLength="20"
		android:minEms="1"/>

	<TextView
		android:id="@+id/textView3"
		android:textColorHint="#eb1507"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText2"
		android:layout_below="@+id/editText2"
		android:layout_marginTop="10dp"
		android:text="Tanggal Lahir"/>

	<EditText
		android:id="@+id/editText3"
		android:textColorHint="#eb1507"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView3"
		android:layout_below="@+id/textView3"
		android:inputType="date"
		android:minEms="1"/>

	<TextView
		android:id="@+id/textView4"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText3"
		android:layout_below="@+id/editText3"
		android:layout_marginTop="10dp"
		android:text="Jenis Kelamin"/>

	<EditText
		android:id="@+id/editText4"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView4"
		android:layout_below="@+id/textView4"
		android:maxLength="1"
		android:hint="L atau P"
		android:inputType="textCapWords"
		android:minEms="1"
		android:maxEms="1"/>

	<TextView
		android:id="@+id/textView5"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText4"
		android:layout_below="@+id/editText4"
		android:layout_marginTop="10dp"
		android:text="Alamat"/>

	<EditText
		android:id="@+id/editText5"
		android:textColorHint="#eb1507"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView5"
		android:inputType="textCapWords"
		android:layout_below="@+id/textView5"
		android:maxLength="100"/>


	<Button
		android:id="@+id/button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/biodataImageView"
		android:layout_alignParentBottom="true"
		style="?android:attr/borderlessButtonStyle"
		android:text="Simpan"/>

	<Button
		android:id="@+id/button2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Kembali"
		style="?android:attr/borderlessButtonStyle"
		android:layout_alignParentBottom="true"
		android:layout_alignRight="@+id/editText5"
		android:layout_alignEnd="@+id/editText5"/>

</RelativeLayout>

Buat xml lagi dengan nama activity_lihat_data.xml pastekan kode berikut

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:id="@+id/activity_lihat_biodata"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:paddingBottom="16dp"
	android:paddingLeft="16dp"
	android:paddingRight="16dp"
	android:paddingTop="16dp">

	<RelativeLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent">

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

			

			<TextView
				android:id="@+id/TextView02"
				android:textColor="#E81407"
				android:layout_marginBottom="5dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="Nama"/>

			<TextView
				android:id="@+id/textView2"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:textColor="#070CE8"
				android:layout_marginBottom="10dp"
				android:text="TextView"
				android:textAppearance="?android:attr/textAppearanceLarge"
				android:layout_marginLeft="15dp"/>

			<TextView
				android:id="@+id/TextView03"
				android:textColor="#E81407"
				android:layout_marginBottom="5dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="Jenis Kelamin"/>
				

			<TextView
				android:id="@+id/textView4"
				android:textColor="#070CE8"
				android:layout_marginBottom="10dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="TextView"
				android:textAppearance="?android:attr/textAppearanceLarge"
				android:layout_marginLeft="15dp"/>

			<TextView
				android:id="@+id/TextView04"
				android:textColor="#E81407"
				android:layout_marginBottom="5dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="Tanggal Lahir"/>
				

			<TextView
				android:id="@+id/textView3"
				android:layout_marginBottom="10dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:textColor="#070CE8"
				android:text="TextView"
				android:textAppearance="?android:attr/textAppearanceLarge"
				android:layout_marginLeft="15dp"/>

			<TextView
				android:id="@+id/TextView05"
				android:textColor="#E81407"
				android:layout_marginBottom="5dp"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="Alamat"/>

			<TextView
				android:id="@+id/textView5"
				android:textColor="#070CE8"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:layout_marginBottom="50dp"
				android:text="TextView"
				android:textAppearance="?android:attr/textAppearanceLarge"
				android:layout_marginLeft="15dp"/>

		</LinearLayout>

	</RelativeLayout>

	

</RelativeLayout>

Buat xml dengan nama activity_update_data.xml pastekan kode berikut

<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:id="@+id/activity_update_biodata"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="#FFFFFF"
	android:paddingBottom="16dp"
	android:paddingLeft="16dp"
	android:paddingRight="16dp"
	android:paddingTop="16dp">

	<TextView
		android:id="@+id/textView2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText1"
		android:layout_below="@+id/editText1"
		android:layout_marginTop="10dp"
		android:text="Nama"/>

	<EditText
		android:id="@+id/editText2"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView2"
		android:layout_below="@+id/textView2"
		android:inputType="textCapWords"
		android:maxLength="20"/>

	<TextView
		android:id="@+id/textView3"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText2"
		android:layout_below="@+id/editText2"
		android:layout_marginTop="10dp"
		android:text="Tanggal Lahir"/>

	<EditText
		android:id="@+id/editText3"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView3"
		android:layout_below="@+id/textView3"
		android:inputType="date"/>

	<TextView
		android:id="@+id/textView4"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText3"
		android:layout_below="@+id/editText3"
		android:layout_marginTop="10dp"
		android:text="Jenis Kelamin"/>

	<EditText
		android:id="@+id/editText4"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView4"
		android:layout_below="@+id/textView4"
		android:inputType="textCapWords"
		android:maxLength="1"
		android:hint="L atau P"/>

	<TextView
		android:id="@+id/textView5"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText4"
		android:layout_below="@+id/editText4"
		android:layout_marginTop="10dp"
		android:text="Alamat"
		android:inputType="text"
		android:maxLength="100"/>

	<EditText
		android:id="@+id/editText5"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/textView5"
		android:inputType="textCapWords"
		android:layout_below="@+id/textView5"/>

	<Button
		android:id="@+id/button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignLeft="@+id/editText5"
		android:layout_alignParentBottom="true"
		style="?android:attr/borderlessButtonStyle"
		android:text="Update"/>

	<Button
		android:id="@+id/button2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Kembali"
		style="?android:attr/borderlessButtonStyle"
		android:layout_alignParentBottom="true"
		android:layout_alignRight="@+id/editText5"
		android:layout_alignEnd="@+id/editText5"/>

</RelativeLayout>

Nah sekarang beralih ke file java,pada MainActivity.java pastekan kode berikut

import android.app.*;
import android.os.*;
import android.database.sqlite.*;
import android.widget.*;
import android.view.*;
import android.database.*;
import android.view.View.*;
import android.content.DialogInterface;
import android.content.*;

import java.util.*;

public class MainActivity extends Activity
{
	String[] daftar;
	ListView ListView01;
	Menu menu;
	protected Cursor cursor;
	DataHelper dbcenter;
	public static MainActivity ma;

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

		Button add = (Button) findViewById(R.id.mainButton);
		add.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(MainActivity.this, BuatDataActivity.class);
					startActivity(intent);
				}
			});

		ma = this;
		dbcenter = new DataHelper(this);
		RefreshList();
	}

	public void RefreshList() {
		SQLiteDatabase db = dbcenter.getReadableDatabase();
		cursor = db.rawQuery("SELECT * FROM biodata", null);
		daftar = new String[cursor.getCount()];
		cursor.moveToFirst();
		for (int cc = 0; cc < cursor.getCount(); cc++) {
			cursor.moveToPosition(cc);
			daftar[cc] = cursor.getString(1).toString();
		}
		ListView01 = (ListView) findViewById(R.id.listView1);
		ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftar));
		ListView01.setSelected(true);


		ListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
					final String selection = daftar[arg2];
					//.getItemAtPosition(arg2).toString();
					final CharSequence[] dialogitem = {"Lihat Biodata", "Update Biodata", "Hapus Biodata"};
					AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
					builder.setTitle("Pilihan");
					builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								switch (item) {
									case 0:
										Intent i = new Intent(getApplicationContext(), LihatDataActivity.class);
										i.putExtra ("nama", selection);
										startActivity(i);
										break;
									case 1:
										Intent in = new Intent(getApplicationContext(), UpdateDataActivity.class);
										in.putExtra("nama", selection);
										startActivity(in);
										break;
									case 2:
										SQLiteDatabase db = dbcenter.getWritableDatabase();
										db.execSQL("delete from biodata where nama = '" + selection + "'");
										RefreshList();
										break;
								}
							}
						});
					builder.create().show();
				}
			});
		((ArrayAdapter) ListView01.getAdapter()).notifyDataSetInvalidated();
	}
}

Buat class dengan nama DataHelper dan pastekan kode berikut

import android.database.sqlite.*;
import android.util.*;
import android.content.*;

public class DataHelper extends SQLiteOpenHelper
{
	private static final String DATABASE_NAME = "biodatadiri.db";
	private static final int DATABASE_VERTSION = 1;

	public DataHelper(Context context){
		super(context, DATABASE_NAME,null,DATABASE_VERTSION);
	}
	@Override
	public void onCreate(SQLiteDatabase db){
		String sql = "create table biodata(nama text null, tgl text null, jk text null, alamat text null);";
		Log.d("Data","onCreate: "+sql);
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2){

	}

}



Buat sebuah class lagi dengan nama BuatDataActivity.java pastekan kode berikut

import android.app.*;
import android.database.*;
import android.widget.*;
import android.os.*;
import android.view.*;
import android.database.sqlite.*;
import android.util.*;

public class BuatDataActivity extends Activity
{
	protected Cursor cursor;
	DataHelper dbHelper;
	Button ton1, ton2;
	EditText text2, text3, text4, text5;
	String edit;
	TextView textV2,textV3,textV4,textV5;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buat_data);

		dbHelper = new DataHelper(this);
		text2 = (EditText) findViewById(R.id.editText2);
		text3 = (EditText) findViewById(R.id.editText3);
		text4 = (EditText) findViewById(R.id.editText4);
		text5 = (EditText) findViewById(R.id.editText5);
		ton1 = (Button) findViewById(R.id.button1);
		ton2 = (Button) findViewById(R.id.button2);
		textV2=(TextView)findViewById(R.id.textView2);
		textV3=(TextView)findViewById(R.id.textView3);
		textV4=(TextView)findViewById(R.id.textView4);
		textV5=(TextView)findViewById(R.id.textView5);


		ton1.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					SQLiteDatabase db = dbHelper.getWritableDatabase();

					edit=text2.getText().toString();
					edit=text3.getText().toString();
					edit=text4.getText().toString();
					edit=text5.getText().toString();
					if(edit.isEmpty())
					{
						Toast.makeText(getApplicationContext(),"Kolom tidak boleh kosong...",Toast.LENGTH_SHORT).show();
					}    else{


						db.execSQL("insert into biodata(nama, tgl, jk, alamat) values('" +
								   
								   text2.getText().toString() + "','" +
								   text3.getText().toString() + "','" +
								   text4.getText().toString() + "','" +
								   text5.getText().toString() + "')");
						finish();
					}

					MainActivity.ma.RefreshList();

				}             


			});



		ton2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					finish();
				}
			});


	}

}

Buat class lagi dengan nama LihatDataActivity.java pastekan kode berikut

import android.app.*;
import android.database.*;
import android.widget.*;
import android.os.*;
import android.database.sqlite.*;
import android.view.*;

public class LihatDataActivity extends Activity
{
	protected Cursor cursor;
	DataHelper dbHelper;
	
	TextView text2, text3, text4, text5;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lihat_data);
		dbHelper = new DataHelper(this);
		text2 = (TextView) findViewById(R.id.textView2);
		text3 = (TextView) findViewById(R.id.textView3);
		text4 = (TextView) findViewById(R.id.textView4);
		text5 = (TextView) findViewById(R.id.textView5);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		cursor = db.rawQuery("SELECT * FROM biodata WHERE nama = '" +
							 getIntent().getStringExtra("nama") + "'",null);
		cursor.moveToFirst();
		if (cursor.getCount()>0)
		{
			cursor.moveToPosition(0);
			text2.setText(cursor.getString(1).toString());
			text3.setText(cursor.getString(2).toString());
			text4.setText(cursor.getString(3).toString());
			text5.setText(cursor.getString(4).toString());
		}
		
				
	}

}

Buat sebuah class dengan nama UpdateDataActivity.java pastekan kode berikut

import android.app.*;
import android.database.*;
import android.widget.*;
import android.os.*;
import android.database.sqlite.*;
import android.view.*;

public class UpdateDataActivity extends Activity
{
	protected Cursor cursor;
	DataHelper dbHelper;
	Button ton1, ton2;
	EditText text2, text3, text4, text5;
	String edit;

	TextView textV2,textV3,textV4,textV5;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_data);

		dbHelper = new DataHelper(this);
		text2 = (EditText) findViewById(R.id.editText2);
		text3 = (EditText) findViewById(R.id.editText3);
		text4 = (EditText) findViewById(R.id.editText4);
		text5 = (EditText) findViewById(R.id.editText5);
		textV2=(TextView)findViewById(R.id.textView2);
		textV3=(TextView)findViewById(R.id.textView3);
		textV4=(TextView)findViewById(R.id.textView4);
		textV5=(TextView)findViewById(R.id.textView5);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		cursor = db.rawQuery("SELECT * FROM biodata WHERE nama = '" +
							 getIntent().getStringExtra("nama") + "'",null);
		cursor.moveToFirst();
		if (cursor.getCount()>0)
		{
			cursor.moveToPosition(0);
			text2.setText(cursor.getString(1).toString());
			text3.setText(cursor.getString(2).toString());
			text4.setText(cursor.getString(3).toString());
			text5.setText(cursor.getString(4).toString());
		}
		ton1 = (Button) findViewById(R.id.button1);
		ton2 = (Button) findViewById(R.id.button2);
		// daftarkan even onClick pada btnSimpan
		ton1.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					SQLiteDatabase db = dbHelper.getWritableDatabase();
					edit=text2.getText().toString();
					edit=text3.getText().toString();
					edit=text4.getText().toString();
					edit=text5.getText().toString();
					if(edit.isEmpty())
					{
						Toast.makeText(getApplicationContext(),"Kolom tidak boleh kosong...",Toast.LENGTH_SHORT).show();
					}    else{
						db.execSQL("update biodata set nama='"+
								   text2.getText().toString() +"', tgl='" +
								   text3.getText().toString()+"', jk='"+
								   text4.getText().toString() +"', alamat='" +
								   text5.getText().toString() + "' where no='" +"'");
								   
						Toast.makeText(getApplicationContext(), "Perubahan Tersimpan...", Toast.LENGTH_LONG).show();

						finish();
					}
					MainActivity.ma.RefreshList();
				}
			});
		ton2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					finish();
				}
			});
	}

}

Terakhir tambahkan activity pada AndroidManifest.xml kidenya seperti berikut

<activity
            android:name=".LihatDataActivity"/>
		<activity
            android:name=".UpdateDataActivity"/>
		<activity
            android:name=".BuatDataActivity"/>

Untuk kode full AndroidManifest.xml sebagai berikut

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<activity
            android:name=".LihatDataActivity"/>
		<activity
            android:name=".UpdateDataActivity"/>
		<activity
            android:name=".BuatDataActivity"/>
            
        
    </application>

</manifest>

Kalau sudah silahkan Run.

'Contoh list data'
Sqlite android
'Alert dialog crud'
Sqlite android

Demikian tutorial membuat Sqlite Android,untuk tampilannya masih sederhana,silahkan dikembangkan sendiri,semoga bermanfaat n sukses selalu…salam.

Lihat juga Cara membuat Splash Screen Pada Applikasi Android

Contoh applikasi yang sudah jadi