Android Network Programming Using PHP to operate MySql to insert data (4), androidmysql

Source: Internet
Author: User
Tags mysql insert

Android Network Programming Using PHP to operate MySql to insert data (4), androidmysql

Because I recently updated my project, I want to summarize some simple methods of interacting with the network that I used in the project, so there will be more blog posts on network programming for Android recently. I will try my best to share it with you in the simplest way to make it easy to understand. If there is anything wrong, please leave a message to point out.

This time I used PHP to operate MySql and inserted the data input on Android to MySql. Here I have written the PHP code for you. If you want to test it by yourself, you only need to copy the php code and replace the Android code. OK. I will post it to you first:

Android:

MySql database:

Database after the program is executed:

Android code:

MainActivity class:

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 // declare the interface address 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 // obtain the content in the input box 49 a = et1.getText (). toString (); 50 B = et2.getText (). toString (); 51 52 // Replace the key-value pair. The key here must be consistent with the key passed by post in the interface 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 ("the first input content:" + a); 68 System. out. println ("the second input content:" + B); 69 70} 71}); 72 73 // the following code must be added, we still need to explore the specific significance. Here is not the main 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}

Note:The interface address here is the address of my local server. If you have to change the address on your computer, check your local address: win key + R and Enter cmd, enter ipconfig/all in the execution box, and then recruit IPv4 in the execution result. Testregister is my project package, and register. php is my php file.

Note:When adding data to the list, the key name in the key-value pair must be the same as the name passed by POST in the interface. Otherwise, empty data may occur.

The following code uses network programming to connect to the server. The meaning of the Code is described at http://www.cnblogs.com/bingbingliang-xiaomonv/p/5247223.html.

JSONParser class code:

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. clientProtocol Exception; 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 jO Bj = 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 // use POST request 36 DefaultHttpClient httpClient = new DefaultHttpClient (); 37 HttpPost httpPost = new HttpPost (url); 38 httpPost. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8 )); 39 HttpResponse httpResponse = httpClient.exe cute (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 // convert to Json Type 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}

Note: you must forget to add the network access permission code in the configuration file:

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

Layout code 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 = "Submit"/> 30 31 </LinearLayout>

 

Server code:

Conn. php (database connection code ):

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?>

Database operation code:

Register. php:

1 <? Php 2 3 require 'conn. php '; 4 5 $ response = array (); 6 7 // Note: The name passed by POST must be the same as the android key, otherwise, data will not be inserted 8 if (isset ($ _ POST ['name']) {9 $ nickname =$ _ POST ['name']; 10 $ password = $ _ POST ['Password']; 11 // execute Mysql INSERT statement 12 $ query = mysql_query ("insert into test_register (nickname, password) VALUES ('$ nickname',' $ password') "); 13 // echo $ query; 14 // echo" test query "; 15 if ($ query) {16 // successfully inserted int O 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?>

Note: echo was only used for testing at the time.

If the following problem occurs in Logcat during the execution of the program, it is almost correct.

For the convenience of testing, I use English. If you use Chinese, the above Code is also acceptable. If you cannot, you can change your encoding method, I am using a UTF-8 here, this is the most common and generally will not have a problem.

If I have a limited level, I should write this first. If there is any problem or a better method, I still need to leave a message. I am very grateful.

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.