【问题标题】:Android App connecting to mysql server is returning values enclosed in [] , {} and double quotes连接到 mysql 服务器的 Android 应用程序返回用 [] 、 {} 和双引号括起来的值
【发布时间】:2012-08-26 02:59:36
【问题描述】:

我开发了一个连接到远程 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":"蝙蝠侠":,.... }],我希望它看起来像这样:id : 1200, name: john smith, sex: m,birtheyear: 1980 等等。由于我是 Android 开发和 JSON 的新手,所以我无法找到实现这一目标的方法,我们将不胜感激。

【问题讨论】:

    标签: android mysql json android-asynctask


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2019-10-26
      • 2011-03-07
      • 1970-01-01
      • 2014-10-03
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多