java - Android - 连接到 MySQL 数据库

标签 java android mysql json

<分区>

我一直在尝试各种网站上显示的有关将 MySQL 数据库连接到 android 的教程。目前下面的代码采用您硬编码的值(即 year=2005 和 name=tom)并通过 php 脚本运行它。我想知道的是如何修改它,以便它采用用户在文本框中输入的值。

 package com.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


public class test extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources 
    // but since its an example saves declaring them in the XML. 
    LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
    txt = new TextView(getApplicationContext()); 
    rootLayout.addView(txt); 
    setContentView(rootLayout); 

    // Set the text and call the connect function. 
    txt.setText("Connecting...");
  //call the method to run the data retrieval
    txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://***.****.com/mysqlcon.php"; //i use my real ip here



private String getServerData(String returnString) {

   InputStream is = null;

   String result = "";
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year","2005"));
    nameValuePairs.add(new BasicNameValuePair("name","tom"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear")
                    );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);
            }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return returnString;
}   

}

最佳答案

好的,我明白你想要什么。你想在应用程序中有一个或两个 EditText。用户将在其中输入信息,按下按钮后,EditText 中的信息应移至 mysql 数据库中。所以,你想制作一个动态应用程序,将记录插入到 mysql 中。为此,请执行以下操作以修改上述 java 代码。

在下面插入以下行,TextView txt;

EditText editTxt;

rootLayout.addView(txt);下面插入两行,

editTxt = new EditText(this);
rootLayout.addView(editTxt); 

现在,修改这一行,nameValuePairs.add(new BasicNameValuePair("name","tom")); 从 EditText 获取值。

nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()));

您也可以为一年创建一个。

关于java - Android - 连接到 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4707656/

相关文章:

javascript - Swagger:第一个枚举值覆盖类型

java - Slick2D 和 JBox2D。如何绘制

java - Spring AnnotationFormatterFactory 与 Thymeleaf th :text, 仅在字段显式为字符串时格式化

java - Hibernate session.save() 总是返回 1

java - 使用自定义适配器将项目添加到自定义 ListView

mysql - 我们在表中保留了多少字段

java - 使用 IBM JDK 1.7.1 的 zLinux RHEL6 上的 Hive 1.1.0

android - AlertDialog 内的 DatePickerDialog(在特定的 EditText 上设置日期)

android - 经纬度为空@onMapReady

mysql - 如何将数据导入星型数据仓库。