ตอนที่ 16 : Show Case 3 : Update Data (Android and Mobile Services) |
ตอนที่ 16 : Show Case 3 : Update Data (Android and Mobile Services) บทความการเขียน Android เพื่อทำการ Update หรือแก้ไขข้อมูลในตารางของ Mobile Services ที่อยู่บน Windows Azure โดยในตัวอย่างนี้จะออกแบบ Activity เป็น 2 Form ด้วยกัน คือ Activity แรกใช้ ListView แสดงรายการข้อมูลทั้งหมด ส่วน Activity ที่สองสำหรับแสดงข้อมูลที่ได้เลือก เพื่อทำการแสดงช่อง EditText ไว้สำหรับแก้ไขข้อมูล
Android Mobile Services Update Form
Android Mobile Service Update Form
สำหรับขั้นตอนนั้นก็คือสร้าง Activity แรกด้วย ListView จากนั้นดึงข้อมูลมาจาก Mobile Services และแต่ล่ะ Item สามารถที่จะเลือกรายการเพื่อ Update ด้วยการส่งค่า id ไปยัง Activity ที่สอง ใน Activity นี้จะมีหน้าที่ไปดึงพวกรายละเอียดต่าง ๆ มาแสดงใน EditText เพื่อรอทำการแก้ไข Update ข้อมูล
Example ตัวอย่างการทำระบบแก้ไข Update Data
ตอนนี้เรามี Mobile Service อยู่ 1 รายการ
ชื่อตารางว่า MyMember
มีข้อมูลอยู่ทั้งหมด 3 รายการ
กลับมายัง Android Project บน Eclipse
โครงสร้างไฟล์ทั้งหมด
ให้เพิ่ม UpdateActivity ลงในไฟล์ AndroidManifest.xml
<activity
android:name="UpdateActivity"
android:theme="@style/AppTheme"
android:screenOrientation="portrait"
android:label="@string/app_name" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
activity_column.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/col_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="id"/>
<TextView
android:id="@+id/col_username"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="name"/>
<TextView
android:id="@+id/col_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="email" />
</LinearLayout>
activity_update.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Update Form "
android:layout_span="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
<View
android:layout_height="1dip"
android:background="#CCCCCC" />
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:orientation="horizontal">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=" = " />
<TextView
android:id="@+id/txtID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=" = " />
<TextView
android:id="@+id/txtUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username" />
</TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/txtPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Name :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Email :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Tel :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/txtTel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10" >
</EditText>
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
</TableLayout >
</TableLayout>
MyMember.java
package com.example.thaicreate;
public class MyMember {
@com.google.gson.annotations.SerializedName("id")
private int mId;
@com.google.gson.annotations.SerializedName("username")
private String mUsername;
@com.google.gson.annotations.SerializedName("password")
private String mPassword;
@com.google.gson.annotations.SerializedName("name")
private String mName;
@com.google.gson.annotations.SerializedName("tel")
private String mTel;
@com.google.gson.annotations.SerializedName("email")
private String mEmail;
public MyMember() {
// empty
}
public MyMember(String username, String password,
String name,String tel,String email) {
this.setUsername(username);
this.setPassword(password);
this.setName(name);
this.setTel(tel);
this.setEmail(email);
}
public final void setId(int id) {
mId = id;
}
public int getId() {
return mId;
}
public final void setUsername(String username) {
mUsername = username;
}
public String getUsername() {
return mUsername;
}
public final void setPassword(String password) {
mPassword = password;
}
public String getPassword() {
return mPassword;
}
public final void setName(String name) {
mName = name;
}
public String getName() {
return mName;
}
public final void setTel(String tel) {
mTel = tel;
}
public String getTel() {
return mTel;
}
public final void setEmail(String email) {
mEmail = email;
}
public String getEmail() {
return mEmail;
}
}
MainActivity.java
package com.example.thaicreate;
import java.net.MalformedURLException;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;
public class MainActivity extends Activity {
private MobileServiceClient mClient;
private MobileServiceTable<MyMember> mMyMember;
private MyMemberAdapter mAdapter;
String[] Cmd = {"View","Update","Delete"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*** Create to Mobile Service ***/
try {
mClient = new MobileServiceClient(
"https://thaicreate.azure-mobile.net/",
"QUjngFknhHZjdaGgYAAzdoXkOzKoxi24",
this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*** Create getTable ***/
mMyMember = mClient.getTable(MyMember.class);
// listView1
final ListView lstView1 = (ListView)findViewById(R.id.listView1);
mAdapter = new MyMemberAdapter(this,R.layout.activity_column);
lstView1.setAdapter(mAdapter);
registerForContextMenu(lstView1);
refreshItemsFromTable();
}
private void refreshItemsFromTable() {
mMyMember.execute(new TableQueryCallback<MyMember>() {
public void onCompleted(List<MyMember> result, int count, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (MyMember item : result) {
mAdapter.add(item);
}
} else {
Log.d("Error","Error Load Data from Mobile Service");
}
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.btn_star_big_on);
menu.setHeaderTitle("Command");
String[] menuItems = Cmd;
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = Cmd;
String CmdName = menuItems[menuItemIndex];
// Check Event Command
if ("View".equals(CmdName)) {
Toast.makeText(MainActivity.this,"Your Selected View",Toast.LENGTH_LONG).show();
/**
* Call the method
*/
} else if ("Update".equals(CmdName)) {
int s_id = mAdapter.getItem(info.position).getId();
//String s_name = mAdapter.getItem(info.position).getId().toString();
//String s_username = mAdapter.getItem(info.position).getUsername().toString();
Toast.makeText(MainActivity.this,"Your Selected Update ",Toast.LENGTH_LONG).show();
Intent newActivity = new Intent(MainActivity.this,UpdateActivity.class);
newActivity.putExtra("sid", s_id);
startActivity(newActivity);
} else if ("Delete".equals(CmdName)) {
Toast.makeText(MainActivity.this,"Your Selected Delete",Toast.LENGTH_LONG).show();
/**
* Call the mthod
*/
}
return true;
}
public class MyMemberAdapter extends ArrayAdapter<MyMember> {
Context mContext;
int mLayoutResourceId;
public MyMemberAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final MyMember currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
// Column id
final TextView txt_id = (TextView) row.findViewById(R.id.col_id);
txt_id.setText(String.valueOf(currentItem.getId()));
// Column username
final TextView txt_name = (TextView) row.findViewById(R.id.col_username);
txt_name.setText(currentItem.getUsername());
// Column name
final TextView txt_email = (TextView) row.findViewById(R.id.col_name);
txt_email.setText(currentItem.getName());
return row;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
UpdateActivity.java
package com.example.thaicreate;
import java.net.MalformedURLException;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;
public class UpdateActivity extends Activity {
private MobileServiceClient mClient;
private MobileServiceTable<MyMember> mMyMember;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
/*** Create to Mobile Service ***/
try {
mClient = new MobileServiceClient(
"https://thaicreate.azure-mobile.net/",
"QUjngFknhHZjdaGgYAAzdoXkOzKoxi24",
this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*** Create getTable ***/
mMyMember = mClient.getTable(MyMember.class);
Intent intent= getIntent();
final int id = intent.getExtras().getInt("sid");
// Refresh Data
refreshItemsFromTable(id);
// btnSave
Button btnSave = (Button) findViewById(R.id.btnSave);
// Perform action on click
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(SaveData(id))
{
// When Save Complete
Intent newActivity = new Intent(UpdateActivity.this,MainActivity.class);
startActivity(newActivity);
}
}
});
// btnCancel
final Button btnCancel = (Button) findViewById(R.id.btnCancel);
// Perform action on click
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(UpdateActivity.this,MainActivity.class);
startActivity(newActivity);
}
});
}
public boolean SaveData(final int id)
{
//*** Update Record ***//
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
final EditText txtName = (EditText)findViewById(R.id.txtName);
final EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
final EditText txtTel = (EditText)findViewById(R.id.txtTel);
//** Select Record ***//
mMyMember.where().field("id").eq(id)
.execute(new TableQueryCallback<MyMember>() {
public void onCompleted(List<MyMember> result, int count, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
MyMember item = result.get(0);
/*** Update Item ***/
item.setPassword(txtPassword.getText().toString());
item.setName(txtName.getText().toString());
item.setEmail(txtEmail.getText().toString());
item.setTel(txtTel.getText().toString());
// Update Record ***/
mMyMember.update(item, new TableOperationCallback<MyMember>() {
public void onCompleted(MyMember entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Toast.makeText(UpdateActivity.this, "Update Data Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UpdateActivity.this, "Update Failed!", Toast.LENGTH_SHORT).show();
Log.d("Error : ",exception.getMessage());
}
}
});
} else {
Log.d("Error","Error Load Data from Mobile Service");
}
}
});
return true;
}
private void refreshItemsFromTable(final int id) {
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
if (mClient == null) {
AlertDialog ad = adb.create();
ad.setMessage("Cannot connect to Windows Azure Mobile Service!");
ad.show();
} else {
mMyMember.where().field("id").eq(id).execute(new TableQueryCallback<MyMember>() {
public void onCompleted(List<MyMember> result, int count, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
if(result.size() > 0)
{
String username = null;
String password = null;
String name = null;
String tel = null;
String email = null;
MyMember item = result.get(0);
username = item.getUsername();
password = item.getPassword();
name = item.getName();
email = item.getEmail();
tel = item.getTel();
final TextView tid = (TextView)findViewById(R.id.txtID);
final TextView tUsername = (TextView)findViewById(R.id.txtUsername);
final TextView tPassword = (TextView)findViewById(R.id.txtPassword);
final TextView tName = (TextView)findViewById(R.id.txtName);
final TextView tEmail = (TextView)findViewById(R.id.txtEmail);
final TextView tTel = (TextView)findViewById(R.id.txtTel);
tid.setText(String.valueOf(id));
tUsername.setText(username);
tPassword.setText(password);
tName.setText(name);
tEmail.setText(email);
tTel.setText(tel);
}
} else {
AlertDialog ad = adb.create();
ad.setMessage("Error : " + exception.getCause().getMessage());
ad.show();
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Screensot
แสดงรายการข้อมูลบร ListView
คลิกค้าง 1 วินาที เพื่อแสดง Context Menu ให้เราเลือก Update
แสดงรายการสำหรับ Update
ทดสอบแก้ไขข้อมูล
หลังจากที่แก้ไขข้อมูลเรียบร้อยแล้ว
เมื่อกลับไปดู DATA ที่ Mobile Services ข้อมูลก็จะถูกแก้ไข Update
บทความถัดไปที่แนะนำให้อ่าน
บทความที่เกี่ยวข้อง
|