Senin, 15 Juni 2015

LAPORAN PRATIKUM 7 | HTTP CONNECTION

Edit Posted by with No comments
Pembahasan selanjutnya adalah menghubungkan aplikasiandroid dengan internet dengan menggunakan http connection, disini anda akan belajar bagaimana membuat aplikasi terhubung dengan internet untuk mendowload gambar dan teks, serta menggunakan rss.
Buatlah project baru seperti ketentuan berikut :

Project Name : HttpURLConnectionA
Buitl Target : Android 2.2
Application name : HttpURLConnectionA
Package name : com.bogotobogo.httpconnecta
Activity : main.xml
Min SDK :8

Buka file layout/main.xml

main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="vertical">
    <Button
    android:id="@+id/Button01"
    android:text="@string/button01"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
    </Button>
    <Button android:id="@+id/Button02"
    android:layout_height="wrap_content"
    android:text="@string/button02"
    android:layout_width="wrap_content">
    </Button>
    <ImageView
    android:id="@+id/imageview01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:cropToPadding="true" >
    </ImageView>
    <TextView 
    android:id="@+id/textview01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>




Kita Download keduan gambar dibawah ini

Setelah itu kita copy kedua gambar icon di folder res, Perhatikan gambar berikut

Pada package src/HttpURLConnectionA, bukaHttpURLConnectionA.java pastikan kodenya seperti berikut
HttpURLConnectionA.java
package com.bogotobogo.httpconnecta;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class HttpURLConnectionA extends Activity {
  
    private ProgressDialog progressDialog;  
    private Bitmap bitmap = null;
    private String text = null;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button imageBtn = (Button)findViewById(R.id.Button01);
        Button textBtn = (Button)findViewById(R.id.Button02);
      
        imageBtn.setOnClickListener( new OnClickListener() {
            public void onClick(View v) {
                downloadImage("http://www.bogotobogo.com/images/smalltiger.gif");          
            }
        });
      
        textBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                downloadText("http://www.bogotobogo.com/android.html");
            }
        });
    }
  
    private void downloadImage(String urlStr) {
        progressDialog = ProgressDialog.show(this, "",
                    "Downloading Image from " + urlStr);
        final String url = urlStr;
      
        new Thread() {
            public void run() {
                InputStream in = null;
                Message msg = Message.obtain();
                msg.what = 1;
                try {
                    in = openHttpConnection(url);
                    bitmap = BitmapFactory.decodeStream(in);
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b);
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                messageHandler.sendMessage(msg);                  
            }
         }.start();
    }
  
    private void downloadText(String urlStr) {
        progressDialog = ProgressDialog.show(this, "",
                "Download Text from " + urlStr);
        final String url = urlStr;
      
        new Thread () {
            public void run() {
                int BUFFER_SIZE = 2000;
                InputStream in = null;
                Message msg = Message.obtain();
                msg.what=2;
                try {
                    in = openHttpConnection(url);
                  
                    InputStreamReader isr = new InputStreamReader(in);
                    int charRead;
                      text = "";
                      char[] inputBuffer = new char[BUFFER_SIZE];

                          while ((charRead = isr.read(inputBuffer))>0)
                          {                  
                              String readString =
                                  String.copyValueOf(inputBuffer, 0, charRead);                  
                              text += readString;
                              inputBuffer = new char[BUFFER_SIZE];
                          }
                         Bundle b = new Bundle();
                            b.putString("text", text);
                            msg.setData(b);
                          in.close();
                    
                }catch (IOException e2) {
                    e2.printStackTrace();
                }
                messageHandler.sendMessage(msg);
            }
        }.start();  
    }
  
    private InputStream openHttpConnection(String urlStr) {
        InputStream in = null;
        int resCode = -1;
      
        try {
            URL url = new URL(urlStr);
            URLConnection urlConn = url.openConnection();
          
            if (!(urlConn instanceof HttpURLConnection)) {
                throw new IOException ("URL is not an Http URL");
            }
          
            HttpURLConnection httpConn = (HttpURLConnection)urlConn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            resCode = httpConn.getResponseCode();               
            if (resCode == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                               
            }       
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return in;
    }
  
    private Handler messageHandler = new Handler() {
      
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 1:
                ImageView img = (ImageView) findViewById(R.id.imageview01);
                img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
                break;
            case 2:
                TextView text = (TextView) findViewById(R.id.textview01);
                text.setText(msg.getData().getString("text"));
                break;
            }
            progressDialog.dismiss();
        }
    };
}

Untuk Mengatasi Terjadi Force Close, Pada package src/AndroidManifest, buka AndroidManifest.xml pastikan kodenya seperti berikut 
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:versionCode="1"
      android:versionName="1.0" package="com.bogotobogo.httpconnecta">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HttpURLConnectionA"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>  
Setelah itu Run dengan shourcut CTRL+F11 atau klik Kanan package > Runa As > Android Projeck. Lihat Hasilnya Seperti Dibawah Ini


 



 

Minggu, 14 Juni 2015

LAPORAN PRAKTIKUM 7 CARA MEMBUAT INTEN

Edit Posted by with No comments
Buatlah project baru seperti ketentuan berikut :

Project Name : Intent
Buitl Target : Android 2.2
Application name : Intent
Package name : www.percobaan3.com
Activity : database4

 Source code string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Try Intent - Aplysit</string>
    <string name="app_name">Try Intent www.aplysit.com</string>
</resources>

Source code main.xml

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

Source code formlogin.xml

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

<RelativeLayout android:id="@+id/widget61"
   android:layout_height="76px"
   android:background="#ffffff"
   android:layout_x="0px"
   android:layout_y="0px"
   android:layout_width="match_parent">

<TextView android:id="@+id/widget62" 
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="FORM LOGIN"
   android:textSize="20sp"
   android:textStyle="bold"
   android:textColor="#000000"
   android:layout_centerVertical="true"
   android:layout_centerHorizontal="true">
</TextView>
</RelativeLayout>

<TextView android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/widget30"
   android:text="NICK"
   android:layout_x="12dip"
   android:layout_y="125dip">
</TextView>

<TextView android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/widget31"
   android:text="PWD"
   android:layout_x="18dip"
   android:layout_y="198dip">
</TextView>


<EditText android:layout_height="wrap_content"
   android:text="" android:layout_width="179px"
   android:textSize="18sp"
   android:layout_x="81dip"
   android:layout_y="185dip"
   android:id="@+id/pass_editText">
</EditText>

<EditText android:layout_height="wrap_content"
   android:text=""
   android:layout_width="179px"
   android:textSize="18sp" 
   android:layout_x="78dip"
   android:layout_y="118dip"
   android:id="@+id/name_editText">
</EditText>

<Button android:text="RESET"
   android:layout_height="wrap_content"
   android:layout_width="92px"
   android:layout_x="33dip"
   android:layout_y="277dip"
   android:id="@+id/reset_btn">
</Button>

<Button android:text="SUBMIT" 
   android:layout_height="wrap_content"
   android:layout_width="92px" 
   android:layout_x="181dip"
   android:layout_y="276dip"
   android:id="@+id/submit_btn">
</Button>

</AbsoluteLayout>

Langkah selanjutnya modifikasi file manifest.xml
Kemudian buatlah sebuah file UsingIntent.java

Source code UsingIntent.java  
 


package www.percobaan3.com;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Usingintent extends ListActivity {
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        //Menyusun menu
        String[] menu = new String[]{"Login","Exit"};
       
        // Menampilkan menu di LisstMenu
        this.setListAdapter(new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, menu));
    }
   
    @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  super.onListItemClick(l, v, position, id);
 
  // Menangkap nilai text yang dklik
  Object o = this.getListAdapter().getItem(position);
  String pilihan = o.toString();
  tampilkanPilihan(pilihan);
 }
   
    protected void tampilkanPilihan(String pilihan) {
   //Intent digunakan untuk sebagai pengenal suatu activity
   Intent i = null;
   if (pilihan.equals("Login")) {    
 
    i = new Intent(this, login.class);
   }
   else if (pilihan.equals("Exit")) {
    finish();
   }
  
   startActivity(i);

 }
   
}

Lalu buatlah sebuah file login.java
login.java
package www.percobaan3.com;

import www.percobaan3.com.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class login extends Activity {
 public String nama;
 EditText name;
 EditText pass;

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.formlogin);
       
        name = (EditText) findViewById(R.id.name_editText);
        pass = (EditText) findViewById(R.id.pass_editText);
       
       
        Button reset = (Button) findViewById(R.id.reset_btn);
        reset.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
    // TODO Auto-generated method stub
    name.setText("");
    pass.setText("");

}
        });
       
        Button submit = (Button) findViewById(R.id.submit_btn);
        submit.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
          // TODO Auto-generated method stub
    nama = name.getText().toString();
    Toast.makeText(getApplicationContext(), "Welcome "+nama,
7).show();
         }
         });
 }
}

Berikut Hasil Runningnya

Terima kasih.
Somoga Bermanfaat.   


 

LAPORAN PRATIKUM 7 | THREAD

Edit Posted by with No comments
Percobaan kali ini adalah untuk membuat sebuah thread yang akan menampilkan pesan
secara terus menerus dan sebuah bilangan acak.

Buatlah project baru seperti ketentuan berikut :
Project Name : Thread
Buitl Target : Android 2.2
Application name : Thread
Package name : www.percobaan2.com
Activity : database4
Min SDK :8

Buka file values/string.xml lalu modifikasi sehingga menjadi source berikut ini:

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Aplysit - IT Solution Center</string>
    <string name="app_name">Try Thread - www.aplysit.com</string>
</resources>

Selanjutnya main.xml lalu modifikasi codingnya

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="Start"
    android:layout_height="wrap_content"
android:id="@+id/btn_start"
android:layout_width="wrap_content">
   
</Button>
<Button android:text="Stop"
    android:layout_height="wrap_content"
android:id="@+id/btn_stop"
android:layout_width="wrap_content">
   
</Button>
</LinearLayout>
 
Lalu buatlah sebuah file benama mythread.java ketikkan coding dibawah ini

Mythread.java

package www.percobaan2.com;


import android.content.Context;
import android.os.Handler;

public class Mythread {
 public Handler mhandler;
 public showText text;

 public Mythread (Context context, Handler handler){
  mhandler = handler;
 }

 public synchronized void startShowText() {
  if (text == null) {
   text = new showText();
   text.start();
  }
 }

 public synchronized void stopShowText() {
  if (text != null) {
   text.requestStop();
   text = null;
  }
 }

 private class showText extends Thread {
  private volatile boolean stop = false;
   
  public void run() {
   while ((!stop)){   
    mhandler.obtainMessage(threadsimple.run,"Pesan dari thread" + Math.random()).sendToTarget();
    try {
     sleep(3000);
    }
    catch (Exception e){}
   }
   if (stop) {
    mhandler.obtainMessage(threadsimple.stop).sendToTarget();
   }
  }
 
  public synchronized void requestStop() {
            stop = true;
  }
 }


Kemudian buatlah sebuah file threadsimple.java lalu masukkan coding dibawah ini:
  
threadsimple.java

package www.percobaan2.com;

import www.percobaan2.com.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class threadsimple extends Activity {
 public static final int run = 1;
 public static final int stop = 2;
 public Mythread thread;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button start = (Button)findViewById(R.id.btn_start);
        start.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    //  TODO Auto-generated method stub
       thread.startShowText();
       System.out.println("run");
   }
        });
       
        Button stop = (Button)findViewById(R.id.btn_stop);
        stop.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    //  TODO Auto-generated method stub
       thread.stopShowText();
       System.out.println("stop");
   }
        });
    }
    public void onStart() {
        super.onStart();
        thread = new Mythread(this, mHandler);
       }
      
       private final Handler mHandler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               switch (msg.what) {
               case run:
                Toast.makeText(getApplicationContext(), msg.obj.toString(), 2).show();
               break;
               case stop:
                Toast.makeText(getApplicationContext(), "Thread Stop", 2).show();
               break;
               }
           }
       };
   }
    
Hasil Runningnya Seperti dibawah ini

Terima Kasih
Semoga Bermanfaat...




TUGAS 3 MEMBUAT CRUD

Edit Posted by with No comments
Buatlah project baru seperti ketentuan berikut :

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

Pada Package Explorer, Buka file main.xml di folder res/layout, perhatikan gambar berikut

Ganti Kode pada main.xml menjadi sepertik berikut

main.xml

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

Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama inputdata.xml
Ganti Kode pada inputdata.xml menjadi sepertik berikut :

inputdata.xml  


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

    <TextView android:id="@+id/txt_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textSize="20px"
        android:text="title" />

    <EditText android:id="@+id/data_name" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:hint="Your name"/>
    <EditText android:id="@+id/data_address" android:layout_width="fill_parent"
        android:layout_height="100px" android:hint="Your address"
        android:gravity="top" android:singleLine="false"/>   
    <EditText android:id="@+id/data_phone" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:phoneNumber="true"
        android:hint="Your phone" />
           
    <Button android:id="@+id/submit_button" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="submit" />
    <Button android:id="@+id/cancel_button" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="cancel" />
</LinearLayout>


Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama listitem.xml
Ganti Kode pada listitem.xml menjadi sepertik berikut :

listitem.xm

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:padding="5px" >
   
    <CheckedTextView android:id="@+id/txt_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:text="Name Customer"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple" />
   
    <TextView android:id="@+id/txt_id"
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:visibility="gone" />
       
</LinearLayout>

 listview.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">   
    <ListView android:id="@+id/list_data"
        android:layout_width="fill_parent"
        android:layout_above="@+id/add_button"
        android:layout_height="fill_parent" />       
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/list_empty"
        android:text="no data" android:gravity="center_vertical|center_horizontal"
        android:layout_above="@+id/add_button" />       
    <Button android:id="@+id/add_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentBottom="true"
        android:text="Add" android:layout_marginLeft="35px"/>       
    <Button android:id="@+id/update_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentBottom="true"
        android:layout_toRightOf="@id/add_button" android:text="Update" />
    <Button android:id="@+id/delete_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentBottom="true"
        android:layout_toRightOf="@id/update_button" android:text="Delete" />
    <Button android:id="@+id/exit_button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentBottom="true"
        android:layout_toRightOf="@id/delete_button" android:text="Exit"/>       
</RelativeLayout>

login.xml

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

Disini Saya menggunakan 6 class


Berikut Sourcode Classnya.  
Customer.java

package com.wilis.databaseapp;

public class Customer {

    long id;
    String name;
    String address;
    String phone;
    boolean complete;
   
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public boolean isComplete() {
        return complete;
    }
    public void setComplete(boolean complete) {
        this.complete = complete;
    }
   
    // -------------------------------------------
    public void toggleComplete() {
        complete = !complete;
    }   
   
}

CustomerListAdapter.java  

package com.wilis.databaseapp;

import java.util.ArrayList;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;

public class CustomerListAdapter extends BaseAdapter {

    ArrayList<Customer> cust;
    Context context;
   
    public CustomerListAdapter(Context context, ArrayList<Customer> custs) {
        super();
        this.cust = custs;
        this.context = context;
    }

    @Override
    public int getCount() {
        return cust.size();
    }

    @Override
    public Customer getItem(int position) {
        return (null == cust) ? null : cust.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
   
    public static class ViewHolder {
        public CheckedTextView nameView;
        public TextView idView;       
       
    }
   
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       
        ViewHolder holder;
        View vi = convertView;
       
        if (null == convertView) {
            LayoutInflater infalInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            vi = infalInflater.inflate(R.layout.listitem, null);
           
            holder = new ViewHolder();           
            holder.nameView = (CheckedTextView) vi.findViewById(R.id.txt_name);
            holder.idView   = (TextView) vi.findViewById(R.id.txt_id);
           
            vi.setTag(holder);
        }
        else
            holder = (ViewHolder) vi.getTag();
       
        String txtName = cust.get(position).getName()+"-"+cust.get(position).getAddress();
        String txtId   = String.valueOf(cust.get(position).getId());
        boolean check  = cust.get(position).isComplete();
       
        holder.nameView.setText(txtName);
        holder.nameView.setChecked(check);       
        holder.idView.setText(txtId);
       
        return vi;
    }
   
    public void forceReload() {
        notifyDataSetChanged();
    }   
    public void toggleDataCompleteAtPosition(int position) {
        Customer cust = getItem(position);
        cust.toggleComplete();
        notifyDataSetChanged();
    }   
    public Long[] removeCheckedCustomer() {
        ArrayList<Customer> completedTasks = new ArrayList<Customer>();
        ArrayList<Long> completedIds = new ArrayList<Long>();
        for (Customer dtCust : cust) {
            if (dtCust.isComplete()) {
                completedTasks.add(dtCust);
                completedIds.add(dtCust.getId());
            }
        }
        cust.removeAll(completedTasks);
        notifyDataSetChanged();
        return completedIds.toArray(new Long[]{});
    } 
   
    public Customer getCheckedCustomer() {
        Customer newCust = new Customer();       
        for (Customer dtCust : cust) {
            if (dtCust.isComplete()) {
                newCust = dtCust; break;
            }
        }       
        return newCust;
    }
}


CustomerSQLHelper.java

package com.wilis.databaseapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CustomerSQLHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "customer_db.sqllite";
    public static final int VERSION = 1;
   
    public static final String TASKS_TABLE = "customer";
    public static final String TASK_ID = "id";
    public static final String TASK_NAME = "name";
    public static final String TASK_ADDRESS = "address";
    public static final String TASK_PHONE   = "phone";
    public static final String TASK_COMPLETE = "complete";
   
    public CustomerSQLHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createTable(db);
    }

    private void createTable(SQLiteDatabase db) {
        db.execSQL("create table " + TASKS_TABLE + " ( " +
        TASK_ID + " integer primary key autoincrement not null, " +
        TASK_NAME + " text, " +
        TASK_ADDRESS + " text, " +
        TASK_PHONE + " text, " +
        TASK_COMPLETE + " text " +
        ");"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

DatabaseApps .java

package com.wilis.databaseapp;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class DatabaseApps extends Activity {
   
    ArrayList<Customer> currentData;
    SQLiteDatabase database;
    CustomerListAdapter adapter;
    ListView list;
    CustomerSQLHelper helper;
    Customer cust;
   
    Button btnSubmit, btnCancel;
    TextView txtTitle;
    EditText dtName, dtAddress, dtPhone;
   
    Utils util;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
       
        util = new Utils(this);
        list = (ListView) findViewById(R.id.list_data);
       
        CustomerSQLHelper helper = new CustomerSQLHelper(this);
        database = helper.getWritableDatabase();
      
        currentData = new ArrayList<Customer>();
        // ---- load data ----
        currentData = util.loadData();
       
        adapter = new CustomerListAdapter(this, currentData);
        list.setAdapter(adapter);
        list.setEmptyView(findViewById(R.id.list_empty));
       
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
               
                adapter.toggleDataCompleteAtPosition(position);
            }
        });
       
        list.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View v,
                    int position, long id) {
               
                Customer c = adapter.getItem(position);
                util.onShowData(c, DatabaseApps.this);
                return false;

            }
        });
       
        // set button click
        onButtonClick();
    }
   
    // ----------------------------------------------
    @Override
    protected void onResume() {
        super.onResume();
        adapter.forceReload();
    }   
   
    // -----------------------------------------------
    public void onButtonClick() {
        Button btnAdd = (Button) findViewById(R.id.add_button);
        btnAdd.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {                   
                 onCreateWidgetData(1, new Customer());  }               
        });
       
        Button btnUpdate = (Button) findViewById(R.id.update_button);
        btnUpdate.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                Customer c = adapter.getCheckedCustomer();
                if (!c.getName().equals(""))
                    onCreateWidgetData(2, c);
                else {
                    Toast.makeText(DatabaseApps.this, "Harus centang satu",
                            Toast.LENGTH_LONG).show();
                }
            }               
        });
       
        Button btnDelete = (Button) findViewById(R.id.delete_button);
        btnDelete.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                Customer c = adapter.getCheckedCustomer();
                onDeleteData(c.getId());               
            }               
        });
       
        Button btnExit = (Button) findViewById(R.id.exit_button);
        btnExit.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            }               
        });
       
    }
   
    public void onCreateWidgetData(int param, final Customer getCust) {       
       
        switch(param) {
            // add data new
            case 1:
                widgetAdd();          
                break;               
            // update existing data
            case 2:
                widgetUpdate(getCust);
                break;           
        }
    }
   
    public void widgetAdd() {
        setContentView(R.layout.inputdata);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("Add Data");       
        btnSubmit = (Button) findViewById(R.id.submit_button);
       
        btnSubmit.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                dtName = (EditText) findViewById(R.id.data_name);
                dtAddress = (EditText) findViewById(R.id.data_address);
                dtPhone = (EditText) findViewById(R.id.data_phone);
               
                if (dtName.getText().length()<1
                    || dtAddress.getText().length()<1
                    || dtPhone.getText().length()<1) {
                    Toast.makeText(DatabaseApps.this, "Check your input...",
                            Toast.LENGTH_SHORT).show();
                }
                else {
                    cust = new Customer();                       
                    cust.setName(dtName.getText().toString());
                    cust.setAddress(dtAddress.getText().toString());
                    cust.setPhone(dtPhone.getText().toString());
                    cust.setComplete(false);
                    util.onSaveData(cust);
                    onCancel();
                }
            }               
        });
       
        btnCancel = (Button) findViewById(R.id.cancel_button);
        btnCancel.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {                   
                onCancel();
            }               
        });
    }
   
   
   
    public void widgetUpdate(final Customer getCust) {
        setContentView(R.layout.inputdata);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("Update Data");
       
        dtName = (EditText) findViewById(R.id.data_name);
        dtName.setText(getCust.getName());
       
        dtAddress = (EditText) findViewById(R.id.data_address);
        dtAddress.setText(getCust.getAddress());
       
        dtPhone = (EditText) findViewById(R.id.data_phone);
        dtPhone.setText(getCust.getPhone());
       
        btnSubmit = (Button) findViewById(R.id.submit_button);
        btnSubmit.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                dtName = (EditText) findViewById(R.id.data_name);
                dtAddress = (EditText) findViewById(R.id.data_address);
                dtPhone = (EditText) findViewById(R.id.data_phone);
                if (dtName.getText().length()<1
                    || dtAddress.getText().length()<1
                    || dtPhone.getText().length()<1) {
                    Toast.makeText(DatabaseApps.this, "Check your input...", Toast.LENGTH_SHORT);
                }
                else {                   
                    getCust.setName(dtName.getText().toString());
                    getCust.setAddress(dtAddress.getText().toString());
                    getCust.setPhone(dtPhone.getText().toString());
                    util.onUpdateData(getCust); onCancel();
                }
            }               
        });       
       
        btnCancel = (Button) findViewById(R.id.cancel_button);
        btnCancel.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {                   
                onCancel();
            }               
        });
    }   
    public void onDeleteData(long id) {
        // Long[] ids = adapter.removeCheckedCustomer();
        // deleteData(ids);
       
        deleteData(new Long[]{id});       
        currentData = util.loadData();       
        adapter = new CustomerListAdapter(this, currentData);
        list.setAdapter(adapter);
    }   
   
    @SuppressWarnings("static-access")
    public void deleteData(Long[] ids) {
        StringBuffer idList = new StringBuffer();
        for (int i =0; i< ids.length; i++) {
            idList.append(ids[i]);
            if (i < ids.length -1 ) {
                idList.append(",");
            }
        }
       
        String where = String.format("%s in (%s)", helper.TASK_ID, idList);
        database.delete(helper.TASKS_TABLE, where, null);
    }
   
    public void onCancel() {
        Intent newIntent = new Intent().setClass(DatabaseApps.this,
                DatabaseApps.class);
        startActivity(newIntent);
        finish();
    }
   
    // -----------------------------------------------
}
 
 NewActivity.java

package com.wilis.databaseapp;

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

public class NewActivity extends Activity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inputdata);
       
       
    }
   
}

NewForm.java

package com.wilis.databaseapp;

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

public class NewForm extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

    }

}




Utils.java 

package com.wilis.databaseapp;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Utils {   
    CustomerSQLHelper helper;
    SQLiteDatabase database;   
   
    public Utils(Context ctx) {
        helper = new CustomerSQLHelper(ctx);
        database = helper.getWritableDatabase();
    }
   
    @SuppressWarnings("static-access")
    public ArrayList<Customer> loadData() {
        ArrayList<Customer> currentData = new ArrayList<Customer>();
        Cursor dataCursor = database.query(helper.TASKS_TABLE,
                new String[] {helper.TASK_ID, helper.TASK_NAME,
                helper.TASK_ADDRESS,
                helper.TASK_PHONE, helper.TASK_COMPLETE},
                null, null, null, null,
                String.format("%s, %s", helper.TASK_COMPLETE, helper.TASK_NAME));
       
        dataCursor.moveToFirst();
        Customer t;
       
        if ( !dataCursor.isAfterLast() ) {
            do {
                int id = dataCursor.getInt(0);  // coloum ID
                String name = dataCursor.getString(1); // coloum name
                String addr = dataCursor.getString(2); // coloum address
                String phon = dataCursor.getString(3); // coloum phone
                String boolValue = dataCursor.getString(4); // coloum complete
                boolean complete = Boolean.parseBoolean(boolValue);               
               
                t = new Customer();
                t.setId(id);
                t.setName(name);
                t.setAddress(addr);
                t.setPhone(phon);
                t.setComplete(complete);
               
                currentData.add(t);
               
            } while(dataCursor.moveToNext());
        }   
       
        /*
        while (dataCursor.moveToNext()) {
           
        }
        */
       
        dataCursor.close();       
        return currentData;
    }
   
    @SuppressWarnings("static-access")
    public void onSaveData(Customer getCust) {
        assert (null != getCust);
       
        ContentValues values = new ContentValues();
        values.put(helper.TASK_NAME, getCust.getName());
        values.put(helper.TASK_ADDRESS, getCust.getAddress());
        values.put(helper.TASK_PHONE, getCust.getPhone());
        values.put(helper.TASK_COMPLETE, Boolean.toString(false));
       
        getCust.setId(database.insert(helper.TASKS_TABLE, null, values));
    }
   
    @SuppressWarnings("static-access")
    public void onUpdateData(Customer getCust) {
        assert (null != getCust);       
        ContentValues values = new ContentValues();
        values.put(helper.TASK_NAME, getCust.getName());
        values.put(helper.TASK_ADDRESS, getCust.getAddress());
        values.put(helper.TASK_PHONE, getCust.getPhone());
        values.put(helper.TASK_COMPLETE, Boolean.toString(getCust.isComplete()));       
        long id = getCust.getId();
        String where = String.format("%s = %d", helper.TASK_ID, id);
        database.update(helper.TASKS_TABLE, values, where, null);
    }
   
    AlertDialog alert;
    public void onShowData(Customer cust, Context ctx) {
        final Customer thisCust = cust;       
        alert = new AlertDialog.Builder(ctx).setIcon(R.drawable.icon)
            .setTitle("Display Data")
            .setMessage(" ------------ Customer -------------\n"
                      + "ID: "+thisCust.getId()+"\n"
                      + "Name: "+thisCust.getName()+"\n"
                      + "Adress: "+thisCust.getAddress()+"\n"
                      + "Phone: "+thisCust.getPhone()+"\n")
            .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                   alert.cancel();
                }
            }).create();           
        alert.show();
    }
}


 Semoga Bermanfaat......



  

TUGAS 1 MEMBUAT KONEKSI DATABASE

Edit Posted by with No comments
Buatlah project baru seperti ketentuan berikut :

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, perhatikan gambar berikut


 Ganti Kode pada main.xml menjadi seperti berikut

main.xml

<?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 Kode pada detail_form.xml menjadi seperti berikut :

detail_form.xml

<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. Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama detail_form.xml Ganti Kode pada detail_form.xml menjadi seperti berikut : row.xml

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

Disini Saya Menggunakan 4 Class


4. Pada package src/AlmagHelper, buka AlmagHelper.java pastikan kodenya seperti berikut


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));
    }
}


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);
            }
           
        }
    }
} 

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();
        }
    };
}




 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);
    }
}

Untuk Mengatasi Terjadi Force Close, Pada package src/AndroidManifest, buka AndroidManifest.xml pastikan kodenya seperti berikut



Setelah itu Run dengan shourcut CTRL+F11 atau klik Kanan package > Runa As > Android Projeck. Lihat Hasilnya Seperti Dibawah Ini 


Terima kasih 
semoga Bermanfaat....