我正在尝试更多地了解MySQL并使用Java(在Android上)从我的WAMS服务器上的数据库中访问和检索信息。我的应用程序的设置方式是它有一个初始登录屏幕,它也抓取登录用户名的“uid”(来自不同的表)并存储它。
登录后(功能正常 - 我设置了一个显示检索到的用户名和登录用户的uid的Toast通知),它会进入一个新的屏幕(dashboard.xml),它有一个TextView字段设置来显示检索到的与存储的“uid”相关联的数据(来自下面发布的表)。这是我试图从中提取数据的表:
现在,我已经设置了一个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”, “类型”: “目标”, “语言”: “”, “标题”: “测试”, “UID”: “1” “状态”: “1”, “创造”: “1342894493”, “改变”: “1342894493”, “评论”: “2”, “推广”: “1”, “中庸”: “0”,”粘 “:” 1" , “tnid”: “0”, “翻译”: “0”}
{ “NID”: “2”, “VID”: “2”, “类型”: “目标”, “语言”: “”, “标题”: “TEST2”, “UID”: “1” “状态”: “1”, “创造”: “1342894529”, “改变”: “1342894529”, “评论”: “2”, “推广”: “1”, “中庸”: “0”,”粘 “:” 1" , “tnid”: “0”, “翻译”: “0”}
{ “NID”: “5”, “VID”: “5”, “类型”: “目标”, “语言”: “”, “标题”: “运行”, “UID”: “1” “状态”: “1”, “创造”: “1343506987”, “改变”: “1343506987”, “评论”: “2”, “推广”: “1”, “中庸”: “0”,”粘 “:” 1" , “tnid”: “0”, “翻译”: “0”}
{“nid”:“9”,“vid”:“9”,“type”:“目标”,“语言”:“”,“标题”:“跑到 丘陵”, “UID”: “1”, “状态”: “1”, “创建”: “1343604338”, “改变”: “1343605100”, “注释”: “2”, “促进”: “0” , “中等”: “0”, “粘”: “0”, “tnid”: “0”, “翻译”: “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模拟器中测试时出现以下错误:
非常感谢任何帮助或建议。
答案 0 :(得分: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"}
]
答案 1 :(得分:0)
问题在于JSON的编码和解码。从您的JSON响应看起来您正在从服务器接收JSON对象,请尝试验证您的JSON响应here。在浏览器中运行您的php文件,在JSON验证器上复制整个响应,并检查您收到响应的括号。
1.如果您的响应以'['它是和数组开头,如果它以'{'开头,它是一个JSON对象。在解析JSON时,您首先定义了JSON数组,但服务器响应是JSON对象。在使用JSON时,您必须在服务器端小心处理它将发送的响应格式,并且您必须在客户端小心处理您收到的响应格式。我正在为您发布示例脚本。
- &gt;服务器端
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脚本会返回一个对象数组的对象(位复杂不是!!)下面是响应的格式
- &gt;验证的JSON响应
{
"data": [
{
"name": "Setu",
"surname": "Desai",
}
]
}
要解码这个我的客户端站点脚本需要是以下
- &gt;解析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数组和对象的位置,然后开始解码。