ProgressDialog 没有出现在 AsyncTask 中 [英] ProgressDialog doesn't show up in AsyncTask

查看:17
本文介绍了ProgressDialog 没有出现在 AsyncTask 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 Android 应用程序,该应用程序依赖于该应用程序从数据库中获取的数据.为了获取这些数据,我有以下类(这个类从 JSON 数据库中获取数据,转换并返回它):

I am creating an android app that depends on data that the app gets from the database. To get this data I have the following class (this class gets data from the database in JSON, translates it and returns it):

public class Json {
    public String jsonResult;

    private Activity activity;
    private String url = "http://json.example.org/json.php";
    private String db, query;

    public Json(Activity activity) {
            this.activity = activity;
        }

    public String accessWebService(String db, String query) {
        JsonReadTask task = new JsonReadTask();

        this.db = db;
        this.query = query;

        task.execute(new String[] { url });

        try {
            task.get();
        } catch (InterruptedException e) {
            Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread got interrupted",
                    Toast.LENGTH_LONG).show();
        } catch (ExecutionException e) {
            Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread wasn't able to execute",
                    Toast.LENGTH_LONG).show();
        }
        return jsonResult;
    }

    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {

        private final ProgressDialog dialog = new ProgressDialog(activity);

        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                // add post data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("db", db));
                nameValuePairs.add(new BasicNameValuePair("query", query));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                if (jsonResult.isEmpty()) {
                    Toast.makeText(activity.getApplicationContext(),
                            "Error, connection is up but didn't receive data. That's strange...", Toast.LENGTH_LONG)
                            .show();
                    this.cancel(true);
                }

            } catch (ClientProtocolException e) {
                // Toast.makeText(activity.getApplicationContext(),
                // "Error, Client Protocol Exception in JSON task",
                // Toast.LENGTH_LONG).show();
                Log.i("Json", "Error, Client Protocol Exception in JSON task");
                this.cancel(true);
            } catch (IOException e) {
                // Toast.makeText(activity.getApplicationContext(),
                // "Error, Please check your internet connection",
                // Toast.LENGTH_LONG).show();
                Log.i("Json", "Error, Please check your internet connection");
                this.cancel(true);
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
                Toast.makeText(activity.getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }
    }// end async task
}

我注意到我的应用在访问数据库时冻结了.经过一番谷歌搜索,我发现这是 accessWebService() 方法中的 .get() 方法导致的.我尝试像这样实现一个progressDialog(我也删除了 .get() 方法):

I noticed that my app freezes while accessing the database. After some googling, I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog like so (I also deleted the .get() method):

private final ProgressDialog dialog = new ProgressDialog(activity);

protected void onPreExecute() {
    super.onPreExecute();
    this.dialog.setMessage("Loading...");
    this.dialog.setCancelable(false);
    this.dialog.show();
}

protected void onPostExecute(String result) {
    if (this.dialog.isShowing()) {
        this.dialog.dismiss();
    }
}

但是对话框没有出现,我得到了 NullPointerException 因为该应用程序仅在有数据时才能工作:

but the dialog didn't show up and I got NullPointerException because the app only works when there is data:

result = json.accessWebService(db, query);

(也许有一点很重要:我也在 for 循环中使用这个方法)

(maybe an important thing to mention: I also use this method in for loops)

所以现在我的问题是:如何更改我的应用程序,以便在访问数据库时获得 ProgressDialog 而不会获得 NullPointerException?我担心我必须重新构建我的整个应用程序,如果我必须这样做,我该怎么做?我希望你们理解我的问题并解决这个问题,因为我真的需要帮助.提前致谢.

So now my question is: How can I change my app so that I get a ProgressDialog while accessing the database and without getting NullPointerException? I fear that I have to rearchitect my whole app and if I have to do this, how do I do this? I hope you guys understand my question and have a fix for this because I really need help. Thanks in advance.

附言对不起,如果我的英语不是很好,我不是母语人士.

P.S. Sorry if my English is not that good, I'm not a native speaker.

推荐答案

... 我发现这是 accessWebService() 方法中的 .get() 方法导致的.我试图实现一个progressDialog...

... I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog...

没错.get() 是一个阻塞调用,仅仅添加一个 ProgressDialog 并不能修复它.您需要删除 .get() 并且这可能会解决您的 ProgressDialog 未显示的问题.

That is right. get() is a blocking call and simply adding a ProgressDialog won't fix it. You need to remove .get() and that will probably fix the issue of your ProgressDialog not showing.

必须在主 Thread 上执行 AsyncTask,因此请确保您正在这样做.

An AsyncTask must be executed on the main Thread so make sure you are doing that.

您遇到的另一个问题是 Toast.LENGTH_LONG).show();UI 上运行,而您在 doInBackground() 中有它这是不可能发生的.您需要将 result 发送到 onPostExecute(),如果需要,您可以在那里显示您的 Toast.这也可以在 onProgressUpdate() 中完成.

Another problem you have is Toast.LENGTH_LONG).show(); runs on the UI and you have it in doInBackground() which cannot happen. You need to send the result to onPostExecute() and you can display your Toast there if need. This could also be done in onProgressUpdate().

这篇关于ProgressDialog 没有出现在 AsyncTask 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