Android应用程序停止时尝试获取来自互联网的数据 [英] Android App stopped when try to fetch data from internet

查看:126
本文介绍了Android应用程序停止时尝试获取来自互联网的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用HTTPGET和HttpClient的获取从互联网上的数据。然而,当我在模拟器中运行它,它立即关闭说:不幸的是,AppName的已经停止。任何想法如何解决这个问题?

的code:

 公共类MainActivity延伸活动{    最后弦乐httpPath =htt​​p://www.google.com
    @覆盖
    保护无效的onCreate(捆绑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的=新DefaultHttpClient();
        HTTPGET HTTPGET =新HTTPGET(httpPath);
        尝试{            HttpEntity httpEntity = httpclient.execute(HTTPGET).getEntity();           如果(httpEntity!= NULL){
            为InputStream的InputStream = httpEntity.getContent();
            的BufferedReader的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream的));
            StringBuilder的StringBuilder的=新的StringBuilder();            串线= NULL;            而((行= bufferedReader.readLine())!= NULL){
                stringBuilder.append(行+\\ n);
            }            inputStream.close();            tvHttp.setText(stringBuilder.toString());
           }        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
            Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
            Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
      }
AssetManager assetManager = getAssets();
//加载文本文件
输入的InputStream;
尝试{
    输入= assetManager.open(dummytext.txt);     INT大小= input.available();
     字节[]缓冲区=新的字节[大小]
     input.read(缓冲液);
     input.close();     //字节的缓冲区转换为字符串
     字符串文本=新的String(缓冲);     txtContent.setText(文本);
}赶上(IOException异常五){
    // TODO自动生成catch块
    e.printStackTrace();}}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

LogCat中:

  3月3日至8日:31:17.762:D / AndroidRuntime(892):关闭VM
3月3日至8日:31:17.762:W / dalvikvm(892):主题ID = 1:螺纹未捕获的异常退出(组= 0x40a71930)
3月3日至8日:31:17.952:E / AndroidRuntime(892):致命异常:主要
3月3日至8日:31:17.952:E / AndroidRuntime(892):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.appname / com.example.appname.MainActivity}:android.os.NetworkOnMainThreadException


解决方案

android.os.NetworkOnMainThreadException

这意味着,你正在做你的主UI 线程与网络相关的调用。

所有的 HTTP 的onCreate()已被移动到的 的AsyncTask

I'm trying to fetch data from the internet by using HttpGet and HttpClient. However, when I run it in my emulator it immediately shutdown saying "Unfortunately, AppName has stopped". Any ideas how to solve this?

The Code:

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

This means that you are doing network related calls on your Main UI thread.

All Http related calls in your onCreate() have to be moved to an AsyncTask.

这篇关于Android应用程序停止时尝试获取来自互联网的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