2011-08-21 87 views
2

我无法使用URL类从Android工作区中的文件中读取文本。我得到一个NetworkOnMainThreadException。相同的确切代码在Android工作区以外工作,因此它必须是网络或权限问题。我从指定的链接生成了一个基本的文本文件。 它似乎在url.openStream上失败。 下面是我的代码,然后我的清单文件(其中我已经添加了应用的权限行。)Android无法从URL读取

static public String[] barList() 
{ 
    ArrayList<String> bars = new ArrayList<String>(); 
    try{ 
     URL url = new URL("****"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); 
     String line = br.readLine(); 
     while(line != null) 
     { 
      bars.add(line); 
      line = br.readLine(); 
     } 
     br.close(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return (String[])bars.toArray(); 
} 

这里是清单文件。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="aexp.explist"> 
<application> 
    <activity android:name=".ExpList" android:label="ExpList"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
</manifest> 
+1

是例外发生了什么暗示? 'e.getMessage()' – Mike

+0

由于某种原因,当我调试程序时,这个异常并没有引起注意。而不是把我带到catch块,它带我到一个“Class.class”文件。 – Glockstock

+1

发生这种情况并且您处于DDMS视角时,请单击绿色的“播放”按钮继续。如有必要,请多做几次,最终您应该在LogCat选项卡中看到堆栈跟踪。顺便说一下,我仅在Internet模拟器中测试了您的代码,但没有发现任何错误。 – Mike

回答

0

也许你流被拉: GZIPInputStream fails with IOException in Android 2.3, but works fine in all previous releases?

,如果你不使用缓冲输入流,可以读取URL内容?

此外,我经常使用url.getContent并将其转换为输入流,并且这可以工作,我不熟悉url.openStream。

问候, 斯特凡

+0

进一步检查时,它在url.openStream上失败。所以它在失败之前甚至没有达到BufferedInput代码。试图使用(InputStream)url.getContent也不起作用。在我看来可能是一个权限问题。也许从https网站阅读? – Glockstock

+0

你会得到一个权限异常,而不是一个ioexception。无论如何,你授予互联网许可给你的应用程序,它不应该是。 – Snicolas

0

您的代码正确运行,而无需如果我将其粘贴到和我的当前项目中运行它抛出一个异常。我瞄准sdk 4-8。