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


Android Web Service and JSON Parser

Android Web Service and JSON Parser บทความและตัวอย่าง Basic Web Service และทำความเข้าใจพื้นฐานการนำ JSON มาใช้งานรวมกับ Web Service ในการรับส่งค่า Resource จาก Web Service ที่มาพร้อมกับ JSON Code เหตุผลที่ใช้ JSON ก็คือเราสามารถนำ Result ที่ได้จาก Web Service ที่อยู่ในรูปแบบของ JSON ไปใช้ได้ง่ายและสะดวก โดยจะสะดวกในกรณีที่ข้อมูลนั้นเป็นชุดของ Array ซึ่งถ้าปกติเราจะต้องเขียน function สำหรับแปลงข้อความเหล่านั้นหรือตัดเอาในตำแหน่งต่าง ๆ ที่ต้องการ แต่ถ้าใช้ JSON เราเพียงส่งข้อความให้อยู่ในรุปแบบ Syntax ของ JSON จากนั้นใช้ function เพื่อ Decode ข้อความ JSON ได้ในทันที และอ่านค่าของชุด Array จาก Index ได้ทันที

Android and Web Service

Android and JSON


พื้นฐาน JSON และ Web Service แนะนำให้อ่าน 2 บทความนี้

Android and Web Service


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

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

ทดสอบการสร้าง Web Service ด้วย PHP และ Return ค่าเป็น JSON

WebServiceServer.php
01.<?php
02.        require_once("lib/nusoap.php");
03.          
04.        //Create a new soap server
05.        $server = new soap_server();
06.          
07.        //Define our namespace
09.        $server->wsdl->schemaTargetNamespace = $namespace;
10.          
11.        //Configure our WSDL
12.        $server->configureWSDL("HelloWorld");
13.          
14.        // Register our method and argument parameters
15.        $varname = array(
16.                   'strName' => "xsd:string",
17.                   'strEmail' => "xsd:string"
18.        );
19.        $server->register('HelloWorld',$varname, array('return' => 'xsd:string'));
20.          
21.        function HelloWorld($strName,$strEmail)
22.        {
23.            $arr["sName"] = "Sawatdee : ".$strName;
24.            $arr["sEmail"] = "Sawatdee : ".$strEmail;
25. 
26.            header('Content-type: application/json');
27.            return json_encode($arr);
28.        }
29.          
30.        // Get our posted data if the service is being consumed
31.        // otherwise leave this data blank.
32.        $POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
33.          
34.        // pass our posted data (or nothing) to the soap service
35.        $server->service($POST_DATA);
36.        exit();
37.?>

จาก Web Service ข้างต้นจะ Return ค่าเป็น JSON ดังนี้

{"sName":"Sawatdee : Weerachai Nukitram","sEmail":"Sawatdee : is_php@hotmail.com"}



Android Project สร้าง Application เพื่ออ่านค่า JSON

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

Android and Web Service

activity_main.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="Web Service Example "
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.        <TableRow>
032.      </TableRow>
033.       
034.      <TextView
035.          android:layout_width="wrap_content"
036.          android:layout_height="wrap_content"
037.          android:text="Input Name :"
038.          android:textAppearance="?android:attr/textAppearanceMedium" />
039. 
040.      <EditText
041.          android:id="@+id/txtName"
042.          android:layout_width="wrap_content"
043.          android:layout_height="wrap_content"
044.          android:ems="10" >
045.      </EditText>
046.       
047.      <TextView
048.          android:layout_width="wrap_content"
049.          android:layout_height="wrap_content"
050.          android:text="Input Email :"
051.          android:textAppearance="?android:attr/textAppearanceMedium" />
052. 
053.      <EditText
054.          android:id="@+id/txtEmail"
055.          android:layout_width="wrap_content"
056.          android:layout_height="wrap_content"
057.          android:inputType="textEmailAddress"
058.          android:ems="10" >
059.      </EditText>
060. 
061.        <Button
062.            android:id="@+id/btnSend"
063.            android:layout_width="wrap_content"
064.            android:layout_height="wrap_content"
065.            android:text="Send" />
066. 
067.        <TextView
068.            android:id="@+id/txtResultName"
069.            android:layout_width="wrap_content"
070.            android:layout_height="wrap_content"
071.            android:textAppearance="?android:attr/textAppearanceSmall"
072.            android:text="Result Name" />
073. 
074.        <TextView
075.            android:id="@+id/txtResultEmail"
076.            android:layout_width="wrap_content"
077.            android:layout_height="wrap_content"
078.            android:text="Result Email" />
079.             
080.    </TableLayout >
081. 
082.    <View
083.        android:layout_height="1dip"
084.        android:background="#CCCCCC" />
085.           
086.    <LinearLayout
087.      android:id="@+id/LinearLayout1"
088.      android:layout_width="wrap_content"
089.      android:layout_height="wrap_content"
090.      android:padding="5dip" >
091. 
092.        <TextView
093.            android:layout_width="wrap_content"
094.            android:layout_height="wrap_content"
095.            android:text="By.. ThaiCreate.Com" />
096. 
097.    </LinearLayout>
098.     
099.</TableLayout>




MainActivity.java
001.package com.myapp;
002. 
003. 
004.import java.io.IOException;
005. 
006.import org.json.JSONException;
007.import org.json.JSONObject;
008.import org.ksoap2.SoapEnvelope;
009.import org.ksoap2.serialization.SoapObject;
010.import org.ksoap2.serialization.SoapSerializationEnvelope;
011.import org.ksoap2.transport.HttpTransportSE;
012.import org.xmlpull.v1.XmlPullParserException;
013. 
014.import android.os.Bundle;
015.import android.os.StrictMode;
016.import android.view.Menu;
017.import android.view.View;
018.import android.widget.Button;
019.import android.widget.EditText;
020.import android.widget.TextView;
021.import android.widget.Toast;
022.import android.annotation.SuppressLint;
023.import android.app.Activity;
024. 
025.public class MainActivity extends Activity {
026.     
027.    private final String NAMESPACE = "https://www.thaicreate.com/android/WebServiceServer.php";
028.    private final String URL = "https://www.thaicreate.com/android/WebServiceServer.php?wsdl"; // WSDL URL
029.    private final String SOAP_ACTION = "https://www.thaicreate.com/android/WebServiceServer.php/HelloWorld";
030.    private final String METHOD_NAME = "HelloWorld"; // Method on web service
031.     
032.    @SuppressLint("NewApi")
033.    @Override
034.    public void onCreate(Bundle savedInstanceState) {
035.        super.onCreate(savedInstanceState);
036.        setContentView(R.layout.activity_main);
037. 
038.        // Permission StrictMode
039.        if (android.os.Build.VERSION.SDK_INT > 9) {
040.            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
041.                    .permitAll().build();
042.            StrictMode.setThreadPolicy(policy);
043.        }
044. 
045.        // btnSend
046.        Button btnSend = (Button) this.findViewById(R.id.btnSend);
047.        btnSend.setOnClickListener(new View.OnClickListener() {
048.            public void onClick(View v) {
049.                 
050.                // txtName
051.                EditText txtName = (EditText) findViewById(R.id.txtName);
052.                // txtEmail
053.                EditText txtEmail = (EditText) findViewById(R.id.txtEmail);
054.                 
055.                 
056.                // txtResultName
057.                TextView txtResultName = (TextView) findViewById(R.id.txtResultName);
058.                // txtResultEmail
059.                TextView txtResultEmail = (TextView) findViewById(R.id.txtResultEmail);
060.                 
061. 
062.                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
063.                request.addProperty("strName", txtName.getText().toString());
064.                request.addProperty("strEmail", txtEmail.getText().toString());
065. 
066.                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
067.                        SoapEnvelope.VER11);
068. 
069.                envelope.setOutputSoapObject(request);
070. 
071.                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
072. 
073.                try {
074. 
075.                    androidHttpTransport.call(SOAP_ACTION, envelope);
076.                    SoapObject result = (SoapObject) envelope.bodyIn;
077. 
078.                    if (result != null) {
079.                         
080.                         
081.                        /** Get result from WebService (Return the JSON Code)
082.                         * Eg Login Failed = {"sName":"Sawatdee : Weerachai Nukitram","sEmail":"Sawatdee : is_php@hotmail.com"}
083.                         */
084.                         
085.                        JSONObject c = new JSONObject(result.getProperty(0).toString());
086.                        String strResultName = c.getString("sName");
087.                        String strResultEmail = c.getString("sEmail");
088.                        txtResultName.setText(strResultName);
089.                        txtResultEmail.setText(strResultEmail);
090.                         
091.                    } else {
092.                        Toast.makeText(getApplicationContext(),
093.                                "Web Service not Response!", Toast.LENGTH_LONG)
094.                                .show();
095.                    }
096. 
097.                } catch (IOException e) {
098.                    // TODO Auto-generated catch block
099.                    e.printStackTrace();
100.                } catch (XmlPullParserException e) {
101.                    // TODO Auto-generated catch block
102.                    e.printStackTrace();
103.                } catch (JSONException e) {
104.                    // TODO Auto-generated catch block
105.                    e.printStackTrace();
106.                }
107. 
108.            }
109.        });
110. 
111.    }
112.     
113.    @Override
114.    public boolean onCreateOptionsMenu(Menu menu) {
115.        getMenuInflater().inflate(R.menu.activity_main, menu);
116.        return true;
117.    }
118.     
119.}


คำอธิบาย
1.JSONObject c = new JSONObject(result.getProperty(0).toString());
2.String strResultName = c.getString("sName");
3.String strResultEmail = c.getString("sEmail");

เป็นการอ่าน Result ที่อยู่ในรูปแบบ JSON โดยอ้างถึง Index ของ Array



Screenshot

Android and Web Service

กรอกข้อมูล

Android and Web Service

แสดงค่าจกา JSON ที่ถูกกแปลงเรียบร้อยแล้ว

   
Hate it
Don't like it
It's ok
Like it
Love it
Share


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


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


   


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

 
Android and JSON
Rating :

 
Android and JSON (GSON)
Rating :

 
Android and Web Service
Rating :

 
Android and Web Server ของ PHP กับ MySQL แสดงบน ListView ในรูปแบบของ JSON
Rating :

 
Android JSON Retrieving Data from URL Web Server (PHP MySQL and JSON)
Rating :

 
Android Loading JSON and ProgressBar/ProgressDialog
Rating :

 
Android Login Form via Web Service
Rating :

 
Android Get Result / Search Data from Server via Web Service
Rating :

 
Android XML Parsing and XML Rss Feed
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 อัตราราคา คลิกที่นี่