Laporan Jobsheet 11 Pemrograman Perangkat Bergerak


Program Database Sederhana

 1. Buat project baru dengan nama Db Projek Isur
 2.  Pada package db.isur, buat class baru dengan nama DBAdapter
 3. Sesuaikan source codenya sebagai berikut:

package db.isur;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    private static final String TAG="DBAdapter";
    private static final String DATABASE_NAME="mycompany.sqlite";
    private static final int DATABASE_VERSION=1;
    private static final String TABLE_CREATE = "create table customers (_id integer primary key autoincrement, "
            + "custname text not null, custaddr text not null, "
            + "custgender text not null, custphone text not null)";
    private static final String TABLE_DROP = "DROP TABLE IF EXISTS customers";
   
    public static final String KEY_ROWID="_id";
    public static final String KEY_CUSTNAME="custname";
    public static final String KEY_CUSTADDR="custaddr";
    public static final String KEY_CUSTGENDER="custgender";
    public static final String KEY_CUSTPHONE="custphone";
    private final Context context;
    private DatabaseHelper dbHelper;
    private SQLiteDatabase db;
   
    public DBAdapter (Context ctx) {
        this.context = ctx;
        dbHelper = new DatabaseHelper(this.context);
    }
   
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper (Context ctx) {
            super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
        }
       
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(TABLE_CREATE);
        }
       
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + "to" + newVersion
                    + ", which will destroy all old data");
            db.execSQL(TABLE_DROP);
            onCreate(db);
            }
    }
   
    public DBAdapter open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }
   
    public void close() {
        dbHelper.close();
    }
   
    public long insertCustomer(String custName, String custAddr, char custGender, String custPhone) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_CUSTNAME, custName);
        initialValues.put(KEY_CUSTADDR, custAddr);
        initialValues.put(KEY_CUSTGENDER, Character.toString(custGender));
        initialValues.put(KEY_CUSTPHONE, custPhone);
       
        return db.insert("customers", null, initialValues);
       
    }
   
    public Cursor getAllCustomers() {
        return db.query("customers", new String[] {
                KEY_ROWID, KEY_CUSTNAME, KEY_CUSTADDR, KEY_CUSTGENDER,KEY_CUSTPHONE
        }, null, null, null, null, KEY_ROWID + " DESC");
    }
}  

4.  Pada package db.isur, buat class baru dengan nama CustomerForm
5. Sesuaikan source codenya sebagai berikut:

package db.isur;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;

public class CustomerForm extends Activity{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customer_form);
       
        Button btnEducation = (Button) findViewById(R.id.Save);
        btnEducation.setOnClickListener(new View.OnClickListener(){
            public void onClick(View arg0) {
                String custName = ((EditText) findViewById(R.id.CustName)).getText().toString().trim();
                String custAddr = ((EditText) findViewById(R.id.CustAddr)).getText().toString().trim();
                String custPhone = ((EditText) findViewById(R.id.CustPhone)).getText().toString().trim();
                char custGender = 'X';
               
                switch(((RadioGroup) findViewById(R.id.radioGroup)).getCheckedRadioButtonId()){
                case R.id.GMale:
                    custGender = 'M';
                    break;
                case R.id.GFemale:
                    custGender = 'F';
                    break;
                }
               
                Context Context = CustomerForm.this;
               
                if(custName.equals("") || custAddr.equals("") || custPhone.equalsIgnoreCase("") || custGender == 'X'){
                    String E = "Please COmplete The Data";
                   
                    new AlertDialog.Builder(Context)
                    .setTitle("Invalid Data")
                    .setMessage(E)
                    .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    }).show();
                } else {
                    Intent I = new Intent( CustomerForm.this, SaveCustomer.class);
                    I.putExtra("CustName", custName);
                    I.putExtra("CustAddr", custAddr);
                    I.putExtra("CustPhone", custPhone);
                    I.putExtra("CustGender", custGender);
                    startActivity(I);
                }
            }
        });
    }
}
 
6.  Pada package db.isur, buat class baru dengan nama SaveCustomer
7. Sesuaikan source codenya sebagai berikut:

package db.isur;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SaveCustomer extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.save_customer);
       
        Intent i = getIntent();
        Bundle b = i.getExtras();
       
        String custName = b.getString("CustName");
        String custAddr = b.getString("CustAddr");
        String custPhone = b.getString("CustPhone");
        char custGender = b.getChar("CustGender");
       
        DBAdapter db = new DBAdapter(this);
                try {
                    db.open();
                    long id = db.insertCustomer(custName, custAddr, custGender, custPhone);
                    Toast.makeText(this, "Data successfully saved", Toast.LENGTH_SHORT).show();
                }
                catch (Exception ex) {
                    Toast.makeText(this, "Saving error", Toast.LENGTH_SHORT).show();
        }
        finally {
            db.close();
        }
                Button btnBack = (Button) findViewById(R.id.Button01);
                btnBack.setOnClickListener(new View.OnClickListener() {
                   
                    public void onClick(View arg0) {
                        Intent i = new Intent (SaveCustomer.this, DbProjekIsurActivity.class);
                            startActivity(i);
                    }
                } );
    }
}
 

8.  Sesuaikan source code  pada Db Projek Isur.Activity sebagai berikut:

package db.isur;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DbProjekIsurActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button New = (Button) findViewById(R.id.NewCust);
        New.setOnClickListener(new View.OnClickListener() {
           
            public void onClick(View v) {
                Intent i = new Intent(DbProjekIsurActivity.this, CustomerForm.class);
                    startActivity(i);       
            }
        });
       
        Button Browse = (Button) findViewById(R.id.BrowseCust);
        Browse.setOnClickListener(new View.OnClickListener() {
           
           
            public void onClick(View v) {
                DBAdapter db = new DBAdapter(DbProjekIsurActivity.this);
                db.open();
                Cursor c = db.getAllCustomers();
                if (c.moveToFirst()) {
                    do {
                        Toast.makeText(DbProjekIsurActivity.this, c.getString(1) + ", " + c.getString(2), Toast.LENGTH_SHORT).show();
                    } while (c.moveToNext());
                   
                }
                else
                    Toast.makeText(DbProjekIsurActivity.this, "No data", Toast.LENGTH_SHORT).show();
                db.close();               
            }
        });
    }
}

 
9.  Sesuaikan source code pada main.xml sebagai berikut:

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

    <Button
        android:id="@+id/NewCust"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New" />

    <Button
        android:id="@+id/BrowseCust"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse" />

</LinearLayout>

10. Selanjutnya buat Android XML File di res>layout dengan nama customer_form.xml
11. Sesuaikan source codenya sebagai berikut:

<?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" >

    <TextView
        android:id="@+id/textname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <EditText
        android:id="@+id/CustName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textaddr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Address" />

    <EditText
        android:id="@+id/CustAddr"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <TextView
        android:id="@+id/custGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gender" />
<RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
    <RadioButton
        android:id="@+id/GMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Male" />

    <RadioButton
        android:id="@+id/GFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Female" />

    <TextView
        android:id="@+id/textphone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone" />

    <EditText
        android:id="@+id/CustPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <Button
        android:id="@+id/Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />

    </RadioGroup>
</LinearLayout>

12. Selanjutnya buat Android XML File di res>layout dengan nama save_customer.xml
13. Sesuaikan source codenya sebagai berikut:

<?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" >

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back to Main Menu" />

</LinearLayout>

14.Tambahkan source code pada AndroidManifest.xml berikut:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="db.isur"
    android:versionCode="1"
    android:versionName="1.0" >

  <uses-sdk android:minSdkVersion="7" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DbProjekIsurActivity"
            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=".CustomerForm" android:label="Customer Data"></activity>
        <activity android:name=".SaveCustomer" android:label="Save Data"></activity>

    </application>
   
</manifest> 

15. Jalankan project, sehingga hasilnya sebagai berikut:

 Klik New.

Isikan data berikut, klik save.

Data berhasil disimpan, klik Back to Main Menu

 Klik Browse, sehingga hasilnya seperti berikut:


Komentar

Postingan Populer