Anda di halaman 1dari 27

Belajar Android Studio Membuat Aplikasi CRUD Data Mahasiswa

Agus Haryanto
agus.superwriter@gmail.com
http://agusharyanto.net
Belajar Android studio kali ini akan menarik karena kita akan membuat aplikasi
CRUD Data Mahasiswa dimana nantinya disini kita akan belajar tentang cara
insert, update, delete, select data ke suatu table database sqlite. Disini kita
juga sudah menggunakan beberapa komponen material design seperti
coordinator layout, toolbar, floating action button, RecyclerView dan
CardView.
Sekarang mari kita mulai pembuatannya.
1. Buka Android Studio lalu buat project baru, isi project name dengan
CRUD Data Mahasiswa dan domain name dengan agusharyanto.net
kemudian klik next 2 kali
2. Sampai pada pada jendela add an activity to mobile pilih Blank Activity
lalu klik next sampai finish.
3. Sekarang kita edit script gradle(Module:app)nya lalu ketikan kode berikut.
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId
"net.agusharyanto.cruddatamahasiswa"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles
getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include:
['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompatv7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.android.support:cardview-v7:23.1.0'
compile 'com.android.support:recyclerviewv7:23.1.0'
}

3. Untuk Data Mahasiswa kita perlu buat modelnya. Untuk itu buat class baru
dengan nama Mahasiswa lalu ketikan kode berikut
package net.agusharyanto.cruddatamahasiswa;
import java.io.Serializable;
/**
* Created by agus on 12/1/15.
*/
public class Mahasiswa implements Serializable{
private String id="";
private String nim="";
private String nama="";
private String jurusan="";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNim() {
return nim;
}
public void setNim(String nim) {
this.nim = nim;
}
public String getNama() {
return nama;

}
public void setNama(String nama) {
this.nama = nama;
}
public String getJurusan() {
return jurusan;
}
public void setJurusan(String jurusan) {
this.jurusan = jurusan;
}
@Override
public String toString() {
return "Mahasiswa{" +
"id='" + id + '\'' +
", nim='" + nim + '\'' +
", nama='" + nama + '\'' +
", jurusan='" + jurusan + '\'' +
'}';
}
}

4. Sekarang kita urus pembuatan databasenya, buat class baru dengan nama
DatabaseHelper lalu ketikan kode berikut
package net.agusharyanto.cruddatamahasiswa;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by agus on 12/1/15.
*/
public class DatabaseHelper extends
SQLiteOpenHelper{
private final static String DATABASE_NAME
="dbmahasiswa";
private final static int DATABASE_VERSION = 1;

private final static String MAHASISWA_TABLE =


"tbl_mahasiswa";
private final static String FIELD_ID="_id";
private final static String FIELD_NIMS ="nim";
private final static String FIELD_NAMA="nama";
private final static String
FIELD_JURUSAN="jurusan";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creat table dan init data
String SQL_CREATE_TABLE = "create table "+
MAHASISWA_TABLE +
" ("+FIELD_ID+" integer primary key
autoincrement, "
+ FIELD_NIMS + " text not null,
"+FIELD_NAMA+ " text not null,"
+ FIELD_JURUSAN +" text not null);";
db.execSQL(SQL_CREATE_TABLE);
initData(db);
}
private void initData(SQLiteDatabase db){
ContentValues contentValues = new
ContentValues();
contentValues.put(FIELD_NIMS,"201510001");
contentValues.put(FIELD_NAMA,"Mika");
contentValues.put(FIELD_JURUSAN,"TI");
db.insert(MAHASISWA_TABLE,null,contentValues);
ContentValues contentValues1 = new
ContentValues();
contentValues1.put(FIELD_NIMS,"201510002");
contentValues1.put(FIELD_NAMA,"Fatin");
contentValues1.put(FIELD_JURUSAN, "SI");
db.insert(MAHASISWA_TABLE, null,
contentValues1);
ContentValues contentValues2 = new

ContentValues();
contentValues2.put(FIELD_NIMS,"201510003");
contentValues2.put(FIELD_NAMA,"Muhid");
contentValues2.put(FIELD_JURUSAN, "TI");
db.insert(MAHASISWA_TABLE,null,contentValues2);
}
public ArrayList<Mahasiswa>
getDataMahasiswa(SQLiteDatabase db){
ArrayList<Mahasiswa> mahasiswaArrayList =
new ArrayList<Mahasiswa>();
String[] allColumns = {FIELD_ID, FIELD_NIMS,
FIELD_NAMA, FIELD_JURUSAN};
Cursor cursor =
db.query(MAHASISWA_TABLE,allColumns,null,null,null,n
ull,null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Mahasiswa mahasiswa =
cursorToMahasiswa(cursor);
mahasiswaArrayList.add(mahasiswa);
cursor.moveToNext();
}
return mahasiswaArrayList;
}
public long updateMahasiswa(Mahasiswa mahasiswa,
SQLiteDatabase db) {
ContentValues initialValues = new
ContentValues();
initialValues.put(FIELD_NIMS,
mahasiswa.getNim());
initialValues.put(FIELD_NAMA,
mahasiswa.getNama());
initialValues.put(FIELD_JURUSAN,
mahasiswa.getJurusan());
long rowaffect =db.update(MAHASISWA_TABLE,
initialValues, FIELD_ID + "=" + mahasiswa.getId(),
null);
return rowaffect;
}

