2

我想获取 Internet txt 文件的内容。当我用模拟器打开它时,我收到了这条消息

“不幸的是,应用程序已停止”。

如果删除“http://”,则什么也不会发生,但它不会读取任何内容并变为null. 怎么了?如何阅读上面的网址?我已添加权限。

这是我更改的整个代码,但仍然出现相同的错误。我做错了什么? http://dforum.zxq.net/code.txt

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... arg0) {



            try {
                URL url = new URL("http://dforum.zxq.net/myfile.txt");

                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();      
                    // str is one line of text; readLine() strips the newline character(s)
                }
                in.close();
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            }




            return null;
            // TODO Auto-generated method stub

        }


     }.execute();
}

@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;
}

}

4

2 回答 2

1

确保您不在 UI 线程上执行此操作,并检查您是否具有 Internet 权限。

这两种情况都可能导致让您的应用程序崩溃的异常。

下面是一个关于如何防止在 GUI 线程上进行网络操作的示例:

new AsyncTask<Void, Void, Void>{
    @Override
    protected Void doInBackground(Void... params) {

        // add your try catch block here.

        return null;
    }
}.execute();
于 2013-04-26T20:58:05.840 回答
0

Make sure you taking this process off the main UI thread by running it inside an AsyncTask. Check out this tutorial: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/. More specifically, check out the JSONParser class in there.

UPDATE

You are calling Toast in a while loop, which I think is the reason it's crashing. Replace it with Log.d() or System.out.println()

于 2013-04-26T21:14:26.077 回答