我试图学习有关MySQL的更多信息,并使用Java(在Android上)从WAMS服务器上的数据库访问和检索信息。我的应用程序的设置方式是它具有一个初始登录屏幕,该屏幕还捕获(从另一个表中)登录的用户名的“ uid”并进行存储。
登录后(功能正常- 我设置了一个敬酒通知,其中显示了登录用户的检索到的用户名和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”,”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”}
{“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”}
现在,我写了一些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
任何帮助或建议,将不胜感激。
在您的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"} ]