public long insertMahasiswa(Mahasiswa mahasiswa,


SQLiteDatabase db) {
ContentValues initialValues = new
ContentValues();
initialValues.put(FIELD_NIMS,
mahasiswa.getNim());
initialValues.put(FIELD_NAMA,
mahasiswa.getNama());
initialValues.put(FIELD_JURUSAN,
mahasiswa.getJurusan());
long insertId = db.insert(MAHASISWA_TABLE,
null,
initialValues);
return insertId;
}
public void deleteMahasiswa(Mahasiswa mahasiswa,
SQLiteDatabase db) {
String id = mahasiswa.getId();
System.out.println("Comment deleted with id:
" + id);
db.delete(MAHASISWA_TABLE, FIELD_ID
+ " = " + id, null);
}
private Mahasiswa cursorToMahasiswa(Cursor
cursor) {
Mahasiswa mahasiswa = new Mahasiswa();
mahasiswa.setId(cursor.getString(0));
mahasiswa.setNim(cursor.getString(1));
mahasiswa.setNama(cursor.getString(2));
mahasiswa.setJurusan(cursor.getString(3));
//
Log.d("TAG", mahasiswa.toString());
return mahasiswa;
}
@Override
public void onUpgrade(SQLiteDatabase db, int
oldVersion, int newVersion) {
}
}

5. Aplikasi CRUD Data mahasiswa ini untuk tampilannya pertama kali


menampilkan data mahasiswa. Untuk itu mari kita siapkan layoutnya.
6. Sebelumnya kita harus siapkan dulu variabel labelnya. Pada directory
res/values/ edit strings.xml lalu ketikan kode berikut.
<resources>
<string name="app_name">CRUD Data
Mahasiswa</string>
<string name="action_settings">Settings</string>
<string name="action_save">Save</string>
<string name="action_delete">Delete</string>
<string name="nim">NIM</string>
<string name="nama">Nama</string>
<string name="jurusan">Jurusan</string>
<string
name="title_activity_mahasiswa">MahasiswaActivity</s
tring>
</resources>

7. pada directory res/layout edit content_mahasiswa.xml lalu ketikan kode


berikut
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:app="http://schemas.android.com/apk/resauto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_marg
in"
android:paddingLeft="@dimen/activity_horizontal_marg
in"
android:paddingRight="@dimen/activity_horizontal_mar

gin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_b
ehavior"
tools:context="net.agusharyanto.cruddatamahasiswa.Ma
inActivity"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

7. pada directory res/layout buat layout baru dengan nama


row_mahasiswa.xml lalu ketikan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cv"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<TextView

