AsyncTask在从Json检索信息时返回一个布尔值

时间:2016-03-01 10:37:40

标签: android json android-asynctask

我想检查用户是否在数据库中注册,以及是否获取用户的信息。

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

在我按如下方式调用AsyncTask之前:

AsyncTask

但现在我正在尝试不同的方法。我希望我的asynktask只返回一个布尔值,我调用task=new isCollectorRegistered(); task.execute();

AsyncTask如下所示:

AsyncTask

我已经检查了几个帖子,但我还没有找到检索布尔值的方法,我称之为Asynktask,就像这样:

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");
        }
    }
} 

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

2 个答案:

答案 0 :(得分:1)

要使用AsyncTask,您必须将其子类化。 AsyncTask使用泛型和变量。参数如下AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue>

通过AsyncTask方法启动execute()

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

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

在您的情况下,您将Void传递给AsyncTaskisCollectorRegistered extends AsyncTask<Void, Void, Void>,这样您就无法从该帖子中获得结果。 请阅读此tutorial以深入了解Android中的AsyncTask

答案 1 :(得分:1)

我认为以下内容正是您所寻找的,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...
    }


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