我为我的Android应用程序创建了JSONPARSE数据。我使用LogCat能够使用Log.d(" id",id)查看Json响应,但是当我想将textview值设置为id时,它显示错误。请帮忙,谢谢。下面是我用于java和php的代码
以下是我的代码。
Log cat:
MainActivity.Java
private static String url_Retrieve = "http://hospital.leeyengyang.com/android_connect/Retrieve.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json2 = jsonParser.makeHttpRequest(url_Retrieve, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json2.toString());
try {
// Checking for SUCCESS TAG
int success2 = json2.getInt(TAG_SUCCESS);
if (success2 == 1) {
// products found
// Getting Array of Products
JSONArray Retrieve = json2.getJSONArray("tracking");
// looping through All Products
for (int i = 0; i < Retrieve.length(); i++) {
JSONObject c = Retrieve.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("Data");
String name = c.getString("Username");
Log.d("id", id);
Log.d("name", name);
// creating new HashMap
txtUpdate.setText(id);
// adding each child node to HashMap key => value
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Bluetooth.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
Retrive.php
<?php
// Locate WP Location
$location = $_SERVER['DOCUMENT_ROOT'];
include ($location . '/wp-config.php');
include ($location . '/wp-load.php');
include ($location . '/wp-includes/pluggable.php');
// array for JSON response
$response = array();
date_default_timezone_set('Asia/Kuala_Lumpur');
$date = date("Y-m-d");
$sql="SELECT Data,Username FROM tracking Where Username='jin' AND Date= '".$date."'";
// Initial Add data to HM
$result = mysql_query($sql) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tracking"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$tracking = array();
$tracking["Data"] = $row["Data"];
$tracking["Username"] = $row["Username"];
// push single product into final response array
array_push($response["tracking"], $tracking);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
JsonParser.Java
package com.example.Leeyengyang;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
答案 0 :(得分:0)
要将int值设置为TextView,请使用
txtUpdate.setText(""+id);
// OR
txtUpdate.setText(Integer.toString(id));
基本上你需要将int值转换为String。它不直接将int值设置为TextView。
确保您仅从主线程更新UI。
希望这有帮助!
感谢。
答案 1 :(得分:0)
您无法在UI线程外部更改用户界面(例如doInBackground()
的{{1}}方法)。
虽然 - 你仍然可以在onPostExecute中执行此更新,这在后台工作完成后调用,并在主(UI)线程上运行。
另外,考虑使用一个可以简化整个过程的库,如Jake Wharton&#39; s Retrofit:http://square.github.io/retrofit/
答案 2 :(得分:0)
SetText就是这样 runOnUiThread(new Runnable(){
@Override
public void run() {
txtUpdate.setText(id);
}
});
我希望这会对你有所帮助!