异步任务的问题

发布于 2024-11-29 14:12:35 字数 3588 浏览 0 评论 0原文

我正在尝试从网络服务器获取数据并显示一条消息“确定”或“无效密钥”。当它获取数据时,它应该产生一个进度对话框。我尝试了很多方法,包括将其放入线程内,但是在线程内,警报对话框将不起作用。我尝试过使用异步任务方法,但它似乎也不起作用。有人可以帮我找到解决方案吗?谢谢

verifyCode.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
    //I surround the async task with the progressdialog so that it should show while the method is working in the background
        final ProgressDialog progressDialog = ProgressDialog.show(
                    Activate.this, "", "Loading...");
            new checkActivationCode().execute(activationCode.toString().toUpperCase()
                    );

            progressDialog.dismiss();       
        }
    });

   public class checkActivationCode extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... activationCode) {
        // TODO Auto-generated method stub
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(
                    "https://iphone-radar.com/accounts/confirmation");

            JSONObject holder = new JSONObject();

            holder.put("code", activationCode);
            StringEntity se = new StringEntity(holder.toString());
            httpost.setEntity(se);
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");

            ResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpclient.execute(httpost, responseHandler);

            if (response != null) {
                org.json.JSONObject obj = new org.json.JSONObject(response);

                if ("00000000-0000-0000-0000-000000000000".equals(obj
                        .getString("id"))) {
                    new AlertDialog.Builder(Activate.this)
                            .setTitle(
                                    getResources().getString(
                                            R.string.InvalidKey))
                            .setMessage(
                                    getResources()
                                            .getString(
                                                    R.string.PleaseEntervalidRegistration))
                            .setNeutralButton("OK", null).show();

                } else {
                    // add permanent variables
                    SharedPreferences prefs = getSharedPreferences(
                            "Settings", 0);
                    SharedPreferences.Editor editor = prefs.edit();

                    editor.putBoolean("ACTIVATED", true);
                    editor.putString("ID", obj.getString("id"));
                    editor.commit();

                    Intent imTracking = new Intent(Activate.this,
                            ImTracking.class);
                    imTracking.putExtra("ActivationSuccessful", true);
                    // transfer more data
                    startActivity(imTracking);
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return null;
    }

}

I am trying to get data from a webserver and display a message saying "ok" or "invalid key". While it is getting the data it should produce a progress dialog. I have tried many methods including putting it inside of a thread however inside a thread the alert dialogs won't work. I have tried to use the async task method but it doesnt seem to work either. Can someone help me find a solution? Thanks

verifyCode.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
    //I surround the async task with the progressdialog so that it should show while the method is working in the background
        final ProgressDialog progressDialog = ProgressDialog.show(
                    Activate.this, "", "Loading...");
            new checkActivationCode().execute(activationCode.toString().toUpperCase()
                    );

            progressDialog.dismiss();       
        }
    });

   public class checkActivationCode extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... activationCode) {
        // TODO Auto-generated method stub
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(
                    "https://iphone-radar.com/accounts/confirmation");

            JSONObject holder = new JSONObject();

            holder.put("code", activationCode);
            StringEntity se = new StringEntity(holder.toString());
            httpost.setEntity(se);
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");

            ResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpclient.execute(httpost, responseHandler);

            if (response != null) {
                org.json.JSONObject obj = new org.json.JSONObject(response);

                if ("00000000-0000-0000-0000-000000000000".equals(obj
                        .getString("id"))) {
                    new AlertDialog.Builder(Activate.this)
                            .setTitle(
                                    getResources().getString(
                                            R.string.InvalidKey))
                            .setMessage(
                                    getResources()
                                            .getString(
                                                    R.string.PleaseEntervalidRegistration))
                            .setNeutralButton("OK", null).show();

                } else {
                    // add permanent variables
                    SharedPreferences prefs = getSharedPreferences(
                            "Settings", 0);
                    SharedPreferences.Editor editor = prefs.edit();

                    editor.putBoolean("ACTIVATED", true);
                    editor.putString("ID", obj.getString("id"));
                    editor.commit();

                    Intent imTracking = new Intent(Activate.this,
                            ImTracking.class);
                    imTracking.putExtra("ActivationSuccessful", true);
                    // transfer more data
                    startActivity(imTracking);
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return null;
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晌融 2024-12-06 14:12:35

您无法通过 doInBackground() 方法显示任何类型的对话框或进度对话框,因为它不在 UI 线程上运行。您将需要使用 onProgressUpdate() 方法通过进度更新来更新 UI。如果您想在完成时显示 AlertDialog,请使用 onPostExecute() 方法。 onProgressUpdate()onPostExecute() 都在 UI 线程上运行,因此您的 AlertDialog 代码将正常工作。

下面是 AsyncTask 页面,其中包含一些有关如何正确使用它的示例代码(包括在何处提供 UI 更新):http://developer.android.com/reference/android/os/AsyncTask.html

这里有一些涉及同一主题的问题:如何使用AsyncTask来显示在 Android 中进行后台工作时使用 ProgressDialog?

从 AsyncTask 更新 Activity 中的进度对话框

如何删除AsyncTask 完成工作后的警报对话框

You can't show any kind of dialog or progress dialog from the doInBackground() method because it doesn't run on the UI Thread. You will want to update the UI with progress updates using the onProgressUpdate() method. If you want to show an AlertDialog on completion, use the onPostExecute() method. Both onProgressUpdate() and onPostExecute() run on the UI thread, so your AlertDialog code will work properly.

Here's the AsyncTask page with some sample code on how to properly use it (including where to provide updates to the UI): http://developer.android.com/reference/android/os/AsyncTask.html

Here's some SO questions covering the same topic: How to use AsyncTask to show a ProgressDialog while doing background work in Android?

Updating progress dialog in Activity from AsyncTask

How can I remove an alert dialog after a AsyncTask has done it's work

万劫不复 2024-12-06 14:12:35

出于好奇......如果您在显示对话的线路下方立即删除“关闭”呼叫,会发生什么?对话有可能在创建后立即被取消吗?

另外...与其他对话你必须去

dialogue.show()

进度对话有什么不同吗?从文档中...

打开进度对话框就像调用 ProgressDialog.show() 一样简单。例如,可以轻松实现右侧显示的进度对话框,而无需通过 onCreateDialog(int) 回调管理对话框,如下所示:

Out of curiosity...what happens if you remove the "dismiss" call immediatelty underneath your line where you show the dialogue? Any chance the dialogue is getting dismissed immediately upon creation?

Also...with other dialogues you have to go

dialogue.show()

Is a progress dialogue any different? From the docs....

Opening a progress dialog can be as simple as calling ProgressDialog.show(). For example, the progress dialog shown to the right can be easily achieved without managing the dialog through the onCreateDialog(int) callback, as shown here:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文