我有一個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