Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone


Android Update Data to Server via Web Service

Android Update Data to Server via Web Service การเขียน Android เพื่อแก้ไข Update ข้อมูลที่อยู่บน Server Database ผ่าน Web Service ที่ทำงานร่วมกับ PHP กับ MySQL หลักการก็คือ ออกแบบ Web Service ไว้ 3 ตัวคือ

- getMember.php ว้สำหรับแสดงรายการข้อมูลทั้งหมดลงใน ListView ของ Android
- resultByMemberID.php ใช้สำหรับแสดงข้อมูลที่ได้เลือกทำการ Update
- updateMemberData.php ใช้สำหรับ Update ข้อมูลที่ถูกแก้ไขและส่งมาจาก Android


Android Update Data Server via Web Service


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

ในการเขียน Android เพื่อติดต่อกับ Internet จะต้องกำหนด Permission ในส่วนนี้ด้วยทุกครั้ง

Web Service

member
01.CREATE TABLE `member` (
02.  `MemberID` int(2) NOT NULL auto_increment,
03.  `Username` varchar(50) NOT NULL,
04.  `Password` varchar(50) NOT NULL,
05.  `Name` varchar(50) NOT NULL,
06.  `Tel` varchar(50) NOT NULL,
07.  `Email` varchar(150) NOT NULL,
08.  PRIMARY KEY  (`MemberID`),
09.  UNIQUE KEY `Username` (`Username`),
10.  UNIQUE KEY `Email` (`Email`)
11.) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
12. 
13.--
14.-- Dumping data for table `member`
15.--
16. 
17.INSERT INTO `member` VALUES (1, 'weerachai', 'weerachai@1', 'Weerachai Nukitram', '0819876107', 'weerachai@thaicreate.com');
18.INSERT INTO `member` VALUES (2, 'adisorn', 'adisorn@2', 'Adisorn Bunsong', '021978032', 'adisorn@thaicreate.com');
19.INSERT INTO `member` VALUES (3, 'surachai', 'surachai@3', 'Surachai Sirisart', '0876543210', 'surachai@thaicreate.com');


Android Update Data Server via Web Service

getMember.php
01.<?
02.ob_start();
03.        require_once("lib/nusoap.php");
04.          
05.        //Create a new soap server
06.        $server = new soap_server();
07.          
08.        //Define our namespace
09.        $namespace = "https://www.thaicreate.com/android/getMember.php";
10.        $server->wsdl->schemaTargetNamespace = $namespace;
11.          
12.        //Configure our WSDL
13.        $server->configureWSDL("resultMember");
14.          
15.        // Register our method and argument parameters
16.        $varname = array(
17.                   'strName' => "xsd:string"
18.        );
19.        $server->register('resultMember',$varname, array('return' => 'xsd:string'));
20.          
21.        function resultMember($strName)
22.        {
23.                $objConnect = mysql_connect("localhost","root","root");
24.                $objDB = mysql_select_db("mydatabase");
25. 
26.                $strSQL = "SELECT * FROM member WHERE 1 AND Name LIKE '%".$strName."%' ";
27.                $objQuery = mysql_query($strSQL);
28.                $intNumField = mysql_num_fields($objQuery);
29.                $resultArray = array();
30.                while($obResult = mysql_fetch_array($objQuery))
31.                {
32.                    $arrCol = array();
33.                    for($i=0;$i<$intNumField;$i++)
34.                    {
35.                        $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
36.                    }
37.                    array_push($resultArray,$arrCol);
38.                }
39. 
40.                mysql_close($objConnect);
41. 
42.                header('Content-type: application/json');
43.                return json_encode($resultArray);
44.        }
45.          
46.        // Get our posted data if the service is being consumed
47.        // otherwise leave this data blank.
48.        $POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
49.          
50.        // pass our posted data (or nothing) to the soap service
51.        $server->service($POST_DATA);
52.        exit();
53.?>


resultByMemberID.php
01.<?
02.ob_start();
03.        require_once("lib/nusoap.php");
04.          
05.        //Create a new soap server
06.        $server = new soap_server();
07.          
08.        //Define our namespace
10.        $server->wsdl->schemaTargetNamespace = $namespace;
11.          
12.        //Configure our WSDL
13.        $server->configureWSDL("resultMember");
14.          
15.        // Register our method and argument parameters
16.        $varname = array(
17.                   'strMemberID' => "xsd:string"
18.        );
19.        $server->register('resultMember',$varname, array('return' => 'xsd:string'));
20.          
21.        function resultMember($strMemberID)
22.        {
23. 
24.                $objConnect = mysql_connect("localhost","root","root");
25.                $objDB = mysql_select_db("mydatabase");
26. 
27.                $strSQL = "SELECT * FROM member WHERE 1
28.                    AND MemberID = '".$strMemberID."'
29.                    ";
30.                $objQuery = mysql_query($strSQL);
31.                $obResult = mysql_fetch_array($objQuery);
32.                if($obResult)
33.                {
34.                    $arr["MemberID"] = $obResult["MemberID"];
35.                    $arr["Username"] = $obResult["Username"];
36.                    $arr["Password"] = $obResult["Password"];
37.                    $arr["Name"] = $obResult["Name"];
38.                    $arr["Email"] = $obResult["Email"];
39.                    $arr["Tel"] = $obResult["Tel"];
40.                }
41. 
42.                mysql_close($objConnect);
43. 
44.                header('Content-type: application/json');
45.                return json_encode($arr);
46.        }
47.          
48.        // Get our posted data if the service is being consumed
49.        // otherwise leave this data blank.
50.        $POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
51.          
52.        // pass our posted data (or nothing) to the soap service
53.        $server->service($POST_DATA);
54.        exit();
55.?>


