CONTOH APLIKASI MENU EDIT DI ECLIPSE 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 klik Finish
9. Kemudain 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.UpdateActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.contoh.DetailUpdateActivity" android:label="@string/title_activity_insert" > </activity> </application> </manifest>
10. Kemudian ini adalah source code UpdateActivity.java
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.content.Intent; 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.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class UpdateActivity extends Activity implements OnItemClickListener{ private final String urlDisplay = "http://10.0.2.2/contoh/getUser.php"; //koneksi database ke localhost private UserAdapter adapter; private ListView listUser; private static UpdateActivity instance; public User selectedUser; public static UpdateActivity getInstance(){ if(instance == null){ instance = new UpdateActivity(); } return instance; } 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); listUser.setOnItemClickListener(this); } private void loadDataUser(){ try { String jsonString = DisplayActivity.getRequestFromServer(urlDisplay); JSONObject jObject = new JSONObject(jsonString); JSONArray newsJsonArray = jObject.getJSONArray("user"); 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 void onItemClick(AdapterView<?> adapterV, View view, int position, long id) { UpdateActivity.getInstance().selectedUser = adapter.getItem(position); startActivity(new Intent(this, DetailUpdateActivity.class)); finish(); } 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. Berikut source code untuk file DetailUpdateActivity.java
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 android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class DetailUpdateActivity extends Activity implements OnClickListener{ Button buttonUpdate; private EditText editPassword; private final String urlUpdate = "http://10.0.2.2/contoh/updateUser.php"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); TextView usernameUser = (TextView) findViewById(R.id.textViewUsername); usernameUser.setText(UpdateActivity.getInstance().selectedUser.username); TextView newPasswordUser = (TextView) findViewById(R.id.textViewNewPassword); buttonUpdate = (Button) findViewById(R.id.buttonUpdate); buttonUpdate.setOnClickListener(this); editPassword = (EditText) findViewById(R.id.editTextPassword); } public void onClick(View view) { if(view.equals(buttonUpdate)){ try { String url = DetailUpdateActivity.getRequestFromServer(urlUpdate+"?username="+UpdateActivity.getInstance().selectedUser.username+ "&password="+editPassword.getText().toString()); Toast.makeText(this, url, Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this, "Error: "+ e.getMessage(), Toast.LENGTH_LONG).show(); } } startActivity(new Intent(this, UpdateActivity.class)); finish(); } 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; } }
12. Perhatikan bagian "http://10.0.2.2/contoh/updateUser.php", bahwa file "updateUser.php" (query untuk mengubah data password) tersimpan pada folder "contoh" di htdocs. Berikut source code untuk file "updateUser.php".
<?php
$username = $_GET['username'];
$password = $_GET['password'];
include "connect_db.php";
$query = "update tbuser set password = '$password' where username ='".$username."' ";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo $result;
?>
13. Berikut soruce code untuk "activity_update.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: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/textViewNewPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Password" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dp" > <Button android:id="@+id/buttonUpdate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="UPDATE" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" > </LinearLayout> </LinearLayout> </LinearLayout>
14. Maka hasilnya seperti gambar di bawah ini
Sebelum di edit |
Ketika di edit |
Sesudah di edit |