我在服務器上有一個文本文件(現在在WAMP的本地服務器上,位於c:/wamp/www/android/sample.txt中)和一個帶有3個活動並通過WiFi讀取數據的android應用程序。 第一個獲得地址(在本地主機上使用10.0.2.2/android/sample.txt)並轉到activity2。在activity2中,我有一個按鈕進入activity3。爲什麼AsyncTask第一次不顯示結果?
代碼是第三個活動:
private InputStream OpenHttpConnection(String urlString) throws Exception {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("NOT an HTTP Connection!");
}
try {
HttpURLConnection httpCon = (HttpURLConnection) conn;
httpCon.setAllowUserInteraction(false);
httpCon.setInstanceFollowRedirects(true);
httpCon.setRequestMethod("GET");
httpCon.connect();
response = httpCon.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpCon.getInputStream();
Log.d("myerr", response + "");
}
} catch (Exception e) {
Log.d("myerr2", e.getLocalizedMessage());
throw new IOException("Error Connection!");
}
return in;
}
private String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String
.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_rh);
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
}
我也Global.java定義了一些全局變量。 這裏是我的問題: 第三項活動並未在第一次顯示textview上的數據。但是當我回到第二個活動,並按下我的數據加載按鈕。 爲什麼AsyncTask第一次不顯示結果以及如何解決這個問題?
感謝您的關注。
發表您的activty代碼按你的代碼中的錯誤可能是你從Global.readedDataFromFile閱讀文本,當所謂的異步任務postexecute你沒有設置文字 –
嘗試加載數據在postExecute –