updateMemberData.php
01.<?
02.ob_start();
03.        require_once("lib/nusoap.php");
04.          
05.        //Create a new soap server
06.        $server = new soap_server();
07.          
08.        //Define our namespace
10.        $server->wsdl->schemaTargetNamespace = $namespace;
11.          
12.        //Configure our WSDL
13.        $server->configureWSDL("updateMember");
14.          
15.        // Register our method and argument parameters
16.        $varname = array(
17.                   'strMemberID' => "xsd:string",
18.                   'strPassword' => "xsd:string",
19.                   'strName' => "xsd:string",
20.                   'strEmail' => "xsd:string",
21.                   'strTel' => "xsd:string"
22.        );
23.        $server->register('updateMember',$varname, array('return' => 'xsd:string'));
24.          
25.        function updateMember($strMemberID,$strPassword,$strName,$strEmail,$strTel)
26.        {
27.                $objConnect = mysql_connect("localhost","root","root");
28.                $objDB = mysql_select_db("mydatabase");
29. 
30.                /*** Check Email Exists ***/
31.                $strSQL = "SELECT * FROM member WHERE Email = '".$strEmail."' AND MemberID != '".$strMemberID."' ";
32.                $objQuery = mysql_query($strSQL);
33.                $objResult = mysql_fetch_array($objQuery);
34.                if($objResult)
35.                {
36.                    $arr['StatusID'] = "0";
37.                    $arr['Error'] = "Email Exists!";   
38. 
39.                    header('Content-type: application/json');
40.                    mysql_close($objConnect);
41. 
42.                    return json_encode($arr);
43.                }
44. 
45.                /*** Update ***/
46.                $strSQL = " UPDATE member SET
47.                    Password = '".$strPassword."'
48.                    ,Name = '".$strName."'
49.                    ,Email = '".$strEmail."'
50.                    ,Tel = '".$strTel."'
51.                    WHERE MemberID = '".$strMemberID."'
52.                ";
53. 
54.                $objQuery = mysql_query($strSQL);
55.                if(!$objQuery)
56.                {
57.                    $arr['StatusID'] = "0";
58.                    $arr['Error'] = "Cannot save data!";   
59.                }
60.                else
61.                {
62.                    $arr['StatusID'] = "1";
63.                    $arr['Error'] = "";
64.                }
65. 
66.                /**
67.                    $arr['StatusID'] // (0=Failed , 1=Complete)
68.                    $arr['Error'] // Error Message
69.                */
70. 
71.                header('Content-type: application/json');
72.                mysql_close($objConnect);
73.                 
74.                return json_encode($arr);
75.        }
76.          
77.        // Get our posted data if the service is being consumed
78.        // otherwise leave this data blank.
79.        $POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
80.          
81.        // pass our posted data (or nothing) to the soap service
82.        $server->service($POST_DATA);
83.        exit();
84.?>


Android Proejct

โครงสร้างของไฟล์ประกอบด้วย 5 ไฟล์คือ MainActivity.java, activity_main.xml, activity_column.xml และ UpdateActivity.java, activity_update.xml

Android Update Data Server via Web Service

activity_main.xml
01.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/tableLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent" >
05.  
06.    <TableRow
07.      android:id="@+id/tableRow1"
08.      android:layout_width="wrap_content"
09.      android:layout_height="wrap_content" >
10.      
11.     <TextView
12.        android:id="@+id/textView1"
13.        android:layout_width="wrap_content"
14.        android:layout_height="wrap_content"
15.        android:gravity="center"
16.        android:text="Update Member : "
17.        android:layout_span="1"
18.        android:textAppearance="?android:attr/textAppearanceMedium" />
19. 
20.     <EditText
21.         android:id="@+id/txtKeySearch"
22.         android:layout_width="wrap_content"
23.         android:layout_height="wrap_content"
24.         android:ems="4" >
25.     </EditText>
26. 
27.     <Button
28.         android:id="@+id/btnSearch"
29.         android:layout_width="wrap_content"
30.         android:layout_height="wrap_content"
31.         android:text="Search" />
32.             
33.    </TableRow>
34. 
35.    <View
36.        android:layout_height="1dip"
37.        android:background="#CCCCCC" />
38.  
39.  <LinearLayout
40.        android:orientation="horizontal"
41.        android:layout_width="fill_parent"
42.        android:layout_height="wrap_content"
43.        android:layout_weight="0.1">  
44.      
45.     <ListView
46.         android:id="@+id/listView1"
47.         android:layout_width="match_parent"
48.         android:layout_height="wrap_content">
49.     </ListView>
50.             
51.    </LinearLayout>
52. 
53.    <View
54.        android:layout_height="1dip"
55.        android:background="#CCCCCC" />
56.           
57.    <LinearLayout
58.      android:id="@+id/LinearLayout1"
59.      android:layout_width="wrap_content"
60.      android:layout_height="wrap_content"
61.      android:padding="5dip" >
62. 
63.        <TextView
64.            android:id="@+id/textView2"
65.            android:layout_width="wrap_content"
66.            android:layout_height="wrap_content"
67.            android:text="By.. ThaiCreate.Com" />
68. 
69.    </LinearLayout>
70.     
71.</TableLayout>


