0

我开发了一个连接到远程 mysql 数据库的小应用程序,以便从中返回信息。我基本上使用的是与 mysql 数据库位于同一服务器上的 php 文件;php 文件根据应用程序的用户响应返回数据。这是它的外观(凭据除外):

<?php
mysql_connect("localhost" ,"my_user","my_password");
mysql_select_db('my_db'); 
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>

在 Android 端,代码如下所示:

package com.example.maltinololperson.asynctask;
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.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ReadWebpageAsyncTask extends Activity {
  private TextView textView;
  InputStream is = null;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.TextView01);
  }
  private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1980"));
        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.org/getAllPeopleBornAfter.php");
            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,"UTF-8"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");

               // Log.i("log_tag","Line reads: " + line); 
            }
            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")
                //);
            }
        }
        catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }
      return result;
    }
    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  }
public void readWebpage(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
 }
} 

一切正常,应用程序似乎完美地连接到服务器,但唯一的问题是返回的数据(在设备模拟上)采用以下形式:[{"id":"1200","name": "John smith", "Sex":"m","birthyear":"1980"},{"id":"7110","name":"Batman":,....}],我想要看起来像这样:id:1200,姓名:john smith,性别:m,birtheyear:1980等等。由于我是 Android 开发和 JSON 的新手,我无法找到实现这一目标的方法,任何帮助将不胜感激。

4

1 回答 1

1

查看此URL这正是您需要学习的内容。参考它,如果您有更多疑问,请告诉我。对于初学者来说,这是一个很棒的教程

于 2012-08-26T03:07:48.727 回答