0

我正在尝试更多地了解 MySQL 并使用 Java(在 Android 上)从我的 WAMS 服务器上的数据库中访问和检索信息。我的应用程序的设置方式是它有一个初始登录屏幕,它还获取正在登录的用户名的“uid”(来自不同的表)并存储它。

登录后(这是功能性的 - 我设置了一个 toast 通知,显示检索到的用户登录用户名和 uid),它进入一个新屏幕(dashboard.xml),其中设置了一个 TextView 字段来显示检索到的数据(来自下面发布的表)与存储的“uid”相关联。这是我试图从中提取数据的表:

http://db.tt/4izVQuGB

现在,我已经设置了一个 PHP 文件,该文件在我的数据库中查询与特定“uid”关联的行。我已经使用 HTML 表单测试了这个文件。

$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb)or die("database selection error");

//Retrieve the User ID
$uid = $_POST['uid'];

//Query
$query = mysql_query("SELECT * FROM node WHERE uid='$uid' AND type='goal'");

//store # of rows returned
$num_rows = mysql_num_rows($query);

if ($num_rows >= 1) {
    while($results=mysql_fetch_assoc($query)) {
        //Store the returned data into a variable
        $output = $results;

        //encode the returned data in JSON format
        echo json_encode($output);
    }
    mysql_close();
}

我通过使用 uid 值为 1 测试 PHP 文件得到的结果是:

{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status ":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky": "1","tnid":"0","翻译":"0"}

{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status ":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky": "1","tnid":"0","翻译":"0"}

{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status ":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky": "1","tnid":"0","翻译":"0"}

{"nid":"9","vid":"9","type":"goal","language":"","title":"跑到山上","uid":"1" “状态”:“1”,“已创建”:“1343604338”,“已更改”:“1343605100”,“评论”:“2”,“提升”:“0”,“中等”:“0”,粘性":"0","tnid":"0","翻译":"0"}

现在,我已经编写了一些 android 代码来设置 httppost 并应该在我的数据库表中检索“标题”。我知道这是错误的(显然因为它不起作用),但我对下一步该做什么感到困惑。

import java.io.BufferedReader;
import java.io.IOException;
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.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Dashboard extends Activity implements OnClickListener {

    // variable declarations
    String uid = "1";

    // create textview to display retrieved data
    TextView display;

    HttpClient httpclient;
    HttpPost httppost;
    HttpResponse httpresponse;
    HttpEntity httpentity;

    ArrayList<NameValuePair> resultArray;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        display = (TextView) findViewById(R.id.test);

        // initialize HttpClient
        httpclient = new DefaultHttpClient();

        // initialize HttpPost
        httppost = new HttpPost("http://192.168.1.112/android/fetch.php");

        try {
        // Create new List
        List<NameValuePair> resultList = new ArrayList<NameValuePair>();
        resultList.add(new BasicNameValuePair("uid", uid));

        httppost.setEntity(new UrlEncodedFormEntity(resultList));

        httpresponse = httpclient.execute(httppost);

        httpentity = httpresponse.getEntity();

        InputStream instream = entity.getContent();

        try {
                            // store incoming stream in an array
            JSONArray jArray = new JSONArray(streamToString(instream));
            JSONObject jData = null;

            for (int i = 0; i < jArray.length(); i++) {
                jData = jArray.getJSONObject(i);
                String goals = jData.getString("title");
                display.setText(goals);
            }
        //} catch (JSONException e) {
            //Toast.makeText(this, "No entries found", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
                    .show();
        }

    } catch (Exception e) {
        e.printStackTrace();
        Notifications error = new Notifications();
        error.userPassErrorDialog();
    }

}

private static String streamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

在 Android 模拟器中测试时出现以下错误:

http://db.tt/2vg9MqYh

任何帮助或建议将不胜感激。

4

2 回答 2

0

在您的 Android 应用程序中,您需要一个 JSONArray:

// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));

但是,在您的 PHP 文件中,您只输出多个单独的 JSON 对象,而不是一个真正的数组。我认为,您应该首先将数据库中的所有项目收集到一个 PHP 数组中,然后只对其进行编码和输出一次。

我的 PHP 技能有点生疏,但我希望这个能奏效:

//store # of rows returned
$num_rows = mysql_num_rows($query);

if ($num_rows >= 1) {
    $output = array();

    while($results = mysql_fetch_assoc($query)) {
        // append row to output
        $output[] = results
    }

    mysql_close();  // shouldn't that be outside the if block?

    //encode the returned data in JSON format
    echo json_encode($output);
}

我希望输出是这样的(也许没有缩进):

[
    {"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
    {"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
    {"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
    {"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
]
于 2012-08-04T15:01:10.843 回答
0

问题在于JSON的编码和解码。从您的 JSON 响应看来,您正在从服务器接收 JSON 对象,也请尝试在此处验证您的 JSON 响应。在浏览器中运行您的 php 文件,在 JSON 验证器上复制整个响应并检查您收到响应的括号。

1. 如果您的响应以 '[' 开头,它是一个数组,如果它以 '{' 开头,它是一个 JSON 对象。在解析 JSON 时,您首先定义了 JSON 数组,但服务器响应是 JSON 对象。在使用 JSON 时,您必须在服务器端注意它将发送的响应格式,并且您必须在客户端注意接收到的响应格式。我正在为您发布示例脚本。

-> 服务器端

if (mysql_num_rows($result)>0){
$response["data"] = array();        //this is an array
while($row= mysql_fetch_array($result))
{
$data = array();      //here I have created another temp array
$data["name"] = $row["name"];         
$data["surname"] = $row["surname"];   

array_push($response["data"], $data);   //this makes an array of objects in the response
}}
}//endif
else{
echo "no input";
}}
mysql_close();
echo json_encode($response);    //and finally I echo it as an JSON object

因为这个 php 脚本将返回我一个对象数组的对象(不是有点复杂!!)下面是响应的格式

-> 验证的 JSON 响应

{
    "data": [
        {
            "name": "Setu",
             "surname": "Desai",
        }
     ]
}

并对此进行解码,我的客户站点脚本需要如下

-> 解析 JSON 对象

JSONObject snObject = new JSONObject(jsonString);
    JSONArray snArray = snObject.getJSONArray("data");
    for (int i = 0; i < snArray.length(); i++) {
        JSONObject snObject2 = snArray.getJSONObject(i);
        String surname = snObject2.getString("surname");
        surnamearray.add(surname);
    }

理解的简单方法是验证您的 JSON 响应并识别 JSON 数组和对象的位置,然后开始解码。

于 2014-03-23T21:10:54.057 回答