基本上这里我使用url连接到php,一切都是在登录和注册阶段找到的工作,现在我想获取我在php文件中创建的json对象,然后在字符串视图中显示它,所以有人对此有想法吗?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
dataField = (TextView) findViewById(R.id.data);
btnDis = (Button) findViewById(R.id.btnClick);
btnDis.setOnClickListener (new View.OnClickListener(){
@Override
public void onClick(View v){
strUrl ="http://10.0.2.2/android/display.php";
new jsonParse().execute();
}
});
}
public class jsonParse extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(EditActivity.this,""+result,Toast.LENGTH_LONG ).show();
}
@Override
protected String doInBackground(String... params) {
try{
URL url = new URL (strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.connect();
//get response from server
BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
String value = bf.readLine();
System.out.println("result is"+value);
result = value;
String finalJson = bf.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
JSONObject finalObject= parentArray.getJSONObject(0);
String username = finalObject.getString("NAME");
String age = finalObject.getString("AGE");
String result = username +" - "+age;
return result;
}
catch(Exception e){
System.out.println(e);
}
return null;
}
}
}
下面是我的php文件display.php
<?php
require "conn.php";
require_once "global.php";
//get record from databases
$query = "SELECT * FROM user";
if($result = mysqli_query($conn, $query)){
// printf("%d", mysqli_num_rows($result));
if(mysqli_num_rows($result) > 0){
$status = 'true';
$message = 'data retrieved successfully';
while($row = mysqli_fetch_assoc($result)){
$name = $row['name'];
$age = $row['age'];
$username = $row['username'];
// echo $name."\n\n";
// echo $age."\n\n";
// echo $username."\n\n";
$data .= '{"NAME" : "'.$name.'", "AGE" : "'.$age.'", "USERNAME" : "'.$username.'"},';
}
}else{
$status = 'false';
$message = 'data retrieved failed';
$data = '';
}
mysqli_free_result($result);
mysqli_close($conn);
}else{
$message = mysqli_error($conn);
}
$output = '{"status": "'.$status.'","message":"'.$message.'", "data": ['.rtrim($data, ',').']}';
echo $output;
?>
4条答案
按热度按时间dtcbnfnu1#
您可以使用Java库GSON https://github.com/google/gson。
要将json格式转换为java String.class,请编写:
z31licg02#
在回调进入onPostExecute之后,String参数可能是键-值对。因此要将String转换为JsonObject,请使用-
lmvvr0a83#
1.您可以使用
数据字段. setText(结果);
在onPostExecute()上
1.为了方便地从远程访问数据,可以使用POJO类的概念。
首先创建一个POJO类,如下所示
然后通过以下方式检索数据
xqnpmsa84#