Buat activity_update.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/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>
Buat 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;
?>
Buat UpdateActivity.java
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;
}
}
Buat DetailUpdateActivity.java
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;
}
}
Senin, 23 Maret 2015
Minggu, 22 Maret 2015
Materi Pertemuan 6 (MySQL-Delete)
Buat class User.java
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();
}
}
}
Buat class DisplayActivity.java
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;
}
}
Buat activity_display.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: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>
Buat 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>
Buat 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;
?>
Buat class DeleteActivity.java
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;
import android.widget.Toast;
public class DeleteActivity extends Activity implements OnItemClickListener{
private final String urlDisplay = "http://10.0.2.2/contoh/getUser.php"; //koneksi database ke localhost
private final String urlDelete = "http://10.0.2.2/contoh/deleteUser.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);
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) {
try { String url = DeleteActivity.getRequestFromServer(urlDelete+"?username="+adapter.getItem(position).username);
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, DeleteActivity.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;
}
}
Buat file deleteUser.php
<?php
$username = $_GET['username'];
include "connect_db.php";
$query = "delete from tbuser where username ='".$username."'";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo $result;
?>
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();
}
}
}
Buat class DisplayActivity.java
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;
}
}
Buat activity_display.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: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>
Buat 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>
Buat 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;
?>
Buat class DeleteActivity.java
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;
import android.widget.Toast;
public class DeleteActivity extends Activity implements OnItemClickListener{
private final String urlDisplay = "http://10.0.2.2/contoh/getUser.php"; //koneksi database ke localhost
private final String urlDelete = "http://10.0.2.2/contoh/deleteUser.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);
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) {
try { String url = DeleteActivity.getRequestFromServer(urlDelete+"?username="+adapter.getItem(position).username);
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, DeleteActivity.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;
}
}
Buat file deleteUser.php
<?php
$username = $_GET['username'];
include "connect_db.php";
$query = "delete from tbuser where username ='".$username."'";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo $result;
?>
Selasa, 10 Maret 2015
Materi Pertemuan 5 (MySQL-Insert)
Berikut Xml
<LinearLayout 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:gravity="center_horizontal"
android:orientation="vertical"
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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username" />
<EditText
android:id="@+id/editTextUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
<Button
android:id="@+id/buttonSignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SIGN UP" />
</LinearLayout>
Berikut Java
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.Toast;
public class InsertActivity extends Activity {
private EditText editUserName;
private EditText editPassword;
private Button buttonSignup;
public static final String urlContoh = "http://10.0.2.2/contoh/setUser.php"; //koneksi database ke localhost
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
editUserName = (EditText) findViewById(R.id.editTextUserName);
editPassword = (EditText) findViewById(R.id.editTextPassword);
buttonSignup = (Button) findViewById(R.id.buttonSignup);
buttonSignup.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try {
String result = InsertActivity.getRequestFromServer(urlContoh+"?username="+editUserName.getText().toString()+"&password="+editPassword.getText().toString());
Toast.makeText(InsertActivity.this, result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InsertActivity.this, "Error: "+ e.getMessage(), Toast.LENGTH_LONG).show();
}
Intent myIntent = new Intent(view.getContext(),InsertActivity.class);
startActivity(myIntent);
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;
}
}
Berikut Php
<?php
$username = $_GET['username'];
$password = $_GET['password'];
include "connect_db.php";
$query = "insert into tbuser (username,password) values('".$username."','".$password."')";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo $result;
?>
Dari code php di atas, ada pemanggilan fungsi "connect_db.php". Berikut source code-nya.
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('dbcontoh') or die('Cannot select the DB');
?>
<LinearLayout 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:gravity="center_horizontal"
android:orientation="vertical"
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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username" />
<EditText
android:id="@+id/editTextUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
<Button
android:id="@+id/buttonSignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SIGN UP" />
</LinearLayout>
Berikut Java
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.Toast;
public class InsertActivity extends Activity {
private EditText editUserName;
private EditText editPassword;
private Button buttonSignup;
public static final String urlContoh = "http://10.0.2.2/contoh/setUser.php"; //koneksi database ke localhost
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
editUserName = (EditText) findViewById(R.id.editTextUserName);
editPassword = (EditText) findViewById(R.id.editTextPassword);
buttonSignup = (Button) findViewById(R.id.buttonSignup);
buttonSignup.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try {
String result = InsertActivity.getRequestFromServer(urlContoh+"?username="+editUserName.getText().toString()+"&password="+editPassword.getText().toString());
Toast.makeText(InsertActivity.this, result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InsertActivity.this, "Error: "+ e.getMessage(), Toast.LENGTH_LONG).show();
}
Intent myIntent = new Intent(view.getContext(),InsertActivity.class);
startActivity(myIntent);
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;
}
}
Berikut Php
<?php
$username = $_GET['username'];
$password = $_GET['password'];
include "connect_db.php";
$query = "insert into tbuser (username,password) values('".$username."','".$password."')";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo $result;
?>
Dari code php di atas, ada pemanggilan fungsi "connect_db.php". Berikut source code-nya.
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('dbcontoh') or die('Cannot select the DB');
?>
Selasa, 03 Maret 2015
Materi Pertemuan 4 (SQLite)
Buat database
package com.example.terjemah;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbterjemah";
public static final String INGGRIS= "inggris";
public static final String INDONESIA = "indonesia";
public static final String JERMAN = "JERMAN";
//Constructor DataKamus untuk initiate database
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "inggris TEXT, indonesia TEXT, jerman TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(INDONESIA, "lari");
cv.put(JERMAN, "laufen");
db.insert("kamus", INGGRIS, cv);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
Buat layout untuk menampilkan terjemahan
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Kamus Inggris Indonesia Jerman" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inggris :" >
</TextView>
<EditText
android:id="@+id/txtInggris"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
<requestFocus>
</requestFocus>
</EditText>
<Button
android:id="@+id/btnTerjemah"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getTerjemahan"
android:text="Terjemahkan" >
</Button>
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Indonesia :" >
</TextView>
<EditText
android:id="@+id/txtIndonesia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:text="" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jerman" >
</TextView>
<EditText
android:id="@+id/txtJerman"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
</LinearLayout>
Buat class untuk panggil layout terjemah
package com.example.terjemah;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtIndonesia;
private EditText txtJerman;
private DatabaseHelper datakamus = null;
public static final String INGGRIS = "inggris";
public static final String INDONESIA = "indonesia";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DatabaseHelper(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtIndonesia = (EditText) findViewById(R.id.txtIndonesia);
txtJerman = (EditText) findViewById(R.id.txtJerman);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN "
+ "FROM kamus where INGGRIS='" + englishword
+ "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtIndonesia.setText(bhsindonesia);
txtJerman.setText(bhsjerman);
}
@Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Buat layout untuk input baru data terjemah
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text = "Kamus Inggris Indonesia Jerman" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Inggris :" >
</TextView>
<EditText
android:id="@+id/txtInggris"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Indonesia :" >
</TextView>
<EditText
android:id="@+id/txtIndonesia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Jerman" >
</TextView>
<EditText
android:id="@+id/txtJerman"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
<Button
android:id="@+id/btnTerjemah"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="saveData"
android:text = "Save Data" >
</Button>
</LinearLayout>
Buat class untuk panggil layout input data
package com.example.terjemah;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class TambahActivity extends Activity {
private SQLiteDatabase db = null;
private EditText txtInggris;
private EditText txtIndonesia;
private EditText txtJerman;
private DatabaseHelper datakamus = null;
public static final String INGGRIS= "inggris";
public static final String INDONESIA = "indonesia";
public static final String JERMAN = "JERMAN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah);
datakamus = new DatabaseHelper(this);
db = datakamus.getWritableDatabase();
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtIndonesia = (EditText) findViewById(R.id.txtIndonesia);
txtJerman = (EditText) findViewById(R.id.txtJerman);
}
public void saveData(View view) {
String bhsindonesia = txtIndonesia.getText().toString();;
String bhsjerman= txtJerman.getText().toString();
String englishword = txtInggris.getText().toString();
ContentValues cv=new ContentValues();
cv.put(INGGRIS, englishword);
cv.put(INDONESIA, bhsindonesia);
cv.put(JERMAN, bhsjerman);
if (db.insert("kamus", INGGRIS, cv)>0){
Toast.makeText(getBaseContext(), "Save Data Success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "Save Data Fail", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
super.onDestroy();
db.close();
}
}
JANGAN LUPA UNTUK MENGATUR CLASS MANA (MainActivity.java atau TambahActivity.java) YANG AKAN DI-RUNNING. ATUR CLASS TERSEBUT PADA FILE AndroidManifest.xml.
package com.example.terjemah;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbterjemah";
public static final String INGGRIS= "inggris";
public static final String INDONESIA = "indonesia";
public static final String JERMAN = "JERMAN";
//Constructor DataKamus untuk initiate database
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "inggris TEXT, indonesia TEXT, jerman TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(INDONESIA, "lari");
cv.put(JERMAN, "laufen");
db.insert("kamus", INGGRIS, cv);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
Buat layout untuk menampilkan terjemahan
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Kamus Inggris Indonesia Jerman" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inggris :" >
</TextView>
<EditText
android:id="@+id/txtInggris"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
<requestFocus>
</requestFocus>
</EditText>
<Button
android:id="@+id/btnTerjemah"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getTerjemahan"
android:text="Terjemahkan" >
</Button>
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Indonesia :" >
</TextView>
<EditText
android:id="@+id/txtIndonesia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:text="" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jerman" >
</TextView>
<EditText
android:id="@+id/txtJerman"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
</LinearLayout>
Buat class untuk panggil layout terjemah
package com.example.terjemah;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtIndonesia;
private EditText txtJerman;
private DatabaseHelper datakamus = null;
public static final String INGGRIS = "inggris";
public static final String INDONESIA = "indonesia";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DatabaseHelper(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtIndonesia = (EditText) findViewById(R.id.txtIndonesia);
txtJerman = (EditText) findViewById(R.id.txtJerman);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN "
+ "FROM kamus where INGGRIS='" + englishword
+ "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtIndonesia.setText(bhsindonesia);
txtJerman.setText(bhsjerman);
}
@Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Buat layout untuk input baru data terjemah
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text = "Kamus Inggris Indonesia Jerman" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Inggris :" >
</TextView>
<EditText
android:id="@+id/txtInggris"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Indonesia :" >
</TextView>
<EditText
android:id="@+id/txtIndonesia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Jerman" >
</TextView>
<EditText
android:id="@+id/txtJerman"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</EditText>
<Button
android:id="@+id/btnTerjemah"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="saveData"
android:text = "Save Data" >
</Button>
</LinearLayout>
Buat class untuk panggil layout input data
package com.example.terjemah;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class TambahActivity extends Activity {
private SQLiteDatabase db = null;
private EditText txtInggris;
private EditText txtIndonesia;
private EditText txtJerman;
private DatabaseHelper datakamus = null;
public static final String INGGRIS= "inggris";
public static final String INDONESIA = "indonesia";
public static final String JERMAN = "JERMAN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah);
datakamus = new DatabaseHelper(this);
db = datakamus.getWritableDatabase();
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtIndonesia = (EditText) findViewById(R.id.txtIndonesia);
txtJerman = (EditText) findViewById(R.id.txtJerman);
}
public void saveData(View view) {
String bhsindonesia = txtIndonesia.getText().toString();;
String bhsjerman= txtJerman.getText().toString();
String englishword = txtInggris.getText().toString();
ContentValues cv=new ContentValues();
cv.put(INGGRIS, englishword);
cv.put(INDONESIA, bhsindonesia);
cv.put(JERMAN, bhsjerman);
if (db.insert("kamus", INGGRIS, cv)>0){
Toast.makeText(getBaseContext(), "Save Data Success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "Save Data Fail", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
super.onDestroy();
db.close();
}
}
JANGAN LUPA UNTUK MENGATUR CLASS MANA (MainActivity.java atau TambahActivity.java) YANG AKAN DI-RUNNING. ATUR CLASS TERSEBUT PADA FILE AndroidManifest.xml.
Minggu, 01 Maret 2015
Materi Pertemuan 3 (SQLite-libs)
Buat Layoutnya
<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"
tools:context=".MainActivity" >
<EditText
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..." />
<ListView
android:id="@+id/lv_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/search" >
</ListView>
<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lv_data"
android:text="Data yang Anda cari tidak ada" />
</RelativeLayout>
Buat Program Javanya
package com.example.contohistilaharti;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements TextWatcher, OnItemClickListener {
private EditText search;
private ListView lv;
private DatabaseHelper dbHelper;
private ArrayAdapter<Kamus> adapter;
private List<Kamus> listKamus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv_data);
lv.setEmptyView(findViewById(R.id.empty));
search = (EditText) findViewById(R.id.search);
dbHelper = DatabaseHelper.getInstance(this);
setData();
search.addTextChangedListener(this);
lv.setOnItemClickListener(this);
}
private void setData() {
listKamus = dbHelper.getAllKamus();
adapter = new ArrayAdapter<Kamus>(this,
android.R.layout.simple_expandable_list_item_1, listKamus);
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("istilah", adapter.getItem(position).getIstilah());
b.putString("arti", adapter.getItem(position).getArti());
Intent i = new Intent(this, ArtiActivity.class);
i.putExtras(b);
startActivity(i);
finish();
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(s.toString());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_settings:
Intent startActivityDictionary = new Intent(this, MainActivity.class);
startActivity(startActivityDictionary);
return true;
case R.id.action_about:
Intent startActivityAbout = new Intent(this, AboutActivity.class);
startActivity(startActivityAbout);
return true;
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Berikut Layout Untuk Menampilkan Istilahnya
<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=".ArtiActivity" >
<TextView
android:id="@+id/istilah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Istilah" />
<TextView
android:id="@+id/garis"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@id/istilah"
android:background="#000" />
<TextView
android:id="@+id/arti"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/garis"
android:text="Arti" />
</RelativeLayout>
Nah, ini Program Java Untuk Menemukan Istilahnya
package com.example.contohistilaharti;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class ArtiActivity extends Activity {
private TextView txtArti, txtIstilah;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arti);
Bundle b = getIntent().getExtras();
txtIstilah = (TextView) findViewById(R.id.istilah);
txtArti = (TextView) findViewById(R.id.arti);
txtIstilah.setText(b.getString("istilah"));
txtArti.setText(b.getString("arti"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.arti, menu);
return true;
}
}
Ingat! Program Istilah-Arti ini butuh class untuk memanggil data di database. Kita butuh dua class, yaitu class untuk deklarasi database, "DatabaseHelper.java"
package com.example.contohistilaharti;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "db_kamus2";
private static final int DB_VER = 1;
private static final String TB_DATA = "tb_kamus";
public static final String COL_ID = "_id";
public static final String COL_ISTILAH = "istilah";
public static final String COL_ARTI = "arti";
private static DatabaseHelper dbInstance;
private static SQLiteDatabase db;
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
public static DatabaseHelper getInstance(Context context) {
if (dbInstance == null) {
dbInstance = new DatabaseHelper(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
@Override
public synchronized void close() {
super.close();
if (dbInstance != null) {
dbInstance.close();
}
}
public List<Kamus> getAllKamus() {
List<Kamus> lisKamus = new ArrayList<Kamus>();
Cursor cursor = db.query(TB_DATA, new String[] { COL_ID, COL_ID,
COL_ARTI, COL_ISTILAH }, null, null, null, null, COL_ISTILAH);
if (cursor.getCount() >= 1) {
cursor.moveToFirst();
do {
Kamus kamus = new Kamus();
kamus.setArti(cursor.getString(cursor
.getColumnIndexOrThrow(COL_ARTI)));
kamus.setIstilah(cursor.getString(cursor
.getColumnIndexOrThrow(COL_ISTILAH)));
lisKamus.add(kamus);
} while (cursor.moveToNext());
}
return lisKamus;
}
}
Dan class untuk menangani operasi set-get datanya, "Kamus.java"
package com.example.contohistilaharti;
public class Kamus {
private String istilah;
private String arti;
public String getIstilah() {
return istilah;
}
public void setIstilah(String istilah) {
this.istilah = istilah;
}
public String getArti() {
return arti;
}
public void setArti(String arti) {
this.arti = arti;
}
@Override
public String toString() {
return this.istilah;
}
}
fileDb
fileAssetHelper
<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"
tools:context=".MainActivity" >
<EditText
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..." />
<ListView
android:id="@+id/lv_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/search" >
</ListView>
<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lv_data"
android:text="Data yang Anda cari tidak ada" />
</RelativeLayout>
Buat Program Javanya
package com.example.contohistilaharti;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements TextWatcher, OnItemClickListener {
private EditText search;
private ListView lv;
private DatabaseHelper dbHelper;
private ArrayAdapter<Kamus> adapter;
private List<Kamus> listKamus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv_data);
lv.setEmptyView(findViewById(R.id.empty));
search = (EditText) findViewById(R.id.search);
dbHelper = DatabaseHelper.getInstance(this);
setData();
search.addTextChangedListener(this);
lv.setOnItemClickListener(this);
}
private void setData() {
listKamus = dbHelper.getAllKamus();
adapter = new ArrayAdapter<Kamus>(this,
android.R.layout.simple_expandable_list_item_1, listKamus);
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("istilah", adapter.getItem(position).getIstilah());
b.putString("arti", adapter.getItem(position).getArti());
Intent i = new Intent(this, ArtiActivity.class);
i.putExtras(b);
startActivity(i);
finish();
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(s.toString());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_settings:
Intent startActivityDictionary = new Intent(this, MainActivity.class);
startActivity(startActivityDictionary);
return true;
case R.id.action_about:
Intent startActivityAbout = new Intent(this, AboutActivity.class);
startActivity(startActivityAbout);
return true;
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Berikut Layout Untuk Menampilkan Istilahnya
<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=".ArtiActivity" >
<TextView
android:id="@+id/istilah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Istilah" />
<TextView
android:id="@+id/garis"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@id/istilah"
android:background="#000" />
<TextView
android:id="@+id/arti"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/garis"
android:text="Arti" />
</RelativeLayout>
Nah, ini Program Java Untuk Menemukan Istilahnya
package com.example.contohistilaharti;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class ArtiActivity extends Activity {
private TextView txtArti, txtIstilah;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arti);
Bundle b = getIntent().getExtras();
txtIstilah = (TextView) findViewById(R.id.istilah);
txtArti = (TextView) findViewById(R.id.arti);
txtIstilah.setText(b.getString("istilah"));
txtArti.setText(b.getString("arti"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.arti, menu);
return true;
}
}
Ingat! Program Istilah-Arti ini butuh class untuk memanggil data di database. Kita butuh dua class, yaitu class untuk deklarasi database, "DatabaseHelper.java"
package com.example.contohistilaharti;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DatabaseHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "db_kamus2";
private static final int DB_VER = 1;
private static final String TB_DATA = "tb_kamus";
public static final String COL_ID = "_id";
public static final String COL_ISTILAH = "istilah";
public static final String COL_ARTI = "arti";
private static DatabaseHelper dbInstance;
private static SQLiteDatabase db;
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
public static DatabaseHelper getInstance(Context context) {
if (dbInstance == null) {
dbInstance = new DatabaseHelper(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
@Override
public synchronized void close() {
super.close();
if (dbInstance != null) {
dbInstance.close();
}
}
public List<Kamus> getAllKamus() {
List<Kamus> lisKamus = new ArrayList<Kamus>();
Cursor cursor = db.query(TB_DATA, new String[] { COL_ID, COL_ID,
COL_ARTI, COL_ISTILAH }, null, null, null, null, COL_ISTILAH);
if (cursor.getCount() >= 1) {
cursor.moveToFirst();
do {
Kamus kamus = new Kamus();
kamus.setArti(cursor.getString(cursor
.getColumnIndexOrThrow(COL_ARTI)));
kamus.setIstilah(cursor.getString(cursor
.getColumnIndexOrThrow(COL_ISTILAH)));
lisKamus.add(kamus);
} while (cursor.moveToNext());
}
return lisKamus;
}
}
Dan class untuk menangani operasi set-get datanya, "Kamus.java"
package com.example.contohistilaharti;
public class Kamus {
private String istilah;
private String arti;
public String getIstilah() {
return istilah;
}
public void setIstilah(String istilah) {
this.istilah = istilah;
}
public String getArti() {
return arti;
}
public void setArti(String arti) {
this.arti = arti;
}
@Override
public String toString() {
return this.istilah;
}
}
fileDb
fileAssetHelper
Langganan:
Komentar (Atom)