【发布时间】:2017-12-20 21:20:51
【问题描述】:
public class Config {
public static final String DATA_URL = "http://192.168.1.2/retrieveone.php?id=";
public static final String KEY_NAME = "BusinessName";
public static final String KEY_AmountTotal = "AmountTotal";
public static final String KEY_RT = "RequiredTotal";
public static final String KEY_MT = "MaxTotal";
public static final String JSON_ARRAY = "result";
}
这是我的类文件。
private void getData(){
String id = TempItem.toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
String url = Config.DATA_URL+TempItem.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(KPDetails.this,error.toString(),Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
int socketTimeout =50000;//5 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject stallsData = result.getJSONObject(0);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
}
Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
这是我从 mysql 数据库中获取数据的构造函数。但是,我设法获得了 setText,但没有获得 config 中字符串的值。
这是我的 php 文件。
?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('conn.php');
$sql = "SELECT * FROM business WHERE BusinessID='".$id."'";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"BusinessName"=>$res['BusinessName'],
"AmountTotal"=>$res['AmountTotal'],
"RequiredTotal"=>$res['RequiredTotal'],
"MaxTotal"=>$res['MaxTotal']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($conn);
}
"http://localhost/retrieveone.php?id=1" 工作得很好,但该值没有出现在我的 setText 中。 我是 Android Studio 的初学者。任何帮助表示赞赏。提前致谢。
编辑:
这是我的错误。 java.lang.String类型的值连接无法转成JSONObject
【问题讨论】:
-
你能显示你的 JSONObject 的输出吗?
-
@Mahdi.Pishguy 你标记错人了,我不是发布问题的人:)
-
@HahaHehe 您解析的 json 不正确请在
e.printStackTrace();之后添加Log.e("error ",e.getMessage())并再次运行应用程序以查看 Logcat 上发生的情况 -
@HemantSangle 对不起,先生,谢谢
-
java.lang.String类型的值连接无法转成JSONObject
标签: php android android-studio