android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/nim"
android:id="@+id/textViewRowNim" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/nama"
android:id="@+id/textViewRowNama"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textViewRowNim"
android:layout_toEndOf="@+id/textViewRowNim" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/jurusan"
android:id="@+id/textViewRowJurusan"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

8. Kembali source java buat Activity baru pilih blank activity lalu beri nama
MahasiswaActivity
9. pada directory res/layout edit activity_mahasiswa.xml lalu ketikan kode
berikut
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:app="http://schemas.android.com/apk/resauto"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="net.agusharyanto.cruddatamahasiswa.Ma
hasiswaActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.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" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_mahasiswa" />
<android.support.design.widget.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"
android:src="@android:drawable/ic_menu_save"
/>
</android.support.design.widget.CoordinatorLayout>

10. Edit content_mahasiswa.xml lalu ketikan kode berikut


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"

xmlns:app="http://schemas.android.com/apk/resauto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_marg
in"
android:paddingLeft="@dimen/activity_horizontal_marg
in"
android:paddingRight="@dimen/activity_horizontal_mar
gin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_b
ehavior"
tools:context="net.agusharyanto.cruddatamahasiswa.Ma
hasiswaActivity"
tools:showIn="@layout/activity_mahasiswa">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<EditText
android:id="@+id/editTextNim"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/nim"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/editTextNama"
android:layout_width="match_parent"
android:layout_height="wrap_content"

android:hint="@string/nama"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<EditText
android:id="@+id/editTextJurusan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/jurusan"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>

10. pada direktori res/menu edit menu_mahasiswa.xml lalu ketikan kode


berikut
<menu
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:app="http://schemas.android.com/apk/resauto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="net.agusharyanto.cruddatamahasiswa.Ma
hasiswaActivity">
<item
android:id="@+id/action_save"
android:orderInCategory="100"
android:title="@string/action_save"
android:icon="@android:drawable/ic_menu_save"
app:showAsAction="always" />
<item
android:id="@+id/action_delete"
android:orderInCategory="100"
android:title="@string/action_delete"
android:icon="@android:drawable/ic_menu_delete"

app:showAsAction="always" />
</menu>

11. Sekarang kita beralih ke bagian javanya. Buat class baru dengan nama
MahasiswaAdapter.java lalu ketikan kode berikut.
package net.agusharyanto.cruddatamahasiswa;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
* Created by agus on 12/4/15.
*/
public class MahasiswaAdapter extends
RecyclerView.Adapter<MahasiswaAdapter.MahasiswaViewH
older> {
List<Mahasiswa> mahasiswas;
MahasiswaAdapter(List<Mahasiswa> mahasiswas) {
this.mahasiswas = mahasiswas;
}
@Override
public MahasiswaViewHolder
onCreateViewHolder(ViewGroup viewGroup, int i) {
View v =
LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row_mahasiswa, viewGroup, false);
MahasiswaViewHolder mahasiswaViewHolder =
new MahasiswaViewHolder(v);
return mahasiswaViewHolder;
}
@Override
public void onBindViewHolder(MahasiswaViewHolder
mahasiswaViewHolder, int i) {
mahasiswaViewHolder.mahasiswaName.setText(mahasiswas.
get(i).getNama());

mahasiswaViewHolder.mahasiswaJurusan.setText(mahasis
was.get(i).getJurusan());
mahasiswaViewHolder.mahasiswaNim.setText(mahasiswas.
get(i).getNim());
}
@Override
public int getItemCount() {
return mahasiswas.size();
}
public Mahasiswa getItem(int position) {
return mahasiswas.get(position);
}
@Override
public void
onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(recyclerView);
}
public static class MahasiswaViewHolder extends
RecyclerView.ViewHolder {
CardView cv;
TextView mahasiswaName;
TextView mahasiswaJurusan;
TextView mahasiswaNim;
MahasiswaViewHolder(View itemView) {
super(itemView);
cv = (CardView)
itemView.findViewById(R.id.cv);
mahasiswaName = (TextView)
itemView.findViewById(R.id.textViewRowNama);
mahasiswaJurusan = (TextView)
itemView.findViewById(R.id.textViewRowJurusan);
mahasiswaNim = (TextView)
itemView.findViewById(R.id.textViewRowNim);
}
}

