2013-05-14 142 views
0

我在服务器上托管的合作伙伴计算机中有一个文本文件。我试图检索我的Android应用程序中的文本文件中的所有字符串值。但是,我的应用程序不会输入while循环方法来读取文本文件。有没有办法解决它?我的电脑连接到我的合作伙伴服务器。Android应用程序while循环错误

该方法的代码。

connect.setOnClickListener(new View.OnClickListener(){ 
    public void onClick(View v){ 
     Thread trd = new Thread(new Runnable(){ 
      @Override 
      public void run(){ 
       //code to do the HTTP request 
       try { 
        URL url = new URL("insert url");//your website link 
        HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); 
        String line; 
        while((line = br.readLine()) != null){ 
         result.setText(line); 
        } 
        con.disconnect(); 
       } catch(IOException e) { 
        System.out.println("Error"); 
       } 
      } 
     }); 
     trd.start(); 
    } 
}); 
} 
+0

你是否在logcat中发生异常?像NetworkOnMainThreadException? – 2013-05-14 09:16:40

+0

nope,该应用程序有一个问题,试图追查我的文件或目录 – 2013-05-15 02:12:44

回答

0
while((line = br.readLine()) != null) { 

    result.setText(line); 

} 

结果不能从UI线程不同的线程运行。 使用

while((line = br.readLine()) != null) { 
final String finalLine = line; 

runOnUiThread(new Runnable() { 
@Override 
public void run() { 
     result.setText(finalLine); 
    } 
}); 
} 
+0

我得到了“无法引用一个不同的方法定义的内部类中的最终变量finalLine”错误 – 2013-05-14 08:33:42

+0

请参阅我的编辑。我添加了最后一个关键字 – Blackbelt 2013-05-14 08:38:26

+0

现在,在eclipse上进行调试后,在bufferedreader行之后,它立即跳转到catch catch行。应用程序没有进入while循环,可能是什么问题? – 2013-05-14 08:44:49

0

试试这个

URL url= new URL("insert url"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); 
    StringBuilder result= new StringBuilder(); 
       String line; 
       while ((line = br.readLine()) != null) { 
        result.append(line + "\n"); 
       } 

       TextView.setText(result); 
+0

它仍然无法正常工作。我的应用程序仍然无法跟踪我的合作伙伴服务器中的文件 – 2013-05-15 01:32:03

0

这是在HttpURLConnection con = (HttpURLConnection)url.openConnection();

你不应该在主线程从蜂窝及以上版本执行网络操作的时候打响了NetworkOnMainThreadException可能是因为这导致了这个错误。正因为如此,while循环从未被执行。

改为使用AsyncTask来执行网络操作。这里有一个链接:How to fix android.os.NetworkOnMainThreadException?

+0

我已经使用新的线程方法在另一个线程上运行连接 – 2013-05-15 01:33:02