2016-04-18 116 views
0

我想開發一個基於身份驗證的android的web服務休息,我正在使用庫作爲內部類異步任務的Retrofit。爲什麼我的變量初始化成功後方法

我有一個名爲loginstatus的變量,如果用戶存在,則返回true否則爲false。

問題是當編譯出來的成功方法isloginstatus初始化爲false。

這裏是我的活動代碼:

public class CheckLoginActivity extends Activity { 

static AlertDialog dialog; 
Button b; 
UserModel userModel; 
TextView statusTV; 
EditText userNameET, passWordET; 
String editTextUsername; 
boolean loginStatus; 
String editTextPassword; 
String API_URL = "http://192.168.42.60/task_manager/v1/index.php"; 
SharedPreferences sharedpreferences; 
public static final String USERPREFERENCE = "userPreference"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_check_login); 
    final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper); 
    final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper); 
    usernameWrapper.setHint("Username"); 
    passwordWrapper.setHint("Password"); 
    dialog = new SpotsDialog(this, "Chargement"); 
    //NameText control 
    userNameET = (EditText) findViewById(R.id.editText1); 
    passWordET = (EditText) findViewById(R.id.editText2); 
    //Display Text control 
    statusTV = (TextView) findViewById(R.id.tv_result); 
    //Button to trigger web service invocation 
    b = (Button) findViewById(R.id.button1); 
    //Display progress bar until web service invocation completes 
    //Button Click Listener 
    sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE); 

    b.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      //Check if text controls are not empty 
      if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") { 
       if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") { 
        editTextUsername = userNameET.getText().toString(); 
        editTextPassword = passWordET.getText().toString(); 
        //  statusTV.setText(""); 
        //Create instance for AsyncCallWS 
        AsyncCallWS task = new AsyncCallWS(); 

        //Call execute 
        task.execute(editTextUsername, editTextPassword); 
       } 
       //If Password text control is empty 
       else { 
         statusTV.setText("Please enter Password"); 
       } 
       //If Username text control is empty 
      } else { 
        statusTV.setText("Please enter Username"); 
      } 
     } 
    }); 
} 

和我的異步任務

private class AsyncCallWS extends AsyncTask<String, String, Void> { 
    //Make Progress Bar visible 
    protected void onPreExecute() { 

     dialog.show(); 
    } 

    @Override 
    protected Void doInBackground(String... params) { 
     RestAdapter restAdapter = new RestAdapter.Builder() 
       .setEndpoint(API_URL) 
       .build(); 
     geolocateApi post = restAdapter.create(geolocateApi.class); 

     post.login(editTextUsername, editTextPassword, new Callback<UserModel>() { 
      @Override 
      public void success(UserModel userModelRecv, Response response) { 
       if (userModelRecv != null) { 
        SharedPreferences.Editor editor = sharedpreferences.edit(); 
        editor.putString("username", userModelRecv.getUsername()); 
        editor.putString("id", userModelRecv.getUser_id()); 
        editor.putString("firstName", userModelRecv.getFirstName()); 
        editor.putString("lastName", userModelRecv.getLastName()); 
        editor.putString("Role", userModelRecv.getRole()); 
        userModel=userModelRecv; 
        editor.commit(); 
        loginStatus=true; 
       }else loginStatus=false; 
      } 

      @Override 
      public void failure(RetrofitError error) { 

      } 

     }); 

     return null; 
    } 

    @Override 
    //Once WebService returns response 
    protected void onPostExecute(Void result) { 
     //Make Progress Bar invisible 

     Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class); 
     try { 
      Thread.sleep(200); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     dialog.hide(); 
     //Error status is false 
      if (loginStatus) { 
       //Based on Boolean value returned from WebService 
       //Navigate to Home Screen 
       startActivity(intSucces); 
      } else { 

       //Set Error message 
       statusTV.setText("Login Failed, try again"); 
      } 
     } 


    } 

我的界面改造

public interface geolocateApi { 
@FormUrlEncoded 
@POST("/login") 
public boolean login(@Field("username") String username,@Field("password") String password, Callback<UserModel> response); 

}

感謝您的幫助

+0