activity_column.xml
01.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/linearLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent" >
05.     
06.    <TextView
07.    android:id="@+id/ColMemberID"
08.        android:layout_width="0dp"
09.        android:layout_height="wrap_content"
10.        android:layout_weight="0.2"
11.        android:text="MemberID"
12.        android:textAppearance="?android:attr/textAppearanceSmall" />
13. 
14.    <TextView
15.        android:id="@+id/ColName"
16.        android:layout_width="0dp"
17.        android:layout_height="wrap_content"
18.        android:layout_weight="1.0"
19.        android:text="Name"
20.        android:textAppearance="?android:attr/textAppearanceSmall" />
21. 
22.    <TextView
23.        android:id="@+id/ColTel"
24.        android:layout_width="0dp"
25.        android:layout_height="wrap_content"
26.        android:layout_weight="1"
27.        android:text="Tel"
28.        android:textAppearance="?android:attr/textAppearanceSmall" />
29. 
30.</LinearLayout>



Android Update Data Server via Web Service

activity_update.xml
001.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
002.    android:id="@+id/tableLayout1"
003.    android:layout_width="fill_parent"
004.    android:layout_height="fill_parent">
005.  
006.    <TableRow
007.      android:id="@+id/tableRow1"
008.      android:layout_width="wrap_content"
009.      android:layout_height="wrap_content" >
010.      
011.     <TextView
012.        android:id="@+id/textView1"
013.        android:layout_width="wrap_content"
014.        android:layout_height="wrap_content"
015.        android:gravity="center"
016.        android:text="Update Form "
017.        android:layout_span="1"
018.        android:textAppearance="?android:attr/textAppearanceLarge" />
019.             
020.    </TableRow>
021. 
022.    <View
023.        android:layout_height="1dip"
024.        android:background="#CCCCCC" />
025.  
026.  <TableLayout
027.        android:layout_width="fill_parent"
028.        android:layout_height="wrap_content"
029.        android:layout_weight="0.1"
030.        android:orientation="horizontal">
031. 
032.     <TableRow>
033.      <TextView
034.          android:layout_width="wrap_content"
035.          android:layout_height="wrap_content"
036.          android:text="MemberID "
037.          android:textAppearance="?android:attr/textAppearanceMedium" />
038.      <TextView
039.          android:layout_width="wrap_content"
040.          android:layout_height="wrap_content"
041.          android:gravity="center"
042.          android:layout_weight="0.2"
043.          android:text=" = " />
044.      <TextView
045.          android:id="@+id/txtMemberID"
046.          android:layout_width="wrap_content"
047.          android:layout_height="wrap_content"
048.          android:text="MemberID" />
049.     </TableRow>
050.      
051.    <TableRow>
052.      <TextView
053.          android:layout_width="wrap_content"
054.          android:layout_height="wrap_content"
055.          android:text="Username "
056.          android:textAppearance="?android:attr/textAppearanceMedium" />
057.      <TextView
058.          android:layout_width="wrap_content"
059.          android:layout_height="wrap_content"
060.          android:gravity="center"
061.          android:layout_weight="0.2"
062.          android:text=" = " />
063.      <TextView
064.          android:id="@+id/txtUsername"
065.          android:layout_width="wrap_content"
066.          android:layout_height="wrap_content"
067.          android:text="Username" />
068.     </TableRow>
069. 
070.      <TextView
071.          android:layout_width="wrap_content"
072.          android:layout_height="wrap_content"
073.          android:text="Input Password/Confirm Password :"
074.          android:textAppearance="?android:attr/textAppearanceMedium" />
075.        <TableRow>
076.      <EditText
077.          android:id="@+id/txtPassword"
078.          android:layout_width="wrap_content"
079.          android:layout_height="wrap_content"
080.          android:ems="6"
081.          android:inputType="textPassword" >
082.      </EditText>
083.      <TextView
084.          android:layout_width="wrap_content"
085.          android:layout_height="wrap_content"
086.          android:text=" Again " />
087. 
088.      <EditText
089.          android:id="@+id/txtConPassword"
090.          android:layout_width="wrap_content"
091.          android:layout_height="wrap_content"
092.          android:ems="7"
093.          android:inputType="textPassword" >
094.      </EditText>
095.      </TableRow>
096.       
097.      <TextView
098.          android:layout_width="wrap_content"
099.          android:layout_height="wrap_content"
100.          android:text="Input Name :"
101.          android:textAppearance="?android:attr/textAppearanceMedium" />
102. 
103.      <EditText
104.          android:id="@+id/txtName"
105.          android:layout_width="wrap_content"
106.          android:layout_height="wrap_content"
107.          android:ems="10" >
108.      </EditText>
109.       
110.      <TextView
111.          android:layout_width="wrap_content"
112.          android:layout_height="wrap_content"
113.          android:text="Input Email :"
114.          android:textAppearance="?android:attr/textAppearanceMedium" />
115. 
116.      <EditText
117.          android:id="@+id/txtEmail"
118.          android:layout_width="wrap_content"
119.          android:layout_height="wrap_content"
120.          android:inputType="textEmailAddress"
121.          android:ems="10" >
122.      </EditText>
123.       
124.      <TextView
125.          android:layout_width="wrap_content"
126.          android:layout_height="wrap_content"
127.          android:text="Input Tel :"
128.          android:textAppearance="?android:attr/textAppearanceMedium" />
129. 
130.      <EditText
131.          android:id="@+id/txtTel"
132.          android:layout_width="wrap_content"
133.          android:layout_height="wrap_content"
134.          android:inputType="phone"
135.          android:ems="10" >
136.      </EditText>
137. 
138.        <Button
139.            android:id="@+id/btnSave"
140.            android:layout_width="wrap_content"
141.            android:layout_height="wrap_content"
142.            android:text="Save" />
143. 
144.        <Button
145.            android:id="@+id/btnCancel"
146.            android:layout_width="wrap_content"
147.            android:layout_height="wrap_content"
148.            android:text="Cancel" />
149.             
150.    </TableLayout >
151. 
152.    <View
153.        android:layout_height="1dip"
154.        android:background="#CCCCCC" />
155.           
156.    <LinearLayout
157.      android:id="@+id/LinearLayout1"
158.      android:layout_width="wrap_content"
159.      android:layout_height="wrap_content"
160.      android:padding="5dip" >
161. 
162.        <TextView
163.            android:id="@+id/textView2"
164.            android:layout_width="wrap_content"
165.            android:layout_height="wrap_content"
166.            android:text="By.. ThaiCreate.Com" />
167. 
168.    </LinearLayout>
169.     
170.</TableLayout>


MainActivity.java
001.package com.myapp;
002. 
003.import java.io.IOException;
004.import java.util.ArrayList;
005.import java.util.HashMap;
006. 
007.import org.json.JSONArray;
008.import org.json.JSONException;
009.import org.json.JSONObject;
010.import org.ksoap2.SoapEnvelope;
011.import org.ksoap2.serialization.SoapObject;
012.import org.ksoap2.serialization.SoapSerializationEnvelope;
013.import org.ksoap2.transport.HttpTransportSE;
014.import org.xmlpull.v1.XmlPullParserException;
015. 
016.import android.os.Bundle;
017.import android.os.StrictMode;
018.import android.annotation.SuppressLint;
019.import android.app.Activity;
020.import android.content.Context;
021.import android.content.Intent;
022.import android.view.ContextMenu;
023.import android.view.ContextMenu.ContextMenuInfo;
024.import android.view.LayoutInflater;
025.import android.view.MenuItem;
026.import android.view.View;
027.import android.view.Menu;
028.import android.view.ViewGroup;
029.import android.view.inputmethod.InputMethodManager;
030.import android.widget.AdapterView;
031.import android.widget.BaseAdapter;
032.import android.widget.Button;
033.import android.widget.EditText;
034.import android.widget.ListView;
035.import android.widget.TextView;
036.import android.widget.Toast;
037. 
038.public class MainActivity extends Activity {
039.     
040.     
041.    // for List Data
042.    private final String NAMESPACE = "https://www.thaicreate.com/android/getMember.php";
043.    private final String URL = "https://www.thaicreate.com/android/getMember.php?wsdl"; // WSDL URL
044.    private final String SOAP_ACTION = "https://www.thaicreate.com/android/getMember.php/resultMember";
045.    private final String METHOD_NAME = "resultMember"; // Method on web service
046.     
047.     
048.    ArrayList<HashMap<String, String>> MyArrList;
049.    String[] Cmd = {"View","Update","Delete"};
050.         
051.    @SuppressLint("NewApi")
052.    @Override
053.    public void onCreate(Bundle savedInstanceState) {
054.        super.onCreate(savedInstanceState);
055.        setContentView(R.layout.activity_main);
056. 
057.        // Permission StrictMode
058.        if (android.os.Build.VERSION.SDK_INT > 9) {
059.            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
060.            StrictMode.setThreadPolicy(policy);
061.        }
062.         
063.        ShowData();
064.         
065.         
066.        // btnSearch
067.        final Button btnSearch = (Button) findViewById(R.id.btnSearch);
068.        //btnSearch.setBackgroundColor(Color.TRANSPARENT);
069.        // Perform action on click
070.        btnSearch.setOnClickListener(new View.OnClickListener() {
071.            public void onClick(View v) {
072.                ShowData();
073.            }
074.        });
075.         
076.    }
077.     
078.    public void ShowData()
079.    {
080.         // listView1
081.        final ListView lisView1 = (ListView)findViewById(R.id.listView1);  
082.         
083.        // keySearch
084.        EditText strKeySearch = (EditText)findViewById(R.id.txtKeySearch);
085.         
086.        // Disbled Keyboard auto focus
087.        InputMethodManager imm = (InputMethodManager)getSystemService(
088.              Context.INPUT_METHOD_SERVICE);
089.        imm.hideSoftInputFromWindow(strKeySearch.getWindowToken(), 0);
090.         
091.         
092.         
093.        /** Web Service return JSON Code
094.         * [{"MemberID":"1","Username":"weerachai","Password":"weerachai@1","Name":"Weerachai Nukitram","Tel":"0819876107","Email":"weerachai@thaicreate.com"},
095.         * {"MemberID":"2","Username":"adisorn","Password":"adisorn@2","Name":"Adisorn Bunsong","Tel":"021978032","Email":"adisorn@thaicreate.com"},
096.         * {"MemberID":"3","Username":"surachai","Password":"surachai@3","Name":"Surachai Sirisart","Tel":"0876543210","Email":"surachai@thaicreate.com"}]
097.         */
098.         
099.        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
100.        request.addProperty("strName", strKeySearch.getText().toString());
101. 
102.        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
103.                SoapEnvelope.VER11);
104. 
105.        envelope.setOutputSoapObject(request);
106. 
107.        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
108.         
109.        try {
110. 
111.            androidHttpTransport.call(SOAP_ACTION, envelope);
112.            SoapObject result = (SoapObject) envelope.bodyIn;
113. 
114.            if (result != null) {
115.                     
116.            /**
117.             * [{"MemberID":"1","Username":"weerachai","Password":"weerachai@1","Name":"Weerachai Nukitram","Tel":"0819876107","Email":"weerachai@thaicreate.com"},
118.             * {"MemberID":"2","Username":"adisorn","Password":"adisorn@2","Name":"Adisorn Bunsong","Tel":"021978032","Email":"adisorn@thaicreate.com"},
119.             * {"MemberID":"3","Username":"surachai","Password":"surachai@3","Name":"Surachai Sirisart","Tel":"0876543210","Email":"surachai@thaicreate.com"}]
120.             */
121.                 
122.                MyArrList = new ArrayList<HashMap<String, String>>();
123.                HashMap<String, String> map;
124.                 
125.                JSONArray data = new JSONArray(result.getProperty(0).toString());
126.                 
127.                for(int i = 0; i < data.length(); i++){
128.                    JSONObject c = data.getJSONObject(i);
129.                     
130.                    map = new HashMap<String, String>();
131.                    map.put("MemberID", c.getString("MemberID"));
132.                    map.put("Username", c.getString("Username"));
133.                    map.put("Password", c.getString("Password"));
134.                    map.put("Name", c.getString("Name"));
135.                    map.put("Email", c.getString("Email"));
136.                    map.put("Tel", c.getString("Tel"));
137.                    MyArrList.add(map);
138.                }
139.                 
140.                lisView1.setAdapter(new ImageAdapter(this));
141.                 
142.                registerForContextMenu(lisView1);
143.                 
144. 
145.            } else {
146.                Toast.makeText(getApplicationContext(),
147.                        "Web Service not Response!", Toast.LENGTH_LONG)
148.                        .show();
149.            }
150. 
151.        } catch (IOException e) {
152.            // TODO Auto-generated catch block
153.            e.printStackTrace();
154.        } catch (XmlPullParserException e) {
155.            // TODO Auto-generated catch block
156.            e.printStackTrace();
157.        } catch (JSONException e) {
158.            // TODO Auto-generated catch block
159.            e.printStackTrace();
160.        }
161.         
162.    }
163.     
164.    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
165. 
166.        menu.setHeaderIcon(android.R.drawable.btn_star_big_on);
167.        menu.setHeaderTitle("Command");
168.        String[] menuItems = Cmd;
169.        for (int i = 0; i<menuItems.length; i++) {
170.            menu.add(Menu.NONE, i, i, menuItems[i]);
171.        }
172.    }
173.     
174.    @Override
175.    public boolean onContextItemSelected(MenuItem item) {
176.        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
177.        int menuItemIndex = item.getItemId();
178.        String[] menuItems = Cmd;
179.        String CmdName = menuItems[menuItemIndex];
180.         
181.        // Check Event Command
182.        if ("View".equals(CmdName)) {
183.             Toast.makeText(MainActivity.this,"Your Selected View",Toast.LENGTH_LONG).show();
184.             /**
185.              * Call the mthod
186.              */
187.        } else if ("Update".equals(CmdName)) {
188.            Toast.makeText(MainActivity.this,"Your Selected Update",Toast.LENGTH_LONG).show();
189. 
190.            String sMemberID = MyArrList.get(info.position).get("MemberID").toString();
191.            String sName = MyArrList.get(info.position).get("Name").toString();
192.            String sTel = MyArrList.get(info.position).get("Tel").toString();
193.             
194.            Intent newActivity = new Intent(MainActivity.this,UpdateActivity.class);
195.            newActivity.putExtra("MemberID", sMemberID);
196.            startActivity(newActivity);
197.             
198.        } else if ("Delete".equals(CmdName)) {
199.             Toast.makeText(MainActivity.this,"Your Selected Delete",Toast.LENGTH_LONG).show();
200.             /**
201.              * Call the mthod
202.              */
203.        }       
204.        return true;
205.    }
206. 
207.     
208.    public class ImageAdapter extends BaseAdapter
209.    {
210.        private Context context;
211. 
212.        public ImageAdapter(Context c)
213.        {
214.            // TODO Auto-generated method stub
215.            context = c;
216.        }
217.  
218.        public int getCount() {
219.            // TODO Auto-generated method stub
220.            return MyArrList.size();
221.        }
222.  
223.        public Object getItem(int position) {
224.            // TODO Auto-generated method stub
225.            return position;
226.        }
227.  
228.        public long getItemId(int position) {
229.            // TODO Auto-generated method stub
230.            return position;
231.        }
232.        public View getView(final int position, View convertView, ViewGroup parent) {
233.            // TODO Auto-generated method stub
234.             
235.            LayoutInflater inflater = (LayoutInflater) context
236.                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
237.             
238.                if (convertView == null) {
239.                    convertView = inflater.inflate(R.layout.activity_column, null);
240.                }
241. 
242.                // ColMemberID
243.                TextView txtMemberID = (TextView) convertView.findViewById(R.id.ColMemberID);
244.                txtMemberID.setPadding(10, 0, 0, 0);
245.                txtMemberID.setText(MyArrList.get(position).get("MemberID") +".");
246.                 
247.                // R.id.ColName
248.                TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
249.                txtName.setPadding(5, 0, 0, 0);
250.                txtName.setText(MyArrList.get(position).get("Name"));
251.                 
252.                // R.id.ColTel
253.                TextView txtTel = (TextView) convertView.findViewById(R.id.ColTel);
254.                txtTel.setPadding(5, 0, 0, 0);
255.                txtTel.setText(MyArrList.get(position).get("Tel"));
256.                 
257.      
258.                return convertView;
259.                 
260.        }
261. 
262.    }
263.     
264.     
265.    @Override
266.    public boolean onCreateOptionsMenu(Menu menu) {
267.        getMenuInflater().inflate(R.menu.activity_main, menu);
268.        return true;
269.    }
270.     
271.}


UpdateActivity.java
001.package com.myapp;
002. 
003.import java.io.IOException;
004. 
005.import org.json.JSONException;
006.import org.json.JSONObject;
007.import org.ksoap2.SoapEnvelope;
008.import org.ksoap2.serialization.SoapObject;
009.import org.ksoap2.serialization.SoapSerializationEnvelope;
010.import org.ksoap2.transport.HttpTransportSE;
011.import org.xmlpull.v1.XmlPullParserException;
012. 
013.import android.os.Bundle;
014.import android.os.StrictMode;
015.import android.annotation.SuppressLint;
016.import android.app.Activity;
017.import android.app.AlertDialog;
018.import android.content.Intent;
019.import android.view.View;
020.import android.view.Menu;
021.import android.widget.Button;
022.import android.widget.EditText;
023.import android.widget.TextView;
024.import android.widget.Toast;
025. 
026.public class UpdateActivity extends Activity {
027.        
028.    // for Show Data
029.    private final String NAMESPACE1 = "https://www.thaicreate.com/android/resultByMemberID.php";
030.    private final String URL1 = "https://www.thaicreate.com/android/resultByMemberID.php?wsdl"; // WSDL URL
031.    private final String SOAP_ACTION1 = "https://www.thaicreate.com/android/resultByMemberID.php/resultMember";
032.    private final String METHOD_NAME1 = "resultMember"; // Method on web service
033.     
034.    // for Update Data
035.    private final String NAMESPACE2 = "https://www.thaicreate.com/android/updateMemberData.php";
036.    private final String URL2 = "https://www.thaicreate.com/android/updateMemberData.php?wsdl"; // WSDL URL
037.    private final String SOAP_ACTION2 = "https://www.thaicreate.com/android/updateMemberData.php/updateMember";
038.    private final String METHOD_NAME2 = "updateMember"; // Method on web service
039.     
040.    @SuppressLint("NewApi")
041.    @Override
042.    public void onCreate(Bundle savedInstanceState) {
043.        super.onCreate(savedInstanceState);
044.        setContentView(R.layout.activity_update);
045. 
046.        // Permission StrictMode
047.        if (android.os.Build.VERSION.SDK_INT > 9) {
048.            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
049.            StrictMode.setThreadPolicy(policy);
050.        }
051.         
052.        showInfo();
053.         
054.        // btnSave
055.        Button btnSave = (Button) findViewById(R.id.btnSave);
056.        // Perform action on click
057.        btnSave.setOnClickListener(new View.OnClickListener() {
058.            public void onClick(View v) {
059.                if(SaveData())
060.                {
061.                    // When Save Complete
062.                    Intent newActivity = new Intent(UpdateActivity.this,MainActivity.class);
063.                    startActivity(newActivity);
064.                }
065.            }
066.        });
067.         
068.         
069.        // btnCancel
070.        final Button btnCancel = (Button) findViewById(R.id.btnCancel);
071.        // Perform action on click
072.        btnCancel.setOnClickListener(new View.OnClickListener() {
073.            public void onClick(View v) {
074.                Intent newActivity = new Intent(UpdateActivity.this,MainActivity.class);
075.                startActivity(newActivity);
076.            }
077.        });
078.         
079.    }
080.     
081.    public void showInfo()
082.    {
083.        // txtMemberID,txtUsername,txtPassword,txtConPassword,txtName,txtEmail,txtTel
084.        final TextView tMemberID = (TextView)findViewById(R.id.txtMemberID);
085.        final TextView tUsername = (TextView)findViewById(R.id.txtUsername);
086.        final TextView tPassword = (TextView)findViewById(R.id.txtPassword);
087.        final TextView tConPassword = (TextView)findViewById(R.id.txtConPassword);
088.        final TextView tName = (TextView)findViewById(R.id.txtName);
089.        final TextView tEmail = (TextView)findViewById(R.id.txtEmail);
090.        final TextView tTel = (TextView)findViewById(R.id.txtTel);
091.         
092.        Button btnSave = (Button) findViewById(R.id.btnSave);
093.        Button btnCancel = (Button) findViewById(R.id.btnCancel);
094.         
095.         
096.        Intent intent= getIntent();
097.        final String MemberID = intent.getStringExtra("MemberID");
098. 
099.        SoapObject request = new SoapObject(NAMESPACE1, METHOD_NAME1);
100.        request.addProperty("strMemberID", MemberID);
101. 
102.        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
103.                SoapEnvelope.VER11);
104. 
105.        envelope.setOutputSoapObject(request);
106. 
107.        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
108.        String resultServer = null;
109. 
110.        /** Get result from Server (Return the JSON Code)
111.         *
112.         * {"MemberID":"2","Username":"adisorn","Password":"adisorn@2","Name":"Adisorn Bunsong","Tel":"021978032","Email":"adisorn@thaicreate.com"}
113.         */
114.         
115.        try {
116.            androidHttpTransport.call(SOAP_ACTION1, envelope);
117.            SoapObject result = (SoapObject) envelope.bodyIn;
118.            resultServer = result.getProperty(0).toString();
119.        } catch (IOException e) {
120.            // TODO Auto-generated catch block
121.            e.printStackTrace();
122.        } catch (XmlPullParserException e) {
123.            // TODO Auto-generated catch block
124.            e.printStackTrace();
125.        }
126.         
127.        String strMemberID = "";
128.        String strUsername = "";
129.        String strPassword = "";
130.        String strName = "";
131.        String strEmail = "";
132.        String strTel = "";
133.         
134.        JSONObject c;
135.        try {
136.            c = new JSONObject(resultServer);
137.            strMemberID = c.getString("MemberID");
138.            strUsername = c.getString("Username");
139.            strPassword = c.getString("Password");
140.            strName = c.getString("Name");
141.            strEmail = c.getString("Email");
142.            strTel = c.getString("Tel");
143.             
144.            if(!strMemberID.equals(""))
145.            {
146.                tMemberID.setText(strMemberID);
147.                tUsername.setText(strUsername);
148.                tPassword.setText(strPassword);
149.                tConPassword.setText(strPassword);
150.                tName.setText(strName);
151.                tEmail.setText(strEmail);
152.                tTel.setText(strTel);
153.            }
154.            else
155.            {
156.                tMemberID.setText("-");
157.                tUsername.setText("-");
158.                tName.setText("-");
159.                tEmail.setText("-");
160.                tTel.setText("-");
161.                btnSave.setEnabled(false);
162.                btnCancel.requestFocus();
163.            }
164.             
165.        } catch (JSONException e) {
166.            // TODO Auto-generated catch block
167.            e.printStackTrace();
168.        }
169.         
170.    }
171.     
172.     
173.    public boolean SaveData()
174.    {
175.         
176.        // txtMemberID,txtPassword,txtName,txtEmail,txtTel
177.        final TextView txtMemberID = (TextView)findViewById(R.id.txtMemberID);
178.        final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
179.        final EditText txtConPassword = (EditText)findViewById(R.id.txtConPassword);
180.        final EditText txtName = (EditText)findViewById(R.id.txtName);
181.        final EditText txtEmail = (EditText)findViewById(R.id.txtEmail);
182.        final EditText txtTel = (EditText)findViewById(R.id.txtTel);
183.         
184.             
185.            // Dialog
186.            final AlertDialog.Builder ad = new AlertDialog.Builder(this);
187. 
188.            ad.setTitle("Error! ");
189.            ad.setIcon(android.R.drawable.btn_star_big_on);
190.            ad.setPositiveButton("Close", null);
191. 
192.            // Check Password
193.            if(txtPassword.getText().length() == 0 || txtConPassword.getText().length() == 0 )
194.            {
195.                ad.setMessage("Please input [Password/Confirm Password] ");
196.                ad.show();
197.                txtPassword.requestFocus();
198.                return false;
199.            }
200.            // Check Password and Confirm Password (Match)
201.            if(!txtPassword.getText().toString().equals(txtConPassword.getText().toString()))
202.            {
203.                ad.setMessage("Password and Confirm Password Not Match! ");
204.                ad.show();
205.                txtConPassword.requestFocus();
206.                return false;
207.            }
208.            // Check Name
209.            if(txtName.getText().length() == 0)
210.            {
211.                ad.setMessage("Please input [Name] ");
212.                ad.show();
213.                txtName.requestFocus();
214.                return false;
215.            }
216.            // Check Email
217.            if(txtEmail.getText().length() == 0)
218.            {
219.                ad.setMessage("Please input [Email] ");
220.                ad.show();
221.                txtEmail.requestFocus();
222.                return false;
223.            }
224.            // Check Tel
225.            if(txtTel.getText().length() == 0)
226.            {
227.                ad.setMessage("Please input [Tel] ");
228.                ad.show();
229.                txtTel.requestFocus();
230.                return false;
231.            }
232.             
233. 
234.            SoapObject request = new SoapObject(NAMESPACE2, METHOD_NAME2);
235.            request.addProperty("strMemberID", txtMemberID.getText().toString());
236.            request.addProperty("strPassword", txtPassword.getText().toString());
237.            request.addProperty("strName", txtName.getText().toString());
238.            request.addProperty("strEmail", txtEmail.getText().toString());
239.            request.addProperty("strTel", txtTel.getText().toString());
240. 
241.            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
242.                    SoapEnvelope.VER11);
243. 
244.            envelope.setOutputSoapObject(request);
245. 
246.            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL2);
247.            String resultServer = null;
248.             
249.            try {
250.                androidHttpTransport.call(SOAP_ACTION2, envelope);
251.                SoapObject result = (SoapObject) envelope.bodyIn;
252.                resultServer = result.getProperty(0).toString();
253.            } catch (IOException e) {
254.                // TODO Auto-generated catch block
255.                e.printStackTrace();
256.            } catch (XmlPullParserException e) {
257.                // TODO Auto-generated catch block
258.                e.printStackTrace();
259.            }
260.             
261.            /** Get result from Server (Return the JSON Code)
262.             * StatusID = ? [0=Failed,1=Complete]
263.             * Error    = ? [On case error return custom error message]
264.             *
265.             * Eg Save Failed = {"StatusID":"0","Error":"Email Exists!"}
266.             * Eg Save Complete = {"StatusID":"1","Error":""}
267.             */
268.             
269.             
270.            /*** Default Value ***/
271.            String strStatusID = "0";
272.            String strError = "Unknow Status!";
273.             
274.            JSONObject c;
275.            try {
276.                c = new JSONObject(resultServer);
277.                strStatusID = c.getString("StatusID");
278.                strError = c.getString("Error");
279.            } catch (JSONException e) {
280.                // TODO Auto-generated catch block
281.                e.printStackTrace();
282.            }
283.             
284.            // Prepare Save Data
285.            if(strStatusID.equals("0"))
286.            {
287.                ad.setMessage(strError);
288.                ad.show();
289.                return false;
290.            }
291.            else
292.            {
293.                Toast.makeText(UpdateActivity.this, "Update Data Successfully", Toast.LENGTH_SHORT).show();
294.            }
295.                     
296.     
297.        return true;
298.    }
299.     
300.     
301.    @Override
302.    public boolean onCreateOptionsMenu(Menu menu) {
303.        getMenuInflater().inflate(R.menu.activity_main, menu);
304.        return true;
305.    }
306.     
307.}


AndroidManifest.xml
1.<activity
2.    android:name="UpdateActivity"
3.    android:theme="@style/AppTheme"
4.    android:screenOrientation="portrait"           
5.    android:label="@string/title_activity_main" />


Screenshot

Android Update Data Server via Web Service

แสดงรายการข้อมูลจาก Web Service

Android Update Data Server via Web Service

เลือกรายการที่จะแก้ไข โดยใช้การ LongClick และมี Context Menu ให้เลือก Update

Android Update Data Server via Web Service

Activity Form สำหรับแก้ไขข้อมูล จะลองแก้ไข นามสกุลในช่อง Name

Android Update Data Server via Web Service

ทดสอบการแก้ไข

Android Update Data Server via Web Service

เลือกบันทึกข้อมูล

Android Update Data Server via Web Service

หลังจากที่บันทึกข้อมุลเรียบร้อยแล้ว และกลับไปดูข้อมูลของ MySQL บน Web Service ก็จะเห็นว่าข้อมูลได้ถูกแก้ไขเรียบร้อยแล้ว

   
Hate it
Don't like it
It's ok
Like it
Love it
Total Votes: 95Overall Rating: 4.2 / 5
Share

Property & Method (Others Related)

Android and Web Service
Android Insert Data to Server via Web Service
Android Delete Data in Server via Web Service

ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-08-11 16:06:48 / 2012-08-13 15:51:20
  Download : No files
 Sponsored Links / Related

 
Android Custom Adapter
Rating :

 
Android People Contact List, Name, Phone No, Photo Picture, Email and Address
Rating :

 
Android Rating (Vote) and ListView Part 1
Rating :

 
Android Rating (Vote) and ListView Part 2 (Member Login and Average Rating)
Rating :

 
Android PhoneGap (jQuery Mobile) Create Convert App from Website(URL)
Rating :

 
Android Capture Image and Camera Capture Screenshot (android.view.SurfaceView)
Rating :

 
Android Pull Down to Refresh And Release to Refresh or Update (Part 1)
Rating :

 
Android Pull Down to Refresh And Release to Update (Part 2 , PHP & MySQL)
Rating :


ThaiCreate.Com Forum
Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   





ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2025 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่