无法在AsyncTask中运行onPostExecute,也可能无法获取doInBackground

时间:2016-02-17 17:02:04

标签: java android android-asynctask

我正在为我的一个班级设计一个应用程序。此应用程序的目标是连接到具有给定HTML的网站,并拉出某个文件。根据输入选择此文件,并创建新活动以在用户单击显示按钮时显示数据。

我的老师希望我们使用AsyncTask从html中提取数据,然后创建新活动。我之前从未遇到过AsyncTask的问题,但现在我无法运行onPostExecute。我把测试人员放在onPostExecute上并且他们从不运行,所以我认为我的doInBackground是问题所在。我还没有找到一个解决了我的问题的答案。

这是我的代码,问题发生在底部(是的,我有一个新的xml和java用于新活动,它在我的清单中)

 private class DownloadFilesTask extends AsyncTask<URL, Void, Integer> {
    @Override
    protected void onPreExecute() {
        Context context = getApplicationContext();
        CharSequence text = "Pulling Data";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    protected Integer doInBackground(URL... urls) {
        URL url = urls[0];
        int complete = 0;
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader isw = new InputStreamReader(in);

            int data = isw.read();
            while (data != 1) {
                char current = (char) data;
                data = isw.read();
                dataToPass += current;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            if (urlConnection != null)
                urlConnection.disconnect();

            if (!dataToPass.equals(""))
                complete = 1;

            return complete;
        }
    }


    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if(result == 1) {
            Context context = getApplicationContext();
            CharSequence text = "Result = 1";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            Intent intent = new Intent(HomeScreen.this, Stock_Data.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(STOCK_DATA, dataToPass);
            startActivity(intent);
        }
        else
        {
            Context context = getApplicationContext();
            CharSequence text = "Result != 1";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            TextView homeMessage = (TextView) findViewById(R.id.homeMessage);
            homeMessage.setText("The website containing the data is unavailable or does not exist." +
                    "\nPlease enter:" +
                    "\n! - Intel" +
                    "\n~ - Microsoft");
        }
    }
}

0 个答案:

没有答案