Indoensia Tanah Airku

Thursday 4 June 2015

Android Membuat Spinner from PHP and MySQL using JSON

Spinner from PHP and MySQL using JSON


***Pertama buatlah database seperti ini :

CREATE DATABASE customers;
CREATE TABLE `customer` (
`customerID` int(2) NOT NULL,
`name` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
PRIMARY KEY (`customerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `customer`
--

INSERT INTO `customer` VALUES (1, 'John', '0786333210');
INSERT INTO `customer` VALUES (2, 'Sam', '0786223210');
INSERT INTO `customer` VALUES (3, 'Ali', '0786543210')


***Kedua buatlah koneksi dengan Script PHP seperti ini :

<?php
 $objConnect = mysql_connect("localhost","YourName","YourPassword");
 $objDB = mysql_select_db("customers");
 $strSQL = "SELECT * FROM customer WHERE 1 ";
 $objQuery = mysql_query($strSQL);
 $intNumField = mysql_num_fields($objQuery);
 $resultArray = array();
 while($obResult = mysql_fetch_array($objQuery))
 {
 $arrCol = array();
 for($i=0;$i<$intNumField;$i++)
 {
 $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
 }
 array_push($resultArray,$arrCol);
 }

mysql_close($objConnect);

echo json_encode($resultArray);

?>

Berinama   getCustomers.php dan  simpan di polder C://XAMPP/htdocs.

***Ketiga buatlah project di eclipse baru dengan ketentuan sgi brkut :


Application Name  :  “Custemers dropdown”
Project Name         : CustemersDropdown

Package Name        : com.custemersdropdown

***Kempat rubahlah isi dari AndroidManifest.xml dengan kode di bawah ini :


<uses-permission android:name="android.permission.INTERNET"/>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.custemersdropdown"
 android:versionCode="1"
 android:versionName="1.0" >

<uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.INTERNET"/>

<application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.custemersdropdown.MainActivity"
 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>

***Klima isikan printah di bawah ini pada activity_main.xml :

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/tableLayout1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <TableRow
 android:id="@+id/tableRow1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:text="Dropdown Example "
 android:layout_span="1"
 android:textAppearance="?android:attr/textAppearanceLarge" />

 </TableRow>

<View
 android:layout_height="1dip"
 android:background="#CCCCCC" />

 <LinearLayout
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.1">

 <Spinner
 android:id="@+id/spinner1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

 </LinearLayout>

<View
 android:layout_height="1dip"
 android:background="#CCCCCC" />

 <LinearLayout
 android:id="@+id/LinearLayout1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="5dip" >

<TextView
 android:id="@+id/textView2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="https://androidappcode.wordpress.com/" />

</LinearLayout>


</TableLayout>

***Kenam buatlah Layout baru dengan nama activity_show.xml dan isikan perintah di bawah ini :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
    android:id="@+id/ColCustomerID"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="CustomerID"/>

    <TextView
        android:id="@+id/ColName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Name"/>

    <TextView
        android:id="@+id/ColTel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Tel" />


</LinearLayout>

***Ketujuh isikan/copy'kan perintah di bawah ini pada class MainActivity.java :

package com.custemersdropdown;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

@SuppressLint("NewApi") public class MainActivity extends Activity {

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

 // Permission StrictMode
 if (android.os.Build.VERSION.SDK_INT > 9) {
 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);
 }

 // spinner1
 final Spinner spin = (Spinner)findViewById(R.id.spinner1);

 String url = "http://10.0.2.2/customer/getcustomers.php";

try {

 JSONArray data = new JSONArray(getJSONUrl(url));

 final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
 HashMap<String, String> map;

 for(int i = 0; i < data.length(); i++){
 JSONObject c = data.getJSONObject(i);

 map = new HashMap<String, String>();
 map.put("customerID", c.getString("customerID"));
 map.put("name", c.getString("name"));
 map.put("phone", c.getString("phone"));
 MyArrList.add(map);

 }
 SimpleAdapter sAdap;
 sAdap = new SimpleAdapter(MainActivity.this, MyArrList, R.layout.activity_show,
 new String[] {"customerID", "name", "phone"}, new int[] {R.id.ColCustomerID, R.id.ColName, R.id.ColTel});
 spin.setAdapter(sAdap);

 final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this);

 spin.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View selectedItemView,
 int position, long id) {
 String sCustomerID = MyArrList.get(position).get("customerID")
 .toString();
 String sName = MyArrList.get(position).get("name")
 .toString();
 String sTel = MyArrList.get(position).get("phone")
 .toString();

 viewDetail.setIcon(android.R.drawable.btn_star_big_on);
 viewDetail.setTitle("Customer Detail");
 viewDetail.setMessage("customerID : " + sCustomerID + "\n"
 + "name : " + sName + "\n" + "Tel : " + sTel);
 viewDetail.setPositiveButton("OK",
 new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog,
 int which) {
 // TODO Auto-generated method stub
 dialog.dismiss();
 }
 });
 viewDetail.show();

 }

public void onNothingSelected(AdapterView<?> arg0) {
 // TODO Auto-generated method stub
 Toast.makeText(MainActivity.this,
 "Your Selected : Nothing",
 Toast.LENGTH_SHORT).show();
 }
 });

 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

}

public String getJSONUrl(String url) {
 StringBuilder str = new StringBuilder();
 HttpClient client = new DefaultHttpClient();
 HttpGet httpGet = new HttpGet(url);
 try {
 HttpResponse response = client.execute(httpGet);
 StatusLine statusLine = response.getStatusLine();
 int statusCode = statusLine.getStatusCode();
 if (statusCode == 200) { // Download OK
 HttpEntity entity = response.getEntity();
 InputStream content = entity.getContent();
 BufferedReader reader = new BufferedReader(new InputStreamReader(content));
 String line;
 while ((line = reader.readLine()) != null) {
 str.append(line);
 }
 } else {
 Log.e("Log", "Failed to download result..");
 }
 } catch (ClientProtocolException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

 return str.toString();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // getMenuInflater().inflate(R.menu.activity_main, menu);
 return true;
 }


}

***Terakhir Run lah program anda makan akan jadi seperti ini :








Ok thank,,,jika ada pertanyaan mengenai tutorial di atas silahkan berkomentar..!!!!

Wednesday 3 June 2015

Pemrograman Android

Koneksi Android DENGAN MYSQL


      Salah satu yang mungkin sempat menjadi pertanyaan buat kita yang biasa bekerja di lingkungan web adalah, bagaimana sih caranya membangun koneksi antara Android dengan MySQL. Sebelum kita mulai ngoding, kita perlu memahami teorinya terlebih dahulu. Mungkin diagram di bawah ini dapat menjadi gambaran awal bagi kita untuk mengetahui proses koneksi antara Android dengan Web Server.


      Jadi yang pertama dilakukan adalah, Android akan mengirimkan Request ke Web Server, yang biasa dikenal dengan method HTTPRequest, yang bisa mengandung parameter. Di web server, kita perlu membuat file PHP untuk meresponse dari permintaan client. Fungsi ini biasa dikenal dengan fungsi API (Application Programming Interface) Setelah permintaan dari client (Android) diproses, maka perlu ada nilai yang harus dikembalikan. Data yang dikembalikan bisa berformat JSON ataupun XML. Pada saat Android menerima data yang dikembalikan ini, dia membutuhkan sebuah class parser untuk dapat membaca data yang dikembalikan tadi. Seperti yang tadi disebutkan, data yang dikirim kembali dapat berupa JSON atau XML.

      Untuk contoh dibawah ini, saya menggunakan class AsyncTask untuk memproses permintaan dari Android Client. Prinsip kerjanya mirip dengan AJAX, jika teman2 biasa ngoding AJAX di web application tentunya tidak akan kesulitan dalam memahami AsyncTask. Ada beberapa method penting yang harus kita perhatikan pada class AsyncTask ini      

1. onPreExecute


Method ini yang akan dijalankan pada activity yang aktif, pada saat request dikirimkan ke web server. oleh karena itu, bentuk tampilannya biasanya berupa gambar ataupun tulisan Loading...
Berikut adalah contoh snippet code nya:
                                                                                                                                             
Protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
                                                                                                                                                 

2. doInBackground

Method ini yang akan memproses permintaan ke web server.

3. onPostExecute

Method ini akan dijalankan setelah proses doInBackground selesai dikerjakan. Artinya method ini yang akan menampilkan hasilnya.

Ok tanpa menunggu lama lagi, berikut adalah contoh coding mengambil string yang ada di web server. Data yang diterima kembali dari Android dalam bentuk JSON, sehingga kita akan membutuhkan class JSONObject.
                                                                                                                                             
package ngodingandroid.httprequest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import ngodingandroid.httprequest.R.string;

public class ProfileActivity extends Activity {

TextView txtUsername;
TextView txtFullname;
TextView txtPosition;
TextView txtSubject;

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

JSONObject profile;

private static final String PROFILE_URL = "http://yoururl.com/data.php";

private static final String TAG_PROFILE = "data";
private static final String TAG_USER = "username";
private static final String TAG_NAME = "fullname";
private static final String TAG_POSITION = "position";
private static final String TAG_SUBJECT = "subject";

@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);

txtUsername = (TextView) findViewById(R.id.username);
txtFullname = (TextView) findViewById(R.id.fullname);
txtPosition = (TextView) findViewById(R.id.position);
txtSubject = (TextView) findViewById(R.id.subject);

new LoadProfile().execute();

}

/**
* Background Async Task to Load profile by making HTTP Request
* */

class LoadProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting Profile JSON
* */

protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("username", user));

// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "GET",params);

try {
// profile json object
profile = json.getJSONObject(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}

return null;

}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Storing each json item in variable
try {
String username = profile.getString(TAG_USER);
String fullname = profile.getString(TAG_NAME);
String position = profile.getString(TAG_POSITION);
String subject = profile.getString(TAG_SUBJECT);

// displaying all data in textview
txtUsername.setText("Username: " + username);
txtFullname.setText("Fullname: " + fullname);
txtPosition.setText("Position: " + position);
txtSubject.setText("Subject: " + subject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

});


}
   
}

}
                                                                                                                                             
   
      Demikianlah cara sederhana untuk mendapatkan data berdasarkan parameter yang dikirim oleh Android Client. Dalam contoh di atas, kita mengirimkan nilai parameter username, yang nantinya akan diproses oleh API dan dengan format JSON akan dikembalikan data-data detail dari username tersebut.
(Sumber: androidhive.info)

Monday 1 June 2015

Android Dasar SQLlite CRUD,Membuat button save,cari,edit dan delet

Dasar SQLlite,Membuat button save,cari,edit,dan delet

Pertama buatlah project baru
Nama Aplikasi : Note PIN
Project Name :scrool
Package Name : com.taufik
Activity name :  MainActivity
Layout Name : activity_main

1).Isikan code di pawah ini pada string.xml yang berada pada Folder “res>menu”.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Masukkan Nama dan PIN</string>
    <string name="app_name">NotePIN</string>
    <string name="btnAddtxt">Save</string>
    <string name="namaLabel">Nama</string>
    <string name="hobiLabel">PIN BB</string>
    <string name="nomorLabel">No.</string>
    <string name="btnGetRow">Cari</string>
    <string name="btnUpdateRow">Update</string>
    <string name="ketUpdate">Sebelum mengubah data,pilih dulu baris ke berapa data yang akan diubah</string>
    <string name="ketAmbilBaris">Tulis No Urut</string>
    <string name="ketDelete">Tulis No Urut</string>
    <string name="btnDel">Delete</string>

</resources>
2.Isikan code dibawah ini pada activiry_maim.xml yang berada di folder “res>layout”
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/hello" />

            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <EditText
                    android:id="@+id/inNama"
                    android:layout_width="118dp"
                    android:layout_height="wrap_content"
                    android:ems="10" />

                <requestFocus />

                <EditText
                    android:id="@+id/inHobi"
                    android:layout_width="91dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.47"
                    android:ems="10" >
                </EditText>

                <Button
                    android:id="@+id/btnAdd"
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.33"
                    android:text="Save" />
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/ketUpdate" >
            </TextView>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <LinearLayout
                android:id="@+id/linearLayout2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/ketAmbilBaris" >
                </TextView>

                <EditText
                    android:id="@+id/inGetId"
                    android:layout_width="48dp"
                    android:layout_height="wrap_content" >
                </EditText>

                <Button
                    android:id="@+id/btnGetId"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Cari" >
                </Button>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/linearLayout3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <EditText
                    android:id="@+id/inUpdateNama"
                    android:layout_width="100dip"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.16" >
                </EditText>

                <EditText
                    android:id="@+id/inUpdateHobi"
                    android:layout_width="100dip"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.65" >
                </EditText>

                <Button
                    android:id="@+id/btnUpdate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.23"
                    android:text="Update" >
                </Button>
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <LinearLayout
                android:id="@+id/linearLayout4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Delete" />

                <EditText
                    android:id="@+id/idDelete"
                    android:layout_width="47dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Delete" />
            </LinearLayout>

            <View
                android:id="@+id/view2"
                android:layout_width="wrap_content"
                android:layout_height="1dip"
                android:background="#FF909090" >
            </View>

            <TableLayout
                android:id="@+id/tabel_data"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >

                    <TextView
                        android:id="@+id/no_id"
                        android:layout_width="50dip"
                        android:layout_height="wrap_content"
                        android:text="@string/nomorLabel" >
                    </TextView>

                    <TextView
                        android:id="@+id/nama_id"
                        android:layout_width="100dip"
                        android:layout_height="wrap_content"
                        android:text="@string/namaLabel" >
                    </TextView>

                    <TextView
                        android:id="@+id/hobi_id"
                        android:layout_width="100dip"
                        android:layout_height="wrap_content"
                        android:text="@string/hobiLabel" >
                    </TextView>
                </TableRow>
            </TableLayout>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

3).Isikan code dibawah ini pada MainActivity.java yang berada di folder “src”

package com.taufik;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
                DatabaseManager dm;
                EditText nama, hobi, GetId, updateNama, updateHobi, idDel;
                Button addBtn, getIdBtn, updateBtn, delBtn;
                TableLayout tabel4data;

                // tabel for data
                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.activity_main);
                                dm = new DatabaseManager(this);
                                setupView();
                                fungsiBtn();
                                updateTable();
                }

                public void setupView() {
                                 tabel4data = (TableLayout) findViewById(R.id.tabel_data);
                                  nama = (EditText) findViewById(R.id.inNama);
                                  hobi = (EditText) findViewById(R.id.inHobi);
                                 updateNama = (EditText) findViewById(R.id.inUpdateNama);
                                  updateHobi = (EditText) findViewById(R.id.inUpdateHobi);
                                  GetId = (EditText) findViewById(R.id.inGetId);
                                  idDel=(EditText)findViewById(R.id.idDelete);
                                  addBtn = (Button) findViewById(R.id.btnAdd);
                                  getIdBtn = (Button) findViewById(R.id.btnGetId);
                                  updateBtn = (Button) findViewById(R.id.btnUpdate);
                                  delBtn = (Button) findViewById(R.id.button1);
                }

                public void fungsiBtn() {
                                addBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                                simpKamuta();
                                                                kosongkanField();
                                                }
                                });
                                getIdBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View b) {
                                                                ambilBaris();
                                                }
                                });

                                updateBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View c) {
                                                                updateBaris();
                                                                kosongkanField();
                                                }
                                });
                                delBtn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View d) {

                                                                // TODO Auto-generated method stub
                                                                deleteData();
                                                                kosongkanField();
                                                }
                                });
                }

                protected void kosongkanField() {
                                nama.setText("");
                                hobi.setText("");
                                updateNama.setText("");
                                updateHobi.setText("");
                                GetId.setText("");
                                idDel.setText("");
                }

                private void deleteData() {
                                dm.deleteBaris(Long.parseLong(idDel.getText().toString()));
                                updateTable();
                }

                protected void updateBaris() {
                                dm.updateBaris(Long.parseLong(GetId.getText().toString()), updateNama
                                                                .getText().toString(), updateHobi.getText().toString());
                                updateTable();
                }

                private void ambilBaris() {
                                try {
                                                ArrayList<Object> baris;
                                                baris = dm.ambilBaris(Long.parseLong(GetId.getText().toString()));
                                                updateNama.setText((String) baris.get(1));
                                                updateHobi.setText((String) baris.get(2));
                                } catch (NumberFormatException e) {
                                                e.printStackTrace();
                                                Log.e("eror db", e.toString());
                                                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                                                                                .show();
                                }
                }

                protected void simpKamuta() {
                                try {
                                                dm.addRow(nama.getText().toString(), hobi.getText().toString());
                                                updateTable();
                                } catch (Exception e) {

                                                e.printStackTrace();
                                                Toast.makeText(getBaseContext(), "gagal simpan," + e.toString(),
                                                                                Toast.LENGTH_LONG).show();
                                }
                }

                protected void updateTable() {
                                while (tabel4data.getChildCount() > 1) {
                                                tabel4data.removeViewAt(1);
                                }
                                ArrayList<ArrayList<Object>> data = dm.ambilSemuaBaris();
                                //
                                for (int posisi = 0; posisi < data.size();

                                posisi++) {
                                                TableRow tabelBaris = new TableRow(this);
                                                ArrayList<Object> baris = data.get(posisi);
                                                TextView idTxt = new TextView(this);
                                                idTxt.setText(baris.get(0).toString());
                                                tabelBaris.addView(idTxt);
                                                TextView namaTxt = new TextView(this);
                                                namaTxt.setText(baris.get(1).toString());
                                                tabelBaris.addView(namaTxt);
                                                TextView hobiTxt = new TextView(this);
                                                hobiTxt.setText(baris.get(2).toString());
                                                tabelBaris.addView(hobiTxt);
                                                tabel4data.addView(tabelBaris);
                                }
                }
}

4.Kemudin buat class baru dengan nama DatabaseManager.java,dan isiskan code di bawah ini

package com.taufik;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DatabaseManager {
                private static final String ROW_ID = "_id";
                private static final String ROW_NAMA = "nama";
                private static final String ROW_HOBI = "hobi";
                private static final String NAMA_DB = "DatabaseAndroidDua";
                private static final String NAMA_TABEL = "hobiku ";
                private static final int DB_VERSION = 1;
                private static final String CREATE_TABLE = "create table " + NAMA_TABEL
                                                + " (" + ROW_ID + " integer PRIMARY KEY autoincrement," + ROW_NAMA
                                                + " text," + ROW_HOBI + " text)";
                private final Context context;
                private DatabaseOpenHelper dbHelper;
                private SQLiteDatabase db;

                public DatabaseManager(Context ctx) {
                                this.context = ctx;
                                dbHelper = new DatabaseOpenHelper(ctx);
                                db = dbHelper.getWritableDatabase();
                }

                private static class DatabaseOpenHelper extends SQLiteOpenHelper {
                                public DatabaseOpenHelper(Context context) {
                                                super(context, NAMA_DB, null, DB_VERSION);
                                }

                                @Override
                                public void onCreate(SQLiteDatabase db) {

                                                db.execSQL(CREATE_TABLE);
                                }

                                @Override
                                public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
                                                db.execSQL("DROP TABLE IF EXISTS " + NAMA_DB);
                                                onCreate(db);
                                }
                }

                public void close() {
                                dbHelper.close();
                }

                public void addRow(String nama, String hobi) {
                                ContentValues values = new ContentValues();
                                values.put(ROW_NAMA, nama);
                                values.put(ROW_HOBI, hobi);
                                try {
                                                db.insert(NAMA_TABEL, null, values);
                                } catch (Exception e) {
                                                Log.e("DB ERROR", e.toString());
                                                e.printStackTrace();
                                }
                }

                public ArrayList<ArrayList<Object>> ambilSemuaBaris() {
                                ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
                                Cursor cur;
                                try {
                                                cur = db.query(NAMA_TABEL, new String[] { ROW_ID, ROW_NAMA,
                                                                                ROW_HOBI }, null, null, null, null, null);
                                                cur.moveToFirst();
                                                if (!cur.isAfterLast()) {
                                                                do {
                                                                                ArrayList<Object> dataList = new ArrayList<Object>();
                                                                                dataList.add(cur.getLong(0));
                                                                                dataList.add(cur.getString(1));
                                                                                dataList.add(cur.getString(2));
                                                                                dataArray.add(dataList);
                                                                } while (cur.moveToNext());
                                                }
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("DEBE ERROR", e.toString());
                                                Toast.makeText(context, "gagal ambil semua baris:" + e.toString(),
                                                                                Toast.LENGTH_SHORT).show();
                                }
                                return dataArray;
                }

                public ArrayList<Object> ambilBaris(long rowId) {
                                ArrayList<Object> arrbaris = new ArrayList<Object>();
                                Cursor cursor;
                                try {
                                                cursor = db.query(NAMA_TABEL, new String[] { ROW_ID, ROW_NAMA,
                                                                                ROW_HOBI }, ROW_ID + "=" + rowId, null, null, null, null,
                                                                                null);
                                                cursor.moveToFirst();
                                                if (!cursor.isAfterLast()) {
                                                                do {
                                                                                arrbaris.add(cursor.getLong(0));
                                                                                arrbaris.add(cursor.getString(1));
                                                                                arrbaris.add(cursor.getString(2));
                                                                } while (cursor.moveToNext());
                                                                String r = String.valueOf(arrbaris);
                                                                Toast.makeText(context, "haha" + r, Toast.LENGTH_SHORT).show();
                                                }
                                                cursor.close();
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("error", e.toString());
                                                Toast.makeText(context, "hhii" + e.toString(), Toast.LENGTH_SHORT)
                                                                                .show();
                                }
                                return arrbaris;
                }

                public void updateBaris(long rowId, String nama, String hobi) {
                                ContentValues cv = new ContentValues();
                                cv.put(ROW_NAMA, nama);
                                cv.put(ROW_HOBI, hobi);
                                try {
                                                db.update(NAMA_TABEL, cv, ROW_ID + "=" + rowId, null);
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("Db Error", e.toString());
                                }
                }

                public void deleteBaris(long idBaris) {
                                try {
                                                db.delete(NAMA_TABEL, ROW_ID + "=" + idBaris, null);
                                } catch (Exception e) {
                                                e.printStackTrace();
                                                Log.e("Error", e.toString());
                                }
                }
}




5). Dan Run lah ,,taraaa lihat hasilnya akan seperti ini




 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best WordPress Themes