Android uses HTTP network communication to achieve interaction with PHP (3). android Network Communication

Source: Internet
Author: User

Android uses HTTP network communication to achieve interaction with PHP (3). android Network Communication

Android and PHP interactions are implemented through Http network programming. php is used to access the database, operate data in the database, and php is used as an interface to connect Android to the database.

In general, we use Json format for transmission, and php to encapsulate data in Json format, and then parse Json data on Android. Display the parsed data on your mobile phone.

In order to interact with the previous two articles, I will not show you the parsing of Json data in this blog post. I will explain the parsing of Json data in the next article, and how to deploy the data in the layout file. This time, I only display the obtained Json data in TextView. For your convenience, I have set two textviews for comparison, one for deployment and the other for local data. In addition, it is implemented through redirection.

  As follows:

 A:

  

  B:

  

C:

  

  Procedure:

First open the software, and then click Submit to jump to another interface to display data. Json data is directly displayed and is not parsed.

Java code:

  MainActivity:

  

 1 package com.example.testregister; 2  3  4 import android.app.Activity; 5 import android.content.Intent; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button;10 import android.widget.EditText;11 12 public class MainActivity extends Activity{13     14     private Button btn;15     16     @Override17     protected void onCreate(Bundle savedInstanceState) {18         super.onCreate(savedInstanceState);19         setContentView(R.layout.activity_main);20         21         btn = (Button) findViewById(R.id.btn_tijao);22         23         btn.setOnClickListener(new OnClickListener() {24             25             @Override26             public void onClick(View v) {27                 28                 Intent intent = new Intent(getApplicationContext(),ShowTest.class);29                 startActivity(intent);30             }31         });32     }33 34 35     36 }

Layout file activity_main.xml:

1 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 2 xmlns: tools = "http://schemas.android.com/tools" 3 android: id = "@ + id/LinearLayout1" 4 android: layout_width = "match_parent" 5 android: layout_height = "match_parent" 6 android: orientation = "vertical" 7 tools: context = ". mainActivity "> 8 9 <TextView10 android: layout_width =" wrap_content "11 android: layout_height =" wrap_content "12 android: text = "@ string/hello_world"/> 13 14 <Button15 android: id = "@ + id/btn_tijao" 16 android: layout_width = "fill_parent" 17 android: layout_height = "wrap_content" 18 android: text = "Submit"/> 19 20 </LinearLayout>

ShowTest:

1 package com. example. testregister; 2 3 import android. app. activity; 4 import android. OS. bundle; 5 import android. widget. textView; 6 7 import com. example. interfaceHttp. httpGetListener; 8 import com. example. service. httpGetData; 9 10 public class ShowTest extends Activity implements HttpGetListener {11 12 private TextView textv1; 13 private TextView textv2; 14 15 // my local server interface, if you need to change the url16 private String url = "http: // 10.17.64.85: 8080/testregister/JSONPars on your server. php "; 17 18 private HttpGetData mhttpgetdata; 19 20 21 @ Override22 protected void onCreate (Bundle savedInstanceState) {23 // TODO Auto-generated method stub24 super. onCreate (savedInstanceState); 25 setContentView (R. layout. activitytwo); 26 mhttpgetdata = (HttpGetData) new HttpGetData(url,this).exe cute (); 27 textv1 = (TextView) findViewById (R. id. tv1); 28 textv2 = (TextView) findViewById (R. id. tv2); 29 30 31} 32 33 34 @ Override35 public void GetDataUrl (String data) {36 // TODO Auto-generated method stub37 System. out. println (data); 38 textv1.setText (data); 39 40} 41 42}

The second layout is activitytwo. xml:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" > 6  7     <TextView 8         android:id="@+id/tv1" 9         android:layout_width="fill_parent"10         android:layout_height="wrap_content"11         android:text="ready..." />12 13     <TextView14         android:id="@+id/tv2"15         android:layout_width="fill_parent"16         android:layout_height="wrap_content"17         android:text="ready..." />18 19 </LinearLayout>

The next step is to use HTTP for network processing. Here we use get requests:

HttpGetData:

1 package com. example. service; 2 3 import java. io. bufferedReader; 4 import java. io. inputStream; 5 import java. io. inputStreamReader; 6 7 import org. apache. http. httpEntity; 8 import org. apache. http. httpResponse; 9 import org. apache. http. client. httpClient; 10 import org. apache. http. client. methods. httpGet; 11 import org. apache. http. impl. client. defaultHttpClient; 12 13 import android. OS. asyncTask; 14 15 imp Ort com. example. interfaceHttp. httpGetListener; 16 17 public class HttpGetData extends AsyncTask <String, Void, String> {18 19 private HttpClient requests; 20 private HttpGet mhttpget; 21 private HttpResponse mhttpResponse; 22 private HttpEntity mHttpEntity; 23 private InputStream in; 24 private StringBuffer sb; 25 26 27 28 29 // declare the url variable 30 private String url; 31 // declare the interface 32 private HttpGetListener listener; 33 34 public HttpGetData () {35} 36 37 public HttpGetData (String url) {38 this. url = url; 39} 40 41 public HttpGetData (String url, HttpGetListener listener) {42 this. url = url; 43 this. listener = listener; 44} 45 46/** 47 * write the program to be executed in the background 48 */49 @ Override50 protected String doInBackground (String... params) {51 52 try {53 // first create a client instance 54 mhttpclient = new DefaultHttpClient (); 55 // set the Transfer Method 56 mhttpget = new HttpGet (Url); 57 // send 58 mhttpResponse = mhttpclient.exe cute (mhttpget) through the client; 59 // obtain the method body 60 mHttpEntity = mhttpResponse through HttpResponse. getEntity (); 61 // get the specific content through the stream 62 in = mHttpEntity. getContent (); 63 // create a buffer 64 BufferedReader br = new BufferedReader (new InputStreamReader (in); 65 sb = new StringBuffer (); 66 String line = null; 67 while (line = br. readLine ())! = Null) {68 sb. append (line); 69} 70 return sb. toString (); 71 72 73} catch (Exception e) {74 e. printStackTrace (); 75} 76 77 return null; 78} 79 80 @ Override81 protected void onPostExecute (String result) {82 // TODO Auto-generated method stub83 listener. getDataUrl (result); 84 super. onPostExecute (result); 85} 86 87}

In order to make more classes easy to use, we have implemented this interface HttpGetListener:

1 package com.example.interfaceHttp;2 3 public interface HttpGetListener {4     void GetDataUrl(String data);5 }

Okay, this is the basic Android code, relatively simple, about HTTP network communication this is not very knowledgeable, it is recommended to refer to the http://www.cnblogs.com/bingbingliang-xiaomonv/p/5247223.html

Note:

Configure the Activity when redirecting

The configuration file is as follows:

1  <activity 2                android:name = "com.example.testregister.ShowTest">3             <intent-filter >4                 <action android:name="android.intent.action.VIEW" />5 6                 <category android:name="android.intent.category.DEFAULT"/>7                 8             </intent-filter>9         </activity>

Because network interaction is involved, you also need to add network conditions and configure them in the configuration file:

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

When talking about the php implementation interface, I will first show you my local database and the data in it.

Database:

Added data:

PHP code:

First, create a database file Conn. php.

1 <? Php 2 // the root password for connecting to the local database localhost and database account is blank 3 $ con = mysql_connect ("localhost", "root ",""); 4 5 // set character set 6 mysql_query ("set names 'utf8'"); 7 mysql_query ("set character set utf8"); 8 9 if (! $ Con) {10 die (mysql_error (); 11} 12 mysql_select_db ("testregister", $ con); 13 // echo "test successful"; 14 15?>

The simple implementation of php code for accessing the database JSONPars. php:

1 <? Php 2 // used to connect to file 3 require 'conn. php '; 4 5 // output 6 $ result = mysql_query ("SELECT nickname, password FROM test_register order by user_id DESC") in reverse ORDER "); 7 // $ array = mysql_fetch_assoc ($ result); 8 // calculate the number of data entries 9 $ num = mysql_num_rows ($ result ); 10 // list the newly added data is output downward above. If $ I <3, only the first three 11 for ($ I = 0; $ I <$ num; $ I ++) {12 // print_r ($ array); 13 echo json_encode (mysql_fetch_assoc ($ result); 14} 15 16?>

Test the above PHP code to check whether the code is successful. If the following code is displayed, the code is successful. If not, an error is displayed.

As follows:

 

The basic implementation has been completed. If you do not understand anything or what is wrong with my article, please leave a message, I will reply immediately.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.