當我嘗試從網站讀取單行文本時,出現錯誤(NetworkOnMainThreadException)。我嘗試了一些東西,但目前爲止沒有任何工作。所以這裏是代碼,如果有人可以幫助。在清單中,我有互聯網許可,所以他不應該成爲問題。NetworkOnMainThreadException從網上讀取時
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Weather extends Activity {
Button button;
TextView t;
String result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
t = (TextView)findViewById(R.id.textView1);
}
public void myButtonClickHandler (View view) throws ClientProtocolException, IOException {
result = getContentFromUrl("http://url.com");
t.setText(result);
}
public static String getContentFromUrl(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null) {
InputStream inStream = entity.getContent();
String result = Weather.convertStreamToString(inStream);
inStream.close();
return result;
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
恩,請問我能舉個例子嗎? – HyperX 2012-02-25 08:58:47
你可以在http://www.vogella.de/articles/AndroidPerformance/article.html和http://www.xoriant.com/blog/mobile-application-development/android-async-task.html以及http://developer.android.com/resources/articles/painless-threading.html – 2012-02-25 10:15:26