13. Buat class baru dengan nama RecyclerItemListener.java lalu ketikan kode
berikut
package net.agusharyanto.cruddatamahasiswa;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by agus on 12/4/15.
*/
public class RecyclerItemClickListener implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int
position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context
context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new
GestureDetector(context, new
GestureDetector.SimpleOnGestureListener() {
@Override public boolean
onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean
onInterceptTouchEvent(RecyclerView view, MotionEvent
e) {
View childView =

view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null
&& mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView,
view.getChildPosition(childView));
return true;
}
return false;
}
@Override public void onTouchEvent(RecyclerView
view, MotionEvent motionEvent) { }
@Override
public void
onRequestDisallowInterceptTouchEvent(boolean b) {
}
}

14. Edit MainActivity.java lalu ketikan kode berikut


package net.agusharyanto.cruddatamahasiswa;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import
android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import
android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
private RecyclerView mRecyclerView;
private MahasiswaAdapter rvAdapter;
private RecyclerView.LayoutManager

mLayoutManager;
private Context context = MainActivity.this;
private DatabaseHelper databaseHelper;
private SQLiteDatabase db;
private static final int REQUEST_CODE_ADD =1;
private static final int REQUEST_CODE_EDIT =2;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)
findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab =
(FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new
Intent(MainActivity.this, MahasiswaActivity.class);
// intent.putExtra("action",
REQUEST_CODE_ADD);
startActivityForResult(intent,
REQUEST_CODE_ADD);
}
});
initializeData();
mRecyclerView = (RecyclerView)
findViewById(R.id.my_recycler_view);
// use this setting to improve performance
if you know that changes
// in content do not change the layout size
of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new
LinearLayoutManager(this);

mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next
example)
gambarDatakeRecyclerView();
}
private void gambarDatakeRecyclerView(){
rvAdapter = new
MahasiswaAdapter(mahasiswaList);
mRecyclerView.setAdapter(rvAdapter);
mRecyclerView.addOnItemTouchListener(
new
RecyclerItemClickListener(context, new
RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View
view, int position) {
Mahasiswa mahasiswa =
rvAdapter.getItem(position);
//Toast.makeText(context,
"Name :" + mahasiswa.getNama(),
Toast.LENGTH_SHORT).show();
// selectedPosition =
position;
Intent intent = new
Intent(MainActivity.this, MahasiswaActivity.class);
intent.putExtra("mahasiswa",
mahasiswa);
startActivityForResult(intent, REQUEST_CODE_EDIT);
}
})
);
}
private List<Mahasiswa> mahasiswaList;
// This method creates an ArrayList that has
three Fruit objects
private void initializeData(){
databaseHelper = new
DatabaseHelper(context);
db = databaseHelper.getWritableDatabase();

mahasiswaList =
databaseHelper.getDataMahasiswa(db);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode,
resultCode, data);
switch (requestCode) {
case REQUEST_CODE_ADD: {
if (resultCode == RESULT_OK && null !
= data) {
if
(data.getStringExtra("refreshflag").equals("1")) {
mahasiswaList =
databaseHelper.getDataMahasiswa(db);
gambarDatakeRecyclerView();
}
}
break;
}
case REQUEST_CODE_EDIT: {
if (resultCode == RESULT_OK && null !
= data) {
if
(data.getStringExtra("refreshflag").equals("1")) {
mahasiswaList =
databaseHelper.getDataMahasiswa(db);
gambarDatakeRecyclerView();
}
}
break;
}
}
}
@Override
public void onDestroy(){
db.close();
databaseHelper.close();
super.onDestroy();

}
}

15. edit MahasiswaActivity.java lalu ketikan kode berikut


package net.agusharyanto.cruddatamahasiswa;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import
android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
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 MahasiswaActivity extends
AppCompatActivity {
private EditText editTextNIM, editTextNama,
editTextJurusan;
private Button buttonSave, buttonHapus;
private Mahasiswa mahasiswa;
private DatabaseHelper databaseHelper;
private SQLiteDatabase db;
private String action_flag="add";
private String refreshFlag="0";
private static final String
TAG="AddEditActivity";
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahasiswa);
Toolbar toolbar = (Toolbar)

findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab =
(FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
saveData();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true)
;
databaseHelper = new
DatabaseHelper(MahasiswaActivity.this);
db= databaseHelper.getWritableDatabase();
mahasiswa = new Mahasiswa();
initUI();
//initEvent();
Intent intent = getIntent();
if (intent.hasExtra("mahasiswa")) {
mahasiswa = (Mahasiswa)
intent.getSerializableExtra("mahasiswa");
Log.d(TAG, "Mahasiswa : " +
mahasiswa.toString());
setData(mahasiswa);
action_flag = "edit";
editTextNIM.setEnabled(false);
}else{
mahasiswa = new Mahasiswa();
}
}
private void setData(Mahasiswa mahasiswa) {
editTextNIM.setText(mahasiswa.getNim());
editTextNama.setText(mahasiswa.getNama());
editTextJurusan.setText(mahasiswa.getJurusan());
}
private void initUI() {

editTextNIM = (EditText)
findViewById(R.id.editTextNim);
editTextNama = (EditText)
findViewById(R.id.editTextNama);
editTextJurusan = (EditText)
findViewById(R.id.editTextJurusan);
}
private void initEvent() {
buttonSave.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
saveData();
}
});
buttonHapus.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
hapusData();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the
action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mahasiswa,
menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem
item) {
// Handle action bar item clicks here. The
action bar will
// automatically handle clicks on the
Home/Up button, so long
// as you specify a parent activity in

AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_save) {
saveData();
return true;
}else if (id == R.id.action_delete) {
hapusData();
return true;
}
return super.onOptionsItemSelected(item);
}
private void saveData() {
String nama =
editTextNama.getText().toString();
String nim =
editTextNIM.getText().toString();
String jurusan =
editTextJurusan.getText().toString();
mahasiswa.setNim(nim);
mahasiswa.setNama(nama);
mahasiswa.setJurusan(jurusan);
long rowaffect=0;
if (action_flag.equals("add")) {
rowaffect =
databaseHelper.insertMahasiswa(mahasiswa, db);
}else if (action_flag.equals("edit")){
rowaffect =
databaseHelper.updateMahasiswa(mahasiswa, db);
}
if (rowaffect > 0){
Toast.makeText(getBaseContext(), "Save
Data Sukses", Toast.LENGTH_SHORT).show();
refreshFlag="1";
finish();
}else{
Toast.makeText(getBaseContext(), "Save
Data Gagal", Toast.LENGTH_SHORT).show();
}
}

private void hapusData() {


new AlertDialog.Builder(this)
.setTitle("Data Mahasiswa")
.setMessage("Hapus Data " +
mahasiswa.getNama() + " ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
public void
onClick(DialogInterface dialog, int whichButton) {
databaseHelper.deleteMahasiswa(mahasiswa, db);
// hapusDataServer();
refreshFlag = "1";
finish();
}
})
.setNegativeButton(android.R.string.no,
null).show();
}
@Override
public void finish() {
System.gc();
Intent data = new Intent();
data.putExtra("refreshflag", refreshFlag);
// data.putExtra("mahasiswa", mahasiswa);
setResult(RESULT_OK, data);
super.finish();
}
@Override
public void onDestroy(){
db.close();
databaseHelper.close();
super.onDestroy();
}
}

16. Jika semua sudah selesai dibuat maka struktur projectnya akan terlihat
seperti dibawah ini.

17. sekarang mari kita run projectnya.

Bagaimana susah tidak buatnya. Langkah-langkahnya memang agak panjang


tapi kita jadi punya pengalaman membuat aplikasi yang menyimpan ke
database sqlite android. Dan semoga bisa menjadi referensi untuk
dikembangkan menjadi sebuah aplikasi yang bermanfaat bagi user. Seperti
aplikasi Catatan Belanja - http://bit.ly/1QTlGa1