ProgressDialog不会在AsyncTask的显示 [英] ProgressDialog doesn't show up in AsyncTask

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

问题描述

我创建一个Android应用程序,depents上的数据的应用程序从数据库获取。为了得到这个数据,我有下面的类(该类获取数据从数据库中的JSON,其转换并返回):

 公共类的Json {

公共字符串jsonResult;

私人活动的活动;
私人字符串URL =htt​​p://json.example.org/json.php;
私人字符串数据库,查询;

公共JSON(活动活动){
    this.activity =活动;
}

公共字符串accessWebService(字符串分贝,查询字符串){
    JsonReadTask任务=新JsonReadTask();

    this.db = DB;
    this.query =查询;

    task.execute(新的String [] {URL});

    尝试 {
        task.get();
    }赶上(InterruptedException异常E){
        Toast.makeText(activity.getApplicationContext(),
                致命错误:线程被中断,Toast.LENGTH_LONG).show();
    }赶上(为ExecutionException E){
        Toast.makeText(activity.getApplicationContext(),
                致命错误:线程无法执行,Toast.LENGTH_LONG).show();
    }
    返回jsonResult;
}

//异步任务来访问网络
私有类JsonReadTask扩展的AsyncTask<字符串,太虚,字符串> {

    私人最终ProgressDialog对话框=新ProgressDialog(活动);

    保护字符串doInBackground(字符串... PARAMS){
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(PARAMS [0]);
        尝试 {
            //添加后的数据
            名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
            nameValuePairs.add(新BasicNameValuePair(DB,DB));
            nameValuePairs.add(新BasicNameValuePair(查询,查询));
            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
            HTT presponse响应= httpclient.execute(httppost);
            。jsonResult = inputStreamToString(response.getEntity()的getContent())的toString();
            如果(jsonResult.isEmpty()){
                Toast.makeText(activity.getApplicationContext(),
                        错误,连接起来,但没有接收数据。真奇怪......
                        Toast.LENGTH_LONG).show();
                this.cancel(真正的);
            }

        }赶上(ClientProtocolException E){
            //Toast.makeText(activity.getApplicationContext(),
            //错误,在JSON任务客户端协议异常,
            // Toast.LENGTH_LONG).show();
            Log.i(JSON的,错误,在JSON任务客户端协议异常);
            this.cancel(真正的);
        }赶上(IOException异常E){
            //Toast.makeText(activity.getApplicationContext(),
            //错误,请检查您的网络连接,
            // Toast.LENGTH_LONG).show();
            Log.i(JSON的,错误,请检查您的网络连接);
            this.cancel(真正的);
        }
        返回null;
    }

    私人的StringBuilder inputStreamToString(InputStream的是){
        字符串rLine =;
        StringBuilder的答案=新的StringBuilder();
        的BufferedReader RD =新的BufferedReader(新InputStreamReader的(是));

        尝试 {
            而((rLine = rd.readLine())!= NULL){
                answer.append(rLine);
            }
        }赶上(IOException异常E){
            Toast.makeText(activity.getApplicationContext(),错误......+ e.toString()
                    Toast.LENGTH_LONG).show();
        }
        返回的答案;
    }


    }
} //结束异步任务
 

}

我注意到,我的应用程序冻结而accesing数据库。一些谷歌上搜索后,我发现这是在accessWebService()方法获得()方法导致此。我试图执行一个progressDialog像这样(我也删除了。获得()方法):

 私人最终ProgressDialog对话框=新ProgressDialog(活动);

    在preExecute保护无效(){
        super.on preExecute();
        this.dialog.setMessage(载入中...);
        this.dialog.setCancelable(假);
        this.dialog.show();
    }

保护无效onPostExecute(字符串结果){
            如果(this.dialog.isShowing()){
                this.dialog.dismiss();
            }
        }
 

但是对话并没有显示出来,并我得到NullPointerException异常,因为该应用程序只能在有数据的:

 的结果= json.accessWebService(DB,查询);
 

(也许一个重要的东西说:我ALSE使用此方法在forloops)

所以,现在我的问题是:我怎样才能改变我的应用程序,这样我得到一个ProgressDialog而accesing数据库,并没有得到NullPointerException异常?我担心,我必须重新构建我的整个应用程序,如果我不得不这样做,我该怎么办呢?我希望你们明白我的问题,有一个固定的,因为我真的很需要帮助。先谢谢了。

P.S。很抱歉,如果我的英语不是很好,我不是一个母语的人。

解决方案
  

...我发现有人在accessWebService()方法获得()方法导致此。我试图执行一个progressDialog ...

这是正确的。 获得()是一个阻塞调用,并简单地增加一个 ProgressDialog 将不会解决它。您需要删除获得(),这将可能解决你的 ProgressDialog 不显示的问题。

这是的AsyncTask 必须在主发执行所以一定要确保你正在做的。

另外一个问题,你必须是 Toast.LENGTH_LONG).show(); 运行在 UI 和你有它在 doInBackground()这是不可能发生的。您需要将结果发送到 onPostExecute()键,可以显示你的吐司如果有需要。这也可以在 onProgressUpdate做()

I am creating an android app that depents 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

}

I noticed that my app freezes while accesing 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();
            }
        }

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

result = json.accessWebService(db, query);

(maybe an important thing to mention: i alse use this method in forloops)

So now my question is: How can I change my app so that i get a ProgressDialog while accesing the database and without getting NullPointerExceptions? 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, im not a native speaker.

解决方案

... I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a 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.

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

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天全站免登陆