CONTOH APLIKASI MENU DISPLAY DENGAN MYSQL
Assalamualaikum Wr.Wb
Pada kesempatan kali saya akan memebuat menu Display menggunakan MySQL atau bagaimana cara menampilkan data di eclipse menggunakan MySQL. Berikut ini adalah langkah langkahnya :
1. Buka Aplikasi Eclipse anda
Catatan : Bagi anda yang belum mempunyai software eclipse anda bisa mendownloadnya DISINI
2. Kemudian anda klik File -> New -> Android Application Project
3. Setelah di klik maka akan muncul form seperti di bawah ini
4. Setelah itu isi nama project yang anda ingin buat di kolom Application Name kemudian klik Next
5. Setelah itu anda ceklis pada kolom Create custom launcher icon , Create Activity , dan Create Project in Workspace seperti gambar di bawah ini
6. Setelah itu maka akan muncul form baru yang berisi Configure Launcher Icon kemudian anda klik Next
7. Setelah itu anda ceklik kolom Create Activity seperti gambar di bawah ini
8. Setelah itu maka akan mucul form seperti gambar di bawah ini kemudian klik Finish
9. Copy kan script AndroidManifest.xml di bawah ini
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contoh"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
//untuk koneksi internet
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.contoh.DisplayActivity"
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>
10. Kemudian Copy kan script DisplayActivity.java di bawah ini
package com.example.contoh;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DisplayActivity extends Activity{
private final String urlContoh = "http://10.0.2.2/contoh/getUser.php"; //koneksi database ke localhost
private UserAdapter adapter;
private ListView listUser;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
adapter = new UserAdapter(this, R.id.textView1);
loadDataUser();
listUser = (ListView) findViewById(R.id.listViewUser);
listUser.setAdapter(adapter);
}
private void loadDataUser(){
try {
String jsonString = DisplayActivity.getRequestFromServer(urlContoh);
Log.w("Load User", jsonString);
JSONObject jObject = new JSONObject(jsonString);
JSONArray newsJsonArray = jObject.getJSONArray("user");
Log.w("Load data User", "Size = "+newsJsonArray.length());
for (int i = 0; i < newsJsonArray.length(); i++) {
User user = new User(newsJsonArray.getJSONObject(i));
adapter.add(user);
}
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
class UserAdapter extends ArrayAdapter<User>{
public UserAdapter(Context context, int resource) {
super(context, resource);
}
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = ((LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_adapter, parent,false);
}
TextView usernameUser = (TextView) convertView.findViewById(R.id.textViewUsername);
TextView passwordUser = (TextView) convertView.findViewById(R.id.textViewPassword);
User entityUser = getItem(position);
usernameUser.setText(entityUser.username);
passwordUser.setText(entityUser.password);
return convertView;
}
}
public static String getRequestFromServer(String url){
try {
Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
.getContextClassLoader());
Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
.currentThread().getContextClassLoader());
Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
Thread.currentThread().getContextClassLoader());
Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);
Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
Method buildMethod = threadPolicyBuilderClass.getMethod("build");
Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();
Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);
obj = penaltyMethod.invoke(obj);
Object threadPolicyObject = buildMethod.invoke(obj);
setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);
} catch (Exception ex) {
Log.w("Thread Policy", ex);
}
String result = "Succeed";
HttpClient client = new DefaultHttpClient();
HttpClientParams.setRedirecting(client.getParams(), true);
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
int lineCount = 0;
while((line = reader.readLine()) != null){
if(lineCount>0) str.append("\n");
str.append(line);
}
in.close();
result = str.toString();
Log.w("get Request", "asli : "+result);
if(result.indexOf("<") > 0){
result = result.substring(0, result.indexOf("<"));
}
Log.w("get Request", "proses : "+Html.fromHtml(result));
return Html.fromHtml(result).toString();
}catch(Exception ex){
ex.printStackTrace();
result = "Error";
}
return result;
}
}
11. Perhatikan bagian "http://10.0.2.2/contoh/getUser.php", bahwa file "getUser.php" (query untuk mengambil data username dan password) tersimpan pada folder "contoh" di htdocs. Berikut source code untuk file "getUser.php".
<?php
include "connect_db.php";
$query = "SELECT username,password FROM tbuser";
$result = mysql_query($query, $link) or die('Errorquery: '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{user:".json_encode($rows)."}";
echo $data;
?>
12. Perhatikan bagian include "connect_db.php", bahwa source code untuk koneksi ke root dari localhost terdapat pada file "connect_db.php".
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('dbcontoh') or die('Cannot select the DB');
?>
13. Berikut soruce code untuk "activity_display.xml" yang tersimpan pada folder "layout" dari struktur direktori android <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<ListView
android:id="@+id/listViewUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="5dp" >
</ListView>
</LinearLayout>
</LinearLayout>
14. Pada "activity_display.xml" di atas, hanya menyediakan widget <ListView untuk menampilkan data username dan password hasil query "getUser.php". Sedangkan format tampilan untuk data username dan password tersebut dilakukan oleh "activity_adapter.xml". Pertama data diperoleh melalui fungsi loadDataUser() pada "DisplayActivity.java". Fungsi loadDataUser() ini memanggil class "User.java" melalui sintax User user = new User(newsJsonArray.getJSONObject(i)) dalam format JSON. Berikut source code untuk file "User.java".
package com.example.contoh;
import org.json.JSONException;
import org.json.JSONObject;
public class User {
public String username;
public String password;
public User(JSONObject json){
super();
try {
this.username = json.getString("username");
this.password = json.getString("password");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
15. Kemudian yang terakhir ini adalah source code untuk activity_adapter.xml.<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Username" />
</LinearLayout>
<TextView
android:id="@+id/textViewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password" />
</LinearLayout>
16. Maka hasilnya akan seperti gambar di bawah ini
Selamat mencoba ... (^_^)
幸運を... (^_^)
EmoticonEmoticon