Praktikum 6 | Tugas 1 | Membuat Koneksi Database



Silahkan Buat project baru seperti berikut ini :

Project Name : DatabaseApps
Buitl Target : Android 2.2
Application name : database4
Package name : com.wilis.database4
Activity : database4
Min SDK :8

1. Pada Package Explorer, Buka file main.xml di folder res/layout/main.xml
Ganti Source Code Berikut ini :

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>



2. Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama detail_form.xml
Ganti Source Code pada detail_form.xml. seperti berikut :

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1"
    >
    <TableRow>
        <TextView android:text="Nama:" />
        <EditText android:id="@+id/nama" />
    </TableRow>
    <TableRow>
        <TextView android:text="Alamat:" />
        <EditText android:id="@+id/alamat" />
    </TableRow>
    <TableRow>
        <TextView android:text="Jenis Kelamin:" />
        <RadioGroup android:id="@+id/jekel">
            <RadioButton android:id="@+id/pria"
                android:text="Pria"
            />
            <RadioButton android:id="@+id/perempuan"
                android:text="Perempuan"
            />
           
        </RadioGroup>
    </TableRow>
    <TableRow>
        <TextView android:text="Hp:" />
        <EditText android:id="@+id/hp"
            android:singleLine="false"
            android:gravity="top"
            android:lines="2"
            android:scrollHorizontally="false"
            android:maxLines="2"
            android:maxWidth="200sp"
        />
    </TableRow>
    <Button android:id="@+id/save"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save"
    />
</TableLayout>
 

3. Setelah itu Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama row.xml
Ganti Source Code pada row.xml seperti berikut : 


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="4px"
    >
    <ImageView android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="4px"
    />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >   
        <TextView android:id="@+id/title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:textStyle="bold"
            android:singleLine="true"
            android:ellipsize="end"
        />
        <TextView android:id="@+id/alamat"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:singleLine="true"
            android:ellipsize="end"
        />
    </LinearLayout>
</LinearLayout>



Baiklah Pada Classnya saya membuat  Class Yaitu :
Class Name : AlmagHelper.java, Database4.java, DetailForm.java, dan EditPreferences.java.

Class AlmagHelper.java

package com.wilis.database4;

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

class AlmagHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="addressmanager4.db";
    private static final int SCHEMA_VERSION=1;
   
    public AlmagHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE almag (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, alamat TEXT, jekel TEXT, hp TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // no-op, since will not be called until 2nd schema
        // version exists
    }

    public Cursor getAll(String orderBy) {
        return(getReadableDatabase()
                        .rawQuery("SELECT _id, nama, alamat, jekel, hp FROM almag ORDER BY "+orderBy,
                                            null));
    }
   
    public Cursor getById(String id) {
        String[] args={id};

        return(getReadableDatabase()
                        .rawQuery("SELECT _id, nama, alamat, jekel, hp FROM almag WHERE _ID=?",
                                            args));
    }
   
    public void insert(String nama, String alamat,
                                         String jekel, String hp) {
        ContentValues cv=new ContentValues();
                   
        cv.put("nama", nama);
        cv.put("alamat", alamat);
        cv.put("jekel", jekel);
        cv.put("hp", hp);
       
        getWritableDatabase().insert("almag", "nama", cv);
    }
   
    public void update(String id, String nama, String alamat,
                                         String jekel, String hp) {
        ContentValues cv=new ContentValues();
        String[] args={id};
       
        cv.put("nama", nama);
        cv.put("alamat", alamat);
        cv.put("jekel", jekel);
        cv.put("hp", hp);
       
        getWritableDatabase().update("almag", cv, "_ID=?",
                                                                 args);
    }
   
    public String getNama(Cursor c) {
        return(c.getString(1));
    }
   
    public String getAlamat(Cursor c) {
        return(c.getString(2));
    }
   
    public String getJekel(Cursor c) {
        return(c.getString(3));
    }
   
    public String getHp(Cursor c) {
        return(c.getString(4));
    }
}


Class Database4.java :

package com.wilis.database4;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;


public class database4 extends ListActivity {
    public final static String ID_EXTRA="com.wilis.database4._ID";
    Cursor model=null;
    AlmagAdapter adapter=null;
    EditText nama=null;
    EditText alamat=null;
    EditText hp=null;
    RadioGroup jekel=null;
    AlmagHelper helper=null;
    SharedPreferences prefs=null;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        helper=new AlmagHelper(this);
        prefs=PreferenceManager.getDefaultSharedPreferences(this);
       
        nama=(EditText)findViewById(R.id.nama);
        alamat=(EditText)findViewById(R.id.alamat);
        hp=(EditText)findViewById(R.id.hp);
        jekel=(RadioGroup)findViewById(R.id.jekel);
       
        initList();
        prefs.registerOnSharedPreferenceChangeListener(prefListener);
    }
   
    @Override
    public void onDestroy() {
        super.onDestroy();
       
        helper.close();
    }
   
    @Override
    public void onListItemClick(ListView list, View view,
                                                            int position, long id) {
        Intent i=new Intent(database4.this, DetailForm.class);

        i.putExtra(ID_EXTRA, String.valueOf(id));
        startActivity(i);
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.option, menu);

        return(super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.add) {
            startActivity(new Intent(database4.this, DetailForm.class));
           
            return(true);
        }
        else if (item.getItemId()==R.id.prefs) {
            startActivity(new Intent(this, EditPreferences.class));
       
            return(true);
        }

        return(super.onOptionsItemSelected(item));
    }
   
    private void initList() {
        if (model!=null) {
            stopManagingCursor(model);
            model.close();
        }
       
        model=helper.getAll(prefs.getString("sort_order", "nama"));
        startManagingCursor(model);
        adapter=new AlmagAdapter(model);
        setListAdapter(adapter);
    }
   
    private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
     new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences sharedPrefs,
                                                                                    String key) {
            if (key.equals("sort_order")) {
                initList();
            }
        }
    };
   
    class AlmagAdapter extends CursorAdapter {
        AlmagAdapter(Cursor c) {
            super(database4.this, c);
        }
       
        @Override
        public void bindView(View row, Context ctxt,
                                                 Cursor c) {
            AlmagHolder holder=(AlmagHolder)row.getTag();
           
            holder.populateFrom(c, helper);
        }
       
        @Override
        public View newView(Context ctxt, Cursor c,
                                                 ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.row, parent, false);
            AlmagHolder holder=new AlmagHolder(row);
           
            row.setTag(holder);
           
            return(row);
        }
    }
   
    static class AlmagHolder {
        private TextView nama=null;
        private TextView alamat=null;
        private ImageView icon=null;
        private View row=null;
       
        AlmagHolder(View row) {
            this.row=row;
           
            nama=(TextView)row.findViewById(R.id.title);
            alamat=(TextView)row.findViewById(R.id.alamat);
            icon=(ImageView)row.findViewById(R.id.icon);
        }
       
        void populateFrom(Cursor c, AlmagHelper helper) {
            nama.setText(helper.getNama(c));
            alamat.setText(helper.getAlamat(c));
   
            if (helper.getJekel(c).equals("Pria")) {
                icon.setImageResource(R.drawable.pria);
            }
            else if (helper.getJekel(c).equals("Perempuan")) {
                icon.setImageResource(R.drawable.perempuan);
            }
           
        }
    }


Class DetailForm.java :

package com.wilis.database4;


import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

public class DetailForm extends Activity {
    EditText nama=null;
    EditText alamat=null;
    EditText hp=null;
    RadioGroup jekel=null;
    AlmagHelper helper=null;
    String almagId=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_form);

        helper=new AlmagHelper(this);
       
        nama=(EditText)findViewById(R.id.nama);
        alamat=(EditText)findViewById(R.id.alamat);
        hp=(EditText)findViewById(R.id.hp);
        jekel=(RadioGroup)findViewById(R.id.jekel);
       
        Button save=(Button)findViewById(R.id.save);
       
        save.setOnClickListener(onSave);
       
        almagId=getIntent().getStringExtra(database4.ID_EXTRA);
       
        if (almagId!=null) {
            load();
        }
    }
   
    @Override
    public void onDestroy() {
        super.onDestroy();
   
        helper.close();
    }
   
    private void load() {
        Cursor c=helper.getById(almagId);

        c.moveToFirst();       
        nama.setText(helper.getNama(c));
        alamat.setText(helper.getAlamat(c));
        hp.setText(helper.getHp(c));
       
        if (helper.getJekel(c).equals("Pria")) {
            jekel.check(R.id.pria);
        }
        else if (helper.getJekel(c).equals("Perempuan")) {
            jekel.check(R.id.perempuan);
        }
       
       
        c.close();
    }
   
    private View.OnClickListener onSave=new View.OnClickListener() {
        public void onClick(View v) {
            String type=null;
           
            switch (jekel.getCheckedRadioButtonId()) {
                case R.id.pria:
                    type="Pria";
                    break;
                case R.id.perempuan:
                    type="Perempuan";
                    break;
               
            }

            if (almagId==null) {
                helper.insert(nama.getText().toString(),
                                            alamat.getText().toString(), type,
                                            hp.getText().toString());
            }
            else {
                helper.update(almagId, nama.getText().toString(),
                                            alamat.getText().toString(), type,
                                            hp.getText().toString());
            }
           
            finish();
        }
    };


Class EditPreferences.java :

package com.wilis.database4;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class EditPreferences extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        addPreferencesFromResource(R.xml.preferences);
    }
}


 
Setelah itu Running dengan klik Kanan package > Runa As > Android A. Lihat Hasilnya Seperti Dibawah Ini :

                


Sekian Dan Terima Kasih ... ^_^
 

0 komentar:

Posting Komentar