嗨,当有人在编辑文本中输入 ID 时,我想从服务器获取数据,如果存在,则匹配的数据应该显示在 TextView 中。
我让它使用静态ID,所以可以说我在SELECT * FROM TABLE where id='1'
中得到了数字1,如果数字1
是在编辑文本中输入,就会显示数字 1 的数据。
null
通常显示在我的浏览器中。
但是现在我使用 $id=_REQUEST['id']
jsonparser 仅返回 NPE(NullPointerException),因为 jsonparser 显示错误:解析数据 org.json 时出错。 JSONException:类型 java.lang.String 的值 nulln 无法转换为 JSONObject
i 假设未触发查询。
我将向您展示我的 JSON Parser 类,以及我的 php.ini 的一部分。
<?php
$mysqli = new mysqli("host", "user", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id=$_REQUEST['id'];
$result = $mysqli->query("Select * From Table where id = '$id'");
while($row = mysqli_fetch_assoc($result)) {
$rows=$row;
}
echo json_encode($rows);
$result->close();
$mysqli->close();?>
Json 解析器类
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String id;
private static final String TAG_ID = "id";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", ""));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
最佳答案
首先,您的代码中存在 SQL 注入(inject)漏洞。未经验证,您不能在 sql 查询中使用任何变量!尝试使用 PDO http://php.net/manual/en/pdo.prepare.php .
其次,您似乎没有将正确的 ID 值从 Java 传输到 PHP,并且您正在搜索 ID = '' 的行。
第三,$rows = $row 不起作用。添加 $rows = array();在 while 之前,然后使用 $rows[] = $row;。
关于java - 通过 edittext SELECT 获取选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26697582/