如何在我的代码中实现ASyncTask

时间:2014-02-23 21:38:05

标签: java android android-asynctask

在我的应用程序中,我试图从在线文本文件中读取一个字符串,然后将内容保存到变量中。这是我目前的代码:

        download.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            try {
                URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
                Scanner s = new Scanner(site.openStream());
                String num = s.nextLine();
            }
            catch(MalformedURLException e) { 
                e.printStackTrace(); 
            }
            catch(IOException e) {
                e.printStackTrace();            
            }                    

            Toast.makeText(getApplicationContext(), "String from file is: " + num,
            Toast.LENGTH_LONG).show();  

        }
    }); 

然而,这给了我一股力量。这是日志:http://pastebin.com/2nsxmJz1 我相信我需要实现一个ASyncTask,但不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您无法在UI线程上使用网络通信。正确地提到你应该使用AsyncTask来解决这些问题:

final AsyncTask<Object,Object,String> task = new AsyncTask<Object,Object,String>() {
   protected String doInBackground(Object... o) {
        try {
            URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
            Scanner s = new Scanner(site.openStream());
            return s.nextLine();
        }
        catch(MalformedURLException e) { 
            throw new RuntimeException("Incorrect URL", e);
        }
        catch(IOException e) {
            throw new RuntimeException("Can't fetch file content from url", e);
        }   
   }

   protected void onPostExecute(String r) {
       Toast.makeText(getApplicationContext(), "String from file is: " + r,
        Toast.LENGTH_LONG).show();  
   }
};
task.execute();