微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 无法从MySQL表中检索与特定“uid”匹配的数据

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

登录后(功能正常 – 我设置了一个显示检索到的用户名登录用户的uid的Toast通知),它将进入一个新的屏幕(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″,”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″}

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

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

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

解决方法:

在您的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"}
]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