【发布时间】:2015-01-31 22:40:13
【问题描述】:
我有一个问题要问你。似乎周围有类似的问题,但对我没有用。我使用 AsynkTask 来解析 JSON 对象,然后我想将结果提供给一些组件,例如 TextViews 和 Buttons。虽然我花了几个小时测试示例,但我无法让它工作。 起初我在 doInBackground() 中进行了解析:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
@Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/consumer.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
// Convert response to String
String result = EntityUtils.toString(response.getEntity());
// TEST
//postResponse = EntityUtils.toString(resEntity).trim();
// CONVERT RESPONSE STRING TO JSON Object
JSONObject json = new JSONObject(result);
// Get the JSONArray "Consumer"
JSONArray ja = json.getJSONArray("Consumer");
//List<String> detailsList = new ArrayList<String>();
// Creating the array that will hold the json items
String[] info = new String[ja.length()];
// Loop through all fields
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("userid");
String fname = c.getString("userfullname");
String tel1 = c.getString("tel1");
String email = c.getString("email");
String address = c.getString("address");
String county = c.getString("county");
String country = c.getString("country");
String rpoints = c.getString("RedeemPoints");
String level = c.getString("Level");
// Add JSON object into the ArrayList
//detailsList.add(name);
// show the values in our logcat
Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints);
}
//Log.v(TAG, "Testing response: " + postResponse);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
@Override
protected void onPostExecute(String postResponse) {
// do stuff after posting data
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
//listener.onFailedLogin(postResponse);
Toast.makeText(getBaseContext(),
"Response is empty", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(),
"Got results!!", Toast.LENGTH_LONG).show();
//name.setText(fname);
}
}
}
这不起作用所以我尝试在 onPostExecute() 中进行解析,如 this 所示再次没有运气...:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
EditText name = (EditText) findViewById(R.id.name);
// do stuff before posting data
}
@Override
protected String doInBackground(String... params) {
String result = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/consumer.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("ConsumerID", "52"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
// Convert response to String
postResponse = EntityUtils.toString(resEntity).trim();
//Log.v(TAG, "Testing response: " + postResponse);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
@Override
protected void onPostExecute(String result) {
// do stuff after posting data
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
//listener.onFailedLogin(postResponse);
Toast.makeText(getBaseContext(),
"Response is empty", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(),
"Got results!!", Toast.LENGTH_LONG).show();
// TEST
//postResponse = EntityUtils.toString(resEntity).trim();
// CONVERT RESPONSE STRING TO JSON Object
try {
JSONObject json = new JSONObject(result);
// Get the JSONArray "Consumer"
JSONArray ja = json.getJSONArray("Consumer");
//List<String> detailsList = new ArrayList<String>();
// Creating the array that will hold the json items
String[] info = new String[ja.length()];
// Loop through all fields
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("userid");
String fname = c.getString("userfullname");
String tel1 = c.getString("tel1");
String email = c.getString("email");
String address = c.getString("address");
String county = c.getString("county");
String country = c.getString("country");
String rpoints = c.getString("RedeemPoints");
String level = c.getString("Level");
name.setText(fname);
// Add JSON object into the ArrayList
//detailsList.add(name);
// show the values in our logcat
Log.v(TAG, "User ID: " + id + "\n"+ "Username: "+ fname + "\n"+ "Redeem points: "+rpoints);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
我不明白。什么是不工作?你检查解析和下载json了吗?这是正确的吗?或者它是正确的,但在
onPostExecute中存在问题? -
你有没有发现异常?
-
Kirill 一切正常,除了 TextViews...我真的不知道为什么我不能设置文本...
标签: android json android-asynctask textview