我試圖通過使用HttpGet和HttpClient從互聯網獲取數據。但是,當我在仿真器中運行它時,它立即關閉並說「不幸的是,AppName已停止」。任何想法如何解決這個問題?嘗試從互聯網獲取數據時Android App停止
驗證碼:
public class MainActivity extends Activity {
final String httpPath = "http://www.google.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtContent = (TextView) findViewById(R.id.txtContent);
TextView tvHttp = (TextView) findViewById(R.id.tvHttp);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(httpPath);
try {
HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
tvHttp.setText(stringBuilder.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
AssetManager assetManager = getAssets();
// To load text file
InputStream input;
try {
input = assetManager.open("dummytext.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
txtContent.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
logcat的:
03-08 03:31:17.762: D/AndroidRuntime(892): Shutting down VM
03-08 03:31:17.762: W/dalvikvm(892): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-08 03:31:17.952: E/AndroidRuntime(892): FATAL EXCEPTION: main
03-08 03:31:17.952: E/AndroidRuntime(892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appname/com.example.appname.MainActivity}: android.os.NetworkOnMainThreadException
如何將它移動到AsyncTask? – user2146966 2013-03-08 04:04:05
我提供的鏈接有關於'AsyncTask'的所有基本信息。一旦你知道了,移動'doInBackground()'中與'Http'(** Internet **)相關的所有代碼片段,並在'onCreate()'中調用'AsyncTask'的execute()'。 – SudoRahul 2013-03-08 04:07:03
檢查[這個例子](http://www.javasrilankansupport.com/2012/11/asynctask-android-example-asynctask-in.html),如果你喜歡。 – SudoRahul 2013-03-08 04:08:05