【问题标题】:Android App stopped when try to fetch data from internetAndroid 应用程序在尝试从互联网获取数据时停止
【发布时间】:2013-02-23 13:15:33
【问题描述】:

我正在尝试使用 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 httpclient http-get


    【解决方案1】:

    android.os.NetworkOnMainThreadException

    这意味着您正在Main UI 线程上进行与网络相关的调用。

    您的onCreate() 中所有与Http 相关的调用都必须移至AsyncTask

    【讨论】:

    • 如何将其移至 AsyncTask?
    • 我提供的链接包含有关AsyncTask 的所有基本信息。一旦你知道了,移动所有与doInBackground() 中的Http(Internet) 相关的代码片段,并在你的onCreate() 中调用AsyncTaskexecute()
    • 如果您愿意,请查看this example
    • 我将所有与 http 相关的代码移动到 doInBackground() 中的异步任务中,并且我已经在我的 onCreate() 中执行了它,现在应用程序打开了,但过了一会儿它显示错误消息和再次关闭应用程序。而且我还没有成功地从互联网上获取数据以显示在我的文本视图中:(
    【解决方案2】:
        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.

    【讨论】:

      【解决方案3】:

      Here 是 vogela 了解如何在 android 中使用 AsynckTask 的绝佳示例。

      你可以扔掉它并将你的网络相关调用放在该任务的 doBackground 中。

      希望你明白了。

      【讨论】:

        猜你喜欢
        • 2012-09-22
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多