2013-04-26 108 views
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; 
} 

}

+0

请添加您的logcat输出。 – rekire 2013-04-26 20:59:20

+0

http://dforum.zxq.net/log.txt – 2013-04-26 21:13:33

回答

1

确保你不这样做,在UI线程上,并检查是否有互联网的权限。

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

下面是关于如何防止GUI线程做网络运营的例子:

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

     // add your try catch block here. 

     return null; 
    } 
}.execute(); 
+0

权限 <使用权限android:name =“android.permission .INTERNET“/> – 2013-04-26 21:08:31

+0

这是我的permisions,但我不知道什么是UI线程。我仍然得到这个错误 – 2013-04-26 21:09:20

+0

好吧,它会是线程的东西。将你的try catch块封装在一个异步任务中。我会将这些添加到我的答案中,请稍等片刻。 – rekire 2013-04-26 21:10:35

0

确保你运行它的AsyncTask内服用此过程中关闭主UI线程。看看这个教程:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/。更具体地说,查看那里的JSONParser类。

UPDATE

你调用一个while循环,我认为这是它崩溃的原因Toast。替换为Log.d()System.out.println()

+0

我做过所有你说的也加上这个 我写了上面的整个代码?那么为什么它再次关闭? – 2013-04-26 22:18:18

+0

如果日志输出不同,请更新您的答案。 – 2013-04-26 22:49:04

+0

尝试为AsyncTask创建一个内部类,而不像上面链接的教程那样。 – 2013-04-26 22:49:54