您在task.execute(editTextUsername,editTextPassword)中提供參數;但是你不會在你的asynctask中使用它們。也許你的登錄不成功,因爲這一點,你出現在錯誤回調,你的登錄布爾仍然是錯誤的......? – ElDuderino

+0

是的,但它不是params的問題我刪除它們,仍然不工作的Web服務返回成功我登錄並返回true,但在方法成功後loginstatus返回false。 – user3499324

回答

1

您正在使用Retrofit進行登錄時使用基本上異步發送請求的回調。因此,在執行onPostExecute時,改造請求可能仍在處理中,您的loginStatus的值將默認爲false值。由於登錄已在後臺運行,因此您不需要AsyncTask。它應該是這樣的

public class CheckLoginActivity extends Activity { 

    static AlertDialog dialog; 
    Button b; 
    UserModel userModel; 
    TextView statusTV; 
    EditText userNameET, passWordET; 
    String editTextUsername; 
    boolean loginStatus; 
    String editTextPassword; 
    String API_URL = "http://192.168.42.60/task_manager/v1/index.php"; 
    SharedPreferences sharedpreferences; 
    public static final String USERPREFERENCE = "userPreference"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_check_login); 
     final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper); 
     final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper); 
     usernameWrapper.setHint("Username"); 
     passwordWrapper.setHint("Password"); 
     dialog = new SpotsDialog(this, "Chargement"); 
     //NameText control 
     userNameET = (EditText) findViewById(R.id.editText1); 
     passWordET = (EditText) findViewById(R.id.editText2); 
     //Display Text control 
     statusTV = (TextView) findViewById(R.id.tv_result); 
     //Button to trigger web service invocation 
     b = (Button) findViewById(R.id.button1); 
     //Display progress bar until web service invocation completes 
     //Button Click Listener 
     sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE); 

     b.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       //Check if text controls are not empty 
       if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") { 
        if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") { 
         editTextUsername = userNameET.getText().toString(); 
         editTextPassword = passWordET.getText().toString(); 
         //  statusTV.setText(""); 
         //Create instance for AsyncCallWS 
         RestAdapter restAdapter = new RestAdapter.Builder() 
           .setEndpoint(API_URL) 
           .build(); 
         geolocateApi post = restAdapter.create(geolocateApi.class); 

         post.login(editTextUsername, editTextPassword, new Callback<UserModel>() { 
          @Override 
          public void success(UserModel userModelRecv, Response response) { 
           dialog.hide(); 
           if (userModelRecv != null) { 
            SharedPreferences.Editor editor = sharedpreferences.edit(); 
            editor.putString("username", userModelRecv.getUsername()); 
            editor.putString("id", userModelRecv.getUser_id()); 
            editor.putString("firstName", userModelRecv.getFirstName()); 
            editor.putString("lastName", userModelRecv.getLastName()); 
            editor.putString("Role", userModelRecv.getRole()); 
            userModel = userModelRecv; 
            editor.commit(); 
            loginStatus = true; 


            Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class); 
            startActivity(intSucces); 
           } else { 
            loginStatus = false; 
            statusTV.setText("Login Failed, try again"); 
           } 
          } 

          @Override 
          public void failure(RetrofitError error) { 

          } 

         }); 

        } 
        //If Password text control is empty 
        else { 
         statusTV.setText("Please enter Password"); 
        } 
        //If Username text control is empty 
       } else { 
        statusTV.setText("Please enter Username"); 
       } 
      } 
     }); 
    } 
} 
+0

我認爲是正確的,''onPostExecute()'將執行'loginStatus'仍然錯誤,而改造請求可能仍然處理 – Yazan

+0

@Shashank當我第一次登錄時,我給現有的用戶它的工作,但是當我輸入錯誤的用戶,然後我鍵入現有的用戶它不起作用,並在onfailure中的改造錯誤返回null? – user3499324

+0

@ user3499324這似乎是一個完全不同的問題,可能與您的服務器或您提出請求的方式有關。改裝應該返回錯誤描述,試着弄清楚它(如果你不能找出一個單獨的問題,錯誤代碼和描述) – Shashank

相關問題