2015-05-01 41 views
0

這是我的註冊功能。Android第一次從數據中獲取信息時如何去其他活動

如果我從我的服務器得到正確的反饋,它會將isCreated更改爲true布爾值,並轉到下一個Activity。

問題是布爾值不能被編輯,我需要再次點擊按鈕才能移動到下一個Activity(布爾值只能在點擊按鈕後設置爲true)?

public void onClick(View view) { 

    switch(view.getId()){ 
     case R.id.register: 
     if(!validate()) 
       Toast.makeText(getBaseContext(), "Enter user information!", Toast.LENGTH_LONG).show(); 
      // call AsynTask to perform network operation on separate thread 
      new HttpAsyncTask().execute(herokuServer); 
      if (isCreated)startActivity(new Intent(this, Preference.class)); 


      break; 
    } 

private class HttpAsyncTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... urls) { 

     newAccount = new userAccount(); 
     newAccount.setPassword(password.getText().toString()); 
     newAccount.setEmail(email.getText().toString()); 

     return POST(urls[0],newAccount); 
    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 
     if (result.equals("Welcome to Opshun!"))isCreated = true; 
     //if (!result.equals("Welcome to Opshun!")) result = "Please use your email to register!"; 
     Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 
    } 
} 

有什麼方法可以解決它嗎?

+0

如果它是一個內部類或使用接口,則可以在'onPostExecute()'中啓動該活動http://stackoverflow.com/questions/18517400/inner-can-access-but-not-update-values -asynctask/18517648#18517648代碼在任務運行時繼續運行,因此**異步** – codeMagic

回答

2

這是AsyncTask後面的整點;它會從UIThread移動長時間運行的操作。通過這樣做,UIThread可以「繼續」執行,而由AsyncTask開始的Thread執行重載操作。

一個可能的解決方案可能是在SharedPreferences中存儲一個布爾值,該值確定AsyncTask是否已經運行。

如果您想要在AsyncTask完成時通知您,您需要使用接口創建委託。 This answer顯示如何做到這一點。

0

將您在doInBackground()中獲得的數據返回到onPostExecute(),如果數據是您想要的,則使用Intent從那裏開始其他活動。

相關問題