我有一个AsynTask从Web服务检索数据并在UI上查看这些数据。所以,在我的MainActivity中,我有一个textView。如何让一个TextView显示一个AsynTask类的值
这是我从Web服务接收到的数据:
{"name":"ezio","country":"italy"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}
的问题是,我不知道如何与“结果”从ClientConnection类值设置TextView的。当我运行应用程序时,textView是空的。
公共类ClientConnection扩展的AsyncTask {
public static final String URL = "http://192.168.0.15/test.php";
static JSONObject jObj = null;
public static String result = "";
@Override
protected String doInBackground(Void... voids) {
// public JSONObject connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("HTTPStatus error:","Status not okay");
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
JSONObject jsonObject = convertToJson(result);
// jsonObject.get()
//result = jsonObject.getString("name");
//JSONArray google = jsonObject.getJSONArray("");
} catch (Exception e) {
//Toast toast = Toast.makeText(null, e.getMessage(), Toast.LENGTH_LONG);
Log.e("Error","don't know what exception though");
}
return result;
}
private JSONObject convertToJson(String test){
JSONArray clients = new JSONArray();
try{
jObj = new JSONObject(test);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jObj;
}
public String getResult(){
return result;
}
public JSONObject getjObj(){
return jObj;
}
}
这是主要的活动
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.textViewTest);
ListView listView = (ListView) findViewById(R.id.listView);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
final ClientJSONParsingActivity clientJSONParsingActivity = new ClientJSONParsingActivity();
buttonConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ClientConnection().execute();
textView.setText(new ClientConnection().getResult());
}
});
}
}
谢谢您的帮助
我已经按照你们所有人的建议添加了这段代码。这是它, 保护无效onPostExecute(字符串结果){ MyActivity活动=新的MyActivity(); activity.setTextView(getResult()); } 这与我现在的textview显示{“name”:“ezio”,“country”:“italy”} {“name”:“fufu”,“country”:“tutu”} {“name” :“chikaka”,“country”:“aceVentura”} 但是,我不太确定这是不错的编码,因为我正在为主要活动创建一个新的参考。没有专门为Android执行这些任务的方法吗? – mokko211
如果您只需要JSON对象中的一个值,那么为什么不将字符串解析为JSON对象 - 并非整个StringBuilder – vodich