Praktikum 7 | Thread

Praktikum kali ini 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

Buka file values/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 :

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

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









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



 
 
 

Praktikum 7 | Intent

Sekarang Buatlah project baru seperti ketentuan berikut :

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

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> 

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 sebuah file formlogin.xml kemudian masukkan coding dibawah ini:
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>

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

 }
   
}


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

Hasil Running :


 
 

Laporan Praktikum 7 | HTTP CONNECTION

Praktikum kali ini menghubungkan aplikasi android dengan internet dengan menggunakan http connection. disini anda akan belajar bagaimana membuat aplikasi terhubung dengan internet untuk mendowload gambar dan teks, serta menggunakan res.
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

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>
 
Silahkan Download gambar berikut ini : 





Setelah itu kita copy gambar tersebut ke res/drawable-hdpi
Berikut ini source code pada class.

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 Hasil Running :
 
 
 

Praktikum 6 | Tugas 2 | Menu Register dan Viewlist

Disini saya akan membuat Menu Register Dan Viewlist :

Project Name : Tugas2
Buitl Target : Android 2.2
Application name : DBPratice
Package name : com.wilis.database4
Activity : main

main.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"
    >
    <TextView android:layout_height="wrap_content"
        android:id="@+id/textViewMainHeading"
        android:layout_width="wrap_content"
        android:text="Slect your choice"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
       
    </TextView>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Register" android:id="@+id/buttonMainRegister"
        android:layout_below="@+id/textViewMainHeading"
        android:layout_centerHorizontal="true" android:layout_marginTop="70dp">
       
    </Button>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="View List and Details"
        android:id="@+id/ButtonMainList"
        android:layout_below="@+id/textViewMainHeading"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="133dp">
       
    </Button>
</RelativeLayout>

registration.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/buttonRegisterBack"
        android:text="Back">
       
    </Button>
    <EditText android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:id="@+id/editTextRegName"
        android:layout_width="120dp"
        android:layout_below="@+id/buttonRegisterBack"
        android:layout_toRightOf="@+id/textViewRegName"
        android:layout_marginLeft="51dp"
        android:layout_marginTop="18dp">
        <requestFocus>
           
        </requestFocus>
    </EditText>
    <TextView android:layout_height="wrap_content"
        android:id="@+id/textViewRegName"
        android:layout_width="wrap_content"
        android:text="Name"
        android:layout_alignBottom="@+id/editTextRegName"
        android:layout_toRightOf="@+id/buttonRegisterBack"
        android:layout_marginLeft="36dp"
        android:layout_marginBottom="14dp">
       
    </TextView>
    <EditText android:layout_height="wrap_content"
        android:inputType="textPostalAddress"
        android:layout_width="120dp"
        android:layout_below="@+id/editTextRegName"
        android:layout_alignLeft="@+id/editTextRegName"
        android:layout_marginTop="26dp"
        android:id="@+id/editTextRegAddress">
       
    </EditText>
    <TextView android:layout_height="wrap_content"
        android:id="@+id/textViewRegAddress"
        android:layout_width="wrap_content"
        android:text="Address"
        android:layout_alignTop="@+id/editTextRegAddress"
        android:layout_alignLeft="@+id/textViewRegName"
        android:layout_marginTop="14dp">
       
    </TextView>
    <EditText android:layout_height="wrap_content"
        android:inputType="phone"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/editTextRegAddress"
        android:id="@+id/editTextRegPhone"
        android:layout_width="120dp">
       
    </EditText>
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/textViewRegAddress"
        android:id="@+id/textViewRegPhone"
        android:text="Phone No.">
       
    </TextView>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/editTextRegPhone"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:id="@+id/buttonRegister"
        android:text="Register">
       
    </Button>
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/login_icon"
        android:layout_below="@+id/buttonRegister"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:id="@+id/imageViewRegLogin">
       
    </ImageView>
   
</RelativeLayout>

details_users.xml :

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/login_icon"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:id="@+id/imageViewDetailsUserIcon">
       
    </ImageView>
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/imageViewDetailsUserIcon"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="51dp"
        android:id="@+id/textViewDetailsName"
        android:text="Name">
       
    </TextView>
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/textViewDetailsName"
        android:layout_alignLeft="@+id/textViewDetailsName"
        android:layout_marginTop="28dp"
        android:id="@+id/textViewDetailsAddress"
        android:text="Address">
       
    </TextView>
    <TextView android:layout_height="wrap_content"
        android:id="@+id/textViewDetailsPhone"
         android:layout_width="wrap_content"
         android:layout_below="@+id/textViewDetailsAddress"
         android:layout_alignLeft="@+id/textViewDetailsAddress"
         android:layout_marginTop="28dp"
         android:text="Phone">
       
    </TextView>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/buttonDetailsBack"
        android:text="Back">
       
    </Button>
    <Button android:id="@+id/buttonEditDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit Details"
        android:layout_below="@+id/textViewDetailsPhone"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="44dp">
       
    </Button>
   
</RelativeLayout>

edit_user.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/buttonEditBack"
        android:text="Back">
       
    </Button>
    <TextView android:layout_height="wrap_content"
        android:id="@+id/textViewEditAddress"
        android:layout_width="wrap_content"
        android:text="Address"
        android:layout_alignTop="@+id/editTextEditAddress"
        android:layout_alignLeft="@+id/textViewEditName"
        android:layout_marginTop="14dp">
       
    </TextView>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/editTextEditPhone"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:id="@+id/buttonEdit"
        android:text="Update">
       
    </Button>
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/login_icon"
        android:layout_below="@+id/buttonEdit"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:id="@+id/imageViewEditLogin">
       
    </ImageView>
    <TextView android:id="@+id/textViewEditName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:layout_alignBottom="@+id/editTextEditName"
        android:layout_toRightOf="@+id/buttonEditBack"
        android:layout_marginBottom="14dp">
       
    </TextView>
    <EditText android:layout_width="120dp"
        android:inputType="textPersonName"
        android:layout_height="wrap_content"
        android:id="@+id/editTextEditName"
        android:layout_below="@+id/buttonEditBack"
        android:layout_alignLeft="@+id/buttonEdit">
        <requestFocus>
           
        </requestFocus>
    </EditText>
    <EditText android:layout_width="120dp"
        android:inputType="textPostalAddress"
        android:layout_height="wrap_content"
        android:id="@+id/editTextEditAddress"
        android:layout_below="@+id/editTextEditName"
        android:layout_alignLeft="@+id/editTextEditName"
        android:layout_marginTop="14dp">
       
    </EditText>
    <EditText android:layout_width="120dp"
        android:inputType="phone"
        android:layout_height="wrap_content"
        android:id="@+id/editTextEditPhone"
        android:layout_below="@+id/editTextEditAddress"
        android:layout_alignLeft="@+id/editTextEditAddress"
        android:layout_marginTop="14dp">
       
    </EditText>
    <TextView android:id="@+id/textViewEditPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone No."
        android:layout_alignTop="@+id/editTextEditPhone"
        android:layout_toRightOf="@+id/buttonEditBack"
        android:layout_marginTop="15dp">
       
    </TextView>
</RelativeLayout>
 

list_users.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="22px"
        android:layout_height="22px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/login_icon" >
    </ImageView>

    <TextView
        android:id="@+id/textViewList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/icon"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/icon"
        android:text="@+id/label"
        android:textSize="20px" />
   
</RelativeLayout>
 
Silahkan Download gambar berikut ini : 






Setelah itu kita copy gambar tersebut ke res/drawable-hdpi
Berikut ini source code pada class.

DBPracticeActivity.java :

package com.example.activity;

import com.example.db.R;

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

public class DBPracticeActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button regButton = (Button)findViewById(R.id.buttonMainRegister);
        Button listButton = (Button)findViewById(R.id.ButtonMainList);
        regButton.setOnClickListener(this);
        listButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch(v.getId()) {
        case R.id.buttonMainRegister :
            intent = new Intent();
            intent.setClass(getApplicationContext(), Registration.class);
            startActivity(intent);
            break;
        case R.id.ButtonMainList :
            intent = new Intent();
            intent.setClass(getApplicationContext(), ListUsers.class);
            startActivity(intent);
            break;
        }
    }
}

DetailsUsers.java :

  package com.example.activity;

import com.example.db.DatabaseHandler;
import com.example.db.R;
import com.example.db.User;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DetailsUsers  extends Activity implements OnClickListener{
    private static String position = null;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_users);
        Intent intent = getIntent();
        position = intent.getStringExtra("position");
        Log.d("value of position from intent", position);
        DatabaseHandler db = new DatabaseHandler(this);
        User user = db.getUser(position);
        TextView textViewDetailName = (TextView) findViewById(R.id.textViewDetailsName);
        textViewDetailName.setText(user.getName());
      
        TextView textViewDetailAddress = (TextView) findViewById(R.id.textViewDetailsAddress);
        textViewDetailAddress.setText(user.getAddress());
      
        TextView textViewDetailsPhone = (TextView) findViewById(R.id.textViewDetailsPhone);
        textViewDetailsPhone.setText(user.getPhone());
      
        Button backButton = (Button)findViewById(R.id.buttonDetailsBack);
        backButton.setOnClickListener(this);
      
        Button editButton = (Button)findViewById(R.id.buttonEditDetails);
        editButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.buttonDetailsBack) {
            Intent intent = new Intent(getApplicationContext(), ListUsers.class);
            startActivity(intent);
        }
        else if(v.getId() == R.id.buttonEditDetails) {
            Intent intent = new Intent(getApplicationContext(), EditUsers.class);
            intent.putExtra("position", position);
            startActivity(intent);
        }
    }
}

EditUsers.java :

package com.example.activity;

import com.example.db.DatabaseHandler;
import com.example.db.R;
import com.example.db.User;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EditUsers extends Activity implements OnClickListener{
    private static String position = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_user);
        Intent intent = getIntent();
        position = intent.getStringExtra("position");

        DatabaseHandler db = new DatabaseHandler(this);
        Log.d("position", position);
        //get user for the position clicked for edit
        User user = db.getUser(position);
      
        Log.d("User Name", user.getName());
        Log.d("Address", user.getAddress());
        Log.d("Users phone", user.getPhone());
      
        //set the values in editText boxes
        EditText name = ((EditText)findViewById(R.id.editTextEditName));
        name.setText(user.getName());
        EditText address = ((EditText)findViewById(R.id.editTextEditAddress));
        address.setText(user.getAddress());
        EditText phone = ((EditText)findViewById(R.id.editTextEditPhone));
        phone.setText(user.getPhone());
      
        Button backButton = (Button)findViewById(R.id.buttonEditBack);
        backButton.setOnClickListener(this);
      
        Button updateButton = (Button)findViewById(R.id.buttonEdit);
        updateButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.buttonEditBack) {
            Intent intent = new Intent(getApplicationContext(), ListUsers.class);
            startActivity(intent);
        }
        else if(v.getId() == R.id.buttonEdit) {
            User user = new User(
                            ((EditText)findViewById(R.id.editTextEditName)).getText().toString(),
                            ((EditText)findViewById(R.id.editTextEditAddress)).getText().toString(),
                            ((EditText)findViewById(R.id.editTextEditPhone)).getText().toString()
                        );
            DatabaseHandler db = new DatabaseHandler(this);
            int updateCount = db.editUser(user, position);
            if(updateCount == 1) {
                Toast toast = Toast.makeText(getApplicationContext(),
                        "User successfully updated",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                Toast toast = Toast.makeText(getApplicationContext(),
                        "User update failed, Try Again",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

}
 
ListUsers.java :

package com.example.activity;

import java.util.List;

import com.example.db.DatabaseHandler;
import com.example.db.R;
import com.example.db.User;

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

public class ListUsers extends ListActivity{
   
    public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
         DatabaseHandler db = new DatabaseHandler(this);
        String[] users = db.getAllUsers();
        if(users!=null) {
            for(String us:users) {
                Log.d("String Array Value", us);
            }
            db.close();
        }
        // Use your own layout
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_users, R.id.textViewList, users);
        setListAdapter(adapter);
    }
   
     @Override
      protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.d("On click of a item", Integer.toString(position));
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), DetailsUsers.class);
        intent.putExtra("position", Integer.toString(position + 1));  //position starts from 0, but in db row starts from 1
        startActivity(intent);
      }
}
 
Registration.java :

package com.example.activity;

import com.example.db.DatabaseHandler;
import com.example.db.R;
import com.example.db.User;

import android.app.Activity;
import android.content.Intent;
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 Registration extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);
        Button regButton = (Button)findViewById(R.id.buttonRegister);
        regButton.setOnClickListener(this);
        Button backButton = (Button)findViewById(R.id.buttonRegisterBack);
        backButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch(v.getId()) {
        case R.id.buttonRegister :
            register();
            break;
        case R.id.buttonRegisterBack :
            intent = new Intent();
            intent.setClass(getApplicationContext(), DBPracticeActivity.class);
            startActivity(intent);
            break;
        }  
    }

    private void register() {
        String user = ((EditText)findViewById(R.id.editTextRegName)).getText().toString();
        String address = ((EditText)findViewById(R.id.editTextRegAddress)).getText().toString();
        String phone = ((EditText)findViewById(R.id.editTextRegPhone)).getText().toString();
        DatabaseHandler db = new DatabaseHandler(this);
        int id = db.addUser(new User(user,address,phone));
        db.close();
        if(id>0) {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "User registered at id " + id,
                    Toast.LENGTH_SHORT);
            toast.show();
        }
        else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "User registration failed",
                    Toast.LENGTH_SHORT);
            toast.show();
        }
        ((EditText)findViewById(R.id.editTextRegName)).setText("");
        ((EditText)findViewById(R.id.editTextRegAddress)).setText("");
        ((EditText)findViewById(R.id.editTextRegPhone)).setText("");
    }

}
 

Hasil Running :

 
 

Praktikum 6 | Tugas 3 | CRUD

Baiklah Praktikum Kali ini Saya Membuat Aplikasi CRUD Android Dengan Menggunakan DatabaseSQlite. Berikut Projectnya :

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

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





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

Layout/listitem.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: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>




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

Baiklah Pada Class saya Menggunakan 7 class :
Class Name : Customer.java, CustomerListAdapter.java, CustomerSQLHelper.java, DatabaseApps.java, NewActivity.java, NewForm.java, Utils.java.

 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;
        public TextView phoneView;
       
    }
   
    @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);
            holder.phoneView   = (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()+"-"+cust.get(position).getPhone();
        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();
            }               
        });
    }   
   
    //Perintah
    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();
    }
}


Hasil Running :