2016-03-01 61 views
0

我想檢查用戶是否已註冊或不在數據庫中,以及是否獲取用戶的信息。AsyncTask從Json中檢索信息時返回一個布爾值

通常,當我從服務器檢索信息時,我在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(); 

什麼是正確的方法?任何幫助,將不勝感激

+1

http:// stackoverflow。com/questions/9458258/return-value-from-async-task-in-android – ritesht93

+0

@ ritesht93謝謝!所以實際上是不可能的,一旦AsyncTask正在執行,因爲它正在運行一個完全不同的線程否的值? – Alvaro

+1

是'doInBackground()'在不同的線程中執行,但是您可以將值從'doInBackground()'傳遞給'publishProgress()'或'onPostExecute()'(這兩種方法在活動的UI線程上運行,您可以使用他們堅持你的價值觀) – ritesht93

回答

1

要使用AsyncTask你必須繼承它。 AsyncTask使用泛型和可變參數。參數如下AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue>。通過​​方法啓動AsyncTask

​​方法調用doInBackground()onPostExecute()方法。

TypeOfVarArgParams傳遞到doInBackground()方法作爲輸入,ProgressValue用於進度信息和ResultValue必須從doInBackground()方法返回,並傳遞給onPostExecute()作爲參數。

在你的情況下,你通過VoidAsyncTaskisCollectorRegistered extends AsyncTask<Void, Void, Void>,所以你不能從線程得到你的結果。 請仔細閱讀本tutorial到Android中深深瞭解的AsyncTask的

1

我認爲下面正是你要找的,阿爾瓦羅...

注意:我調整你的代碼,使之更加合理,但我試圖堅持儘可能多的原密碼儘可能...

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... 
    } 


你去那裏 - 我想這就是你要找的人(原本)。每當我需要外部異步數據時,我總是使用這種方法,並且它還沒有讓我失敗......