簡體   English   中英

嘗試從互聯網獲取數據時,Android App已停止

[英]Android App stopped when try to fetch data from internet

我正在嘗試使用HttpGet和HttpClient從Internet上獲取數據。 但是,當我在模擬器中運行它時,它會立即關閉,並顯示“不幸的是,AppName已停止”。 任何想法如何解決這個問題?

編碼:

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

android.os.NetworkOnMainThreadException

這意味着您正在Main UI線程上進行與網絡相關的調用。

onCreate()所有與Http相關的調用都必須移至AsyncTask

    class DownloadTask extends AsyncTask<Void,Void,Void>
{
  protected void onPreExecute() 
  {
  super.onPreExecute();  
    //show progress dialog()
  }

 @Override
 protected Void doInBackground(Void... params) {
   //get data form internet here
   // put all downloading related code in a method getDownload()
   // call  getDownload() here
 return null;
 }

 @Override
  protected void onPostExecute(Void result) {
  super.onPostExecute(result);
   //dismiss dialog update ui here
   // uodate ur ui with the downloaded data here
   }
 }

使用上面的AsyncTask

作為替代方案,您可以查看githup中的該開源項目,該項目使用robospice進行長時間運行。 https://github.com/octo-online/robospice

是vogela的一個很好的例子,用於了解如何在android中使用AsynckTask。

您可以扔掉它,並將您的網絡相關調用放在該任務的doBackground中。

希望你明白了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM