Android之網路編程利用PHP操作MySql插入資料(四),androidmysql

來源:互聯網
上載者:User

Android之網路編程利用PHP操作MySql插入資料(四),androidmysql

  因為最近在更新我的項目,就想著把自己在項目中用到的一些的簡單的與網路互動的方法總結一下,所以最近Android網路編程方面的博文會比較多一些,我盡量以最簡單的方法給大家分享,讓大家明白易懂。如果有什麼不對的地方,還請大家留言指出。

  這次是利用PHP操作MySql,將Android上面輸入的資料插入到MySql中,這裡我已經給大家寫好了PHP端的代碼,如果大家想要自己測試,只需要將php端的代碼複製即可,Android端的代碼得換包。OK,下面我先給大家貼出來:

Android端:

MySql資料庫:

執行程式之後的資料庫:

Android端的代碼:

MainActivity類:

 1 package com.example.insertphp; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 import org.apache.http.NameValuePair; 7 import org.apache.http.message.BasicNameValuePair; 8 import org.json.JSONObject; 9 10 import android.app.Activity;11 import android.os.Bundle;12 import android.os.StrictMode;13 import android.util.Log;14 import android.view.View;15 import android.view.View.OnClickListener;16 import android.widget.Button;17 import android.widget.EditText;18 19 public class MainActivity extends Activity {20 21     //聲明介面地址22     private String url = "http://10.17.64.8:8080/testregister/register.php";23     24     private String a;25     private String b;26     27     private EditText et1;28     private EditText et2;29     private Button btn;30     31     32     33     @Override34     protected void onCreate(Bundle savedInstanceState) {35         super.onCreate(savedInstanceState);36         setContentView(R.layout.activity_main);37         38         et1 = (EditText) findViewById(R.id.edtv);39         et2 = (EditText) findViewById(R.id.edt);40         btn = (Button) findViewById(R.id.bt);41         42         btn.setOnClickListener(new OnClickListener() {43             44             @Override45             public void onClick(View arg0) {46                 47                 List<NameValuePair> params = new ArrayList<NameValuePair>();48                 //擷取輸入框中的內容49                 a = et1.getText().toString();50                 b = et2.getText().toString();51                 52                 //替換索引值對,這裡的鍵必須和介面中post傳遞的鍵一致53                 params.add(new BasicNameValuePair("name", a));54                 params.add(new BasicNameValuePair("password", b));55                 56                 JSONParser jsonParser = new JSONParser();57                 58                 try{   59                     JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);60                     Log.v("uploadsucceed", "uploadsucceed");   61                   62                 }catch(Exception e){   63                     e.printStackTrace(); 64                 }   65                 66                 67                 System.out.println("輸入的第一個內容:" + a);68                 System.out.println("輸入的第二個內容:" + b);69                 70             }71         });72         73         //下面的代碼是必須加上的,具體的意義還需要大家去探索吧,這裡不是主要講的74         75         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()    76         .detectDiskReads()    77         .detectDiskWrites()    78         .detectNetwork()   // or .detectAll() for all detectable problems    79         .penaltyLog()    80         .build());    81         82         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()    83         .detectLeakedSqlLiteObjects()    84         .detectLeakedClosableObjects()    85         .penaltyLog()    86         .penaltyDeath()    87         .build());   88         89     }90 91 }

注意:這裡的介面地址是我個人的本機伺服器的地址,你如果在自己電腦上測試必須更改地址,查看自己本地的地址方法:win鍵+R 然後輸入cmd,之後在執行框中輸入ipconfig/all,在執行之後的結果中招IPv4就可以了。testregister是我的項目包,register.php是我的php檔案。

特別注意:在將資料添加在list中時,索引值對中的鍵名必須與介面中POST傳遞的名稱一致才可以,不然會出現空資料的情況。

下面的代碼是使用網路編程串連服務端的,其中裡面代碼的意義我在http://www.cnblogs.com/bingbingliang-xiaomonv/p/5247223.html已經介紹過。

JSONParser類代碼:

 1 package com.example.insertphp; 2  3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.UnsupportedEncodingException; 8 import java.util.List; 9 10 import org.apache.http.HttpEntity;11 import org.apache.http.HttpResponse;12 import org.apache.http.NameValuePair;13 import org.apache.http.client.ClientProtocolException;14 import org.apache.http.client.entity.UrlEncodedFormEntity;15 import org.apache.http.client.methods.HttpPost;16 import org.apache.http.impl.client.DefaultHttpClient;17 import org.apache.http.protocol.HTTP;18 import org.json.JSONException;19 import org.json.JSONObject;20 21 import android.util.Log;22 23 public class JSONParser {24 25     static InputStream is = null;   26     static JSONObject jObj = null;   27     static String json = "";   28     // constructor   29     public JSONParser() {   30     }     31     public JSONObject makeHttpRequest(String url, String method,   32     List<NameValuePair> params) {   33         // Making HTTP request   34         try {   35             //使用POST請求 36             DefaultHttpClient httpClient = new DefaultHttpClient();   37             HttpPost httpPost = new HttpPost(url);   38             httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));   39             HttpResponse httpResponse = httpClient.execute(httpPost);   40             HttpEntity httpEntity = httpResponse.getEntity();   41             is = httpEntity.getContent();   42         } catch (UnsupportedEncodingException e) {   43             e.printStackTrace();   44         } catch (ClientProtocolException e) {   45             e.printStackTrace();   46         } catch (IOException e) {   47             e.printStackTrace();   48         }   49         try {   50             BufferedReader reader = new BufferedReader(new InputStreamReader(   51             is, "UTF-8"));   52             StringBuilder sb = new StringBuilder();   53             String line = null;   54             while ((line = reader.readLine()) != null) {   55             sb.append(line + "\n");56         }   57             is.close();   58             json = sb.toString();   59         } catch (Exception e) {   60             Log.e("Buffer Error", "Error converting result " + e.toString());   61             Log.d("json", json.toString());   62         }   63             //轉變為Json類型   64         try {   65             jObj = new JSONObject(json);   66         } catch (JSONException e) {   67             Log.e("JSON Parser", "Error parsing data " + e.toString()); 68         }   69             // return JSON String   70             return jObj;   71     }   72     73 }

注意:必要忘了在設定檔添加訪問網路許可權的代碼:

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

布局代碼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 10     <EditText11         android:id="@+id/edtv"12         android:layout_width="match_parent"13         android:layout_height="wrap_content"14         android:ems="10" >15 16         <requestFocus />17     </EditText>18 19     <EditText20         android:id="@+id/edt"21         android:layout_width="match_parent"22         android:layout_height="wrap_content"23         android:ems="10" />24 25     <Button26         android:id="@+id/bt"27         android:layout_width="wrap_content"28         android:layout_height="wrap_content"29         android:text="提交" />30 31 </LinearLayout>

 

服務端代碼:

Conn.php(串連資料庫的代碼):

 1 <?php 2     //串連本機資料庫localhost以及資料庫賬戶root密碼為空白 3     $con = mysql_connect("localhost","root",""); 4  5     //設定字元集 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 "測試成功";14 15 ?>

操作資料庫的代碼:

register.php:

 1 <?php 2      3     require 'Conn.php'; 4  5     $response = array(); 6  7     //注意:這裡的POST傳遞的name必須和android端的鍵一致,否則不會插入資料 8     if(isset($_POST['name'])){ 9         $nickname = $_POST['name'];10         $password = $_POST['password'];11         //執行Mysql插入語句12         $query = mysql_query("INSERT INTO test_register(nickname,password) VALUES ('$nickname','$password')");13     // echo $query;14     // echo "測試query";15         if ($query) {   16                 // successfully inserted into database   17                 $response["success"] = 1;   18                 $response["message"] = "Product successfully created.";   19                 echo json_encode($response);   20                       21                 } else {   22                     // failed to insert row   23                     $response["success"] = 0;   24                     $response["message"] = "Oops! An error occurred.";   25                     // echoing JSON response   26                     echo json_encode($response);   27                 }   28 29     }30 31 ?>

說明:echo只是為了當時測試用的。

如果在執行程式的過程中Logcat中出現下面情況,就差不多對了。

為了測試方便我使用的是英文,如果有使用中文的,上述代碼也可以,如果你的不可以的話,你就更改你的編碼方式,我這裡是用的UTF-8,這是最普遍的,一般不會出現問題。

  本人的水平有限,就先寫這些了,如果有什麼問題,或者更好的方法,還需要大神留言。我感激不盡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.