【问题标题】:AsyncTask return a boolean while retrieving information from a JsonAsyncTask 在从 Json 检索信息时返回一个布尔值
【发布时间】:2016-03-01 10:37:40
【问题描述】:

我想检查一个用户是否在数据库中注册,如果它是获取用户的信息。

通常,当我从服务器检索信息时,我会在Json 中放入一个变量,说明用户是否存在。然后在onPostExecute(Void result) 中处理Json,所以我不需要AsyncTask 返回任何值。

在我调用 AsyncTask 之前如下:

task=new isCollectorRegistered();
task.execute();

但现在我正在尝试一种不同的方法。我希望我的 asynktask 只返回一个布尔值,我称之为 AsyncTask

AsyncTask 如下所示:

public class isCollectorRegistered extends AsyncTask<Void, Void, Void> {

    private static final String TAG_SUCCESS = "success";
    int TAG_SUCCESS1;
    private static final String TAG_COLLECTOR = "collector";
    public String collector;
    JSONArray USER = null;
    JSONObject jObj = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // Checks on the server if collector is registered
        try {
            jObj = ServerUtilities.UserRegistered(context, collector);
            return null;
        } finally {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Void result) {
        try {

            String success = jObj.getString(TAG_SUCCESS);
            Log.d(TAG_COLLECTOR, "Final Info: " + success);

            //This if sees if user correct
            if (Objects.equals(success, "1")){
                //GOOD! THE COLLECTOR EXISTS!!
            }

        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(TAG_COLLECTOR, "JSON parsing didn't work");
        }
    }
} 

我检查了几篇帖子,但我仍然没有找到方法来检索我调用 Asynktask 的布尔值,如下所示:

task=new isCollectorRegistered();
task.execute();
boolean UserRegistered = task.result();

什么是正确的方法?任何帮助将不胜感激

【问题讨论】:

  • @ritesht93 谢谢!所以实际上一旦 AsyncTask 正在执行就不可能检索一个值,因为它正在运行一个完全不同的线程不是吗?
  • doInBackground() 在不同的线程中执行,但是您可以将值从 doInBackground() 传递到 publishProgress()onPostExecute()(这两个方法在活动的 UI 线程上运行,您可以使用它们坚持你的价值观)
  • @ritesht93 - 你在下面查看我的答案了吗?您如何看待我使用的方法?让我知道。 O&O!。

标签: android json android-asynctask


【解决方案1】:

要使用AsyncTask,您必须对其进行子类化。 AsyncTask 使用泛型和可变参数。参数如下AsyncTask &lt;TypeOfVarArgParams , ProgressValue , ResultValue&gt;

AsyncTask 是通过 execute() 方法启动的。

execute() 方法调用doInBackground()onPostExecute() 方法。

TypeOfVarArgParams 作为输入传递给doInBackground() 方法,ProgressValue 用于进度信息,ResultValue 必须从doInBackground() 方法返回并作为参数传递给onPostExecute()

在您的情况下,您将 Void 传递给您的 AsyncTaskisCollectorRegistered extends AsyncTask&lt;Void, Void, Void&gt; 因此您无法从线程中获得结果。 请阅读此tutorial 以深入了解 Android 中的 AsyncTask

【讨论】:

    【解决方案2】:

    我认为以下内容正是您所寻找的,Alvaro...

    注意:我调整了您的代码以使其更合理,但我尽量坚持使用您的原始代码可能...

        public class RegisterCollector extends AsyncTask<String, Void, Boolean> {
    
            private static final String TAG_SUCCESS = "success";
            private static final String TAG_COLLECTOR = "collector";
    
            int TAG_SUCCESS1;
            String[] strArray;
            JSONArray USER = null;
            JSONObject jObj = null;
            public String collector;
            private AppCompatActivity mAct;  // Just incase you need an Activity Context inside your AsyncTask...
            private ProgressDialog progDial;
    
            // Pass data to the AsyncTask class via constructor -> HACK!!
            // This is a HACK because you are apparently only suppose to pass data to AsyncTask via the 'execute()' method.
            public RegisterCollector (AppCompatActivity mAct, String[] strArray) {
                this.mAct = mAct;
                this.strArray = strArray;
            }
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // AHAH!! - So we do need that Activity Context after all...*TISK* *TISK* @ Google **sigh**.
                progDial = ProgressDialog.show(mAct, "Please wait...", "Fetching the strawberries & cream", true, false);
            }
    
            @Override
            protected Boolean doInBackground(String... params) {
                // Checks on the server if collector is registered
                try {
                    jObj = ServerUtilities.UserRegistered(context, collector);
                    return true;  // return whatever Boolean you require here.
                } finally {
                    return false;  // return whatever Boolean you require here.
                }
            }
    
            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                progDial.dismiss();
                try {
    
                    String success = jObj.getString(TAG_SUCCESS);
                    Log.d(TAG_COLLECTOR, "Final Info: " + success);
    
                    // This 'if' block checks if the user is correct...
                    if (Objects.equals(success, "1")){
                        //GOOD! THE COLLECTOR EXISTS!!
                    }
    
                    // You can then also use the Boolean result here if you need to...
                    if (result) {
                        // GOOD! THE COLLECTOR EXISTS!!
                    } else {
                        // Oh my --> We need to try again!! :(
                    }
    
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d(TAG_COLLECTOR, "JSON parsing didn't work");
                    Toast.makeText(mAct, "JSON parsing FAILED - Please try again.", Toast.LENGTH_LONG).show();
                }
            }
        } 
    


    ...如果您想在 AsyncTask 类之外使用生成的布尔数据,请尝试以下操作:
    .

        RegisterCollector regisColctr = new RegisterCollector((AppCompatActivity) this, String[] myStrArry);
        AsyncTask<String, Void, Boolean> exeRegisColctr = regisColctr.execute("");
        Boolean isColctrRegistered = false;
        try {
            isColctrRegistered = exeRegisColctr.get();  // This is how you FINALLY 'get' the Boolean data outside the AsyncTask...-> VERY IMPORTANT!!
        } catch (InterruptedException in) {
            in.printStackTrace();
        } catch (ExecutionException ex) {
            ex.printStackTrace();
        }
    
        if (isColctrRegistered) {
            // Do whatever tasks you need to do here based on the positive (i.e. 'true') AsyncTask Bool result...
        } else {
            // Do whatever tasks you need to do here based on the negative (i.e. 'false') AsyncTask Bool result...
        }
    


    你去 - 我认为这就是你正在寻找的(最初)。每当我需要外部异步数据时,我总是使用这种方法,但它还没有让我失望...
    .

    【讨论】:

      猜你喜欢
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2021-03-21
      • 2015-03-20
      • 2015-05-03
      相关资源
      最近更新 更多