1

我为我的 Android 应用创建了一个登录活动。用户输入正确的凭据后,登录活动将切换到主页,但我不知道为什么我的代码不会切换,并且我的 logcat 中没有显示错误。清单也被正确定义。

这是我的登录活动:

public class LoginEmployerActivity extends Activity { 
Button btnLoginEmployer; 
Button btnLinkToEmployerRegisterScreen; 
EditText inputEmail; 
EditText inputPassword; 
TextView loginErrorMsg; 
TextView forgotPassword; 

// JSON Response node names 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_CNAME = "cname"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 
private ProgressDialog pDialog; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.login_employer); 

// Importing all assets like buttons, text fields 
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail); 
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword); 
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer); 
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen); 
loginErrorMsg = (TextView) findViewById(R.id.login_error); 
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword); 

// Login button Click Event 
btnLoginEmployer.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View view) { 
        // Checking for server respond 
            new LoginEmployer().execute(); 
        } 
    } 
}); 

// Link to Register Screen 
btnLinkToEmployerRegisterScreen 
        .setOnClickListener(new View.OnClickListener() { 

            public void onClick(View view) { 
                Intent i = new Intent(getApplicationContext(), 
                        RegisterEmployerActivity.class); 
                startActivity(i); 
                finish(); 
            } 
        }); 

// Link to forgot password link 
forgotPassword.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
        // Switching to forgot password screen 
        Intent i = new Intent(getApplicationContext(), 
                ForgotPasswordEmployerActivity.class); 
        startActivity(i); 
    } 
}); 
} 

// Background ASYNC Task to login by making HTTP Request 
class LoginEmployer extends AsyncTask<String, String, String> { 

// Before starting background thread Show Progress Dialog 
@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    pDialog = new ProgressDialog(LoginEmployerActivity.this); 
    pDialog.setMessage("Authenticating..."); 
    pDialog.setIndeterminate(false); 
    pDialog.setCancelable(false); 
    pDialog.show(); 
} 

// Checking login in background 
protected String doInBackground(String... params) { 
    runOnUiThread(new Runnable() { 
        public void run() { 

            String email = inputEmail.getText().toString(); 
            String password = inputPassword.getText().toString(); 
            EmployerFunctions employerFunctions = new EmployerFunctions(); 
            JSONObject json = employerFunctions.loginUser(email, 
                    password); 

            // check for login response 
            try { 
                if (json.getString(KEY_SUCCESS) != null) { 
                    loginErrorMsg.setText(""); 
                    String res = json.getString(KEY_SUCCESS); 
                    if (Integer.parseInt(res) == 1) { 
                        // user successfully logged in 
                        // Store user details in SQLite Database 
                        DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer( 
                                getApplicationContext()); 
                        JSONObject json_user = json 
                                .getJSONObject("user"); 

                        // Clear all previous data in database 
                        employerFunctions 
                                .logoutUser(getApplicationContext()); 
                        dbe.addUser( 
                                json_user.getString(KEY_NAME), 
                                //json_user.getString(KEY_CNAME), 
                                json_user.getString(KEY_EMAIL), 
                                json.getString(KEY_UID), 
                                json_user.getString(KEY_CREATED_AT)); 
                        // Launch Employer homePage Screen 
                        Intent homepage = new Intent( 
                                getApplicationContext(), 
                                HomepageEmployerActivity.class); 

                        // Close all views before launching Employer 
                        // homePage 
                        homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                        startActivity(homepage); 

                        // Close Login Screen 
                        finish(); 
                    } else { 
                        // Error in login 
                        loginErrorMsg 
                                .setText("Invalid username/password"); 
                    } 
                } 
            } catch (JSONException e) { 
                e.printStackTrace(); 
            } 
        } 
    }); 
    return null; 
} 

// After completing background task Dismiss the progress dialog 
protected void onPostExecute(String file_url) { 
    // dismiss the dialog once done 
    pDialog.dismiss(); 
} 
} 
}

将意图声明移至 onPostExecute 方法后编辑的代码

public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;

boolean loginVerify= false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_employer);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
    inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
    btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
    btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);
    forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);

    // Login button Click Event
    btnLoginEmployer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Checking for server respond
                new LoginEmployer().execute();
            }
        }
    });

    // Link to Register Screen
    btnLinkToEmployerRegisterScreen
            .setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterEmployerActivity.class);
                    startActivity(i);
                    finish();
                }
            });

    // Link to forgot password link
    forgotPassword.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Switching to forgot password screen
            Intent i = new Intent(getApplicationContext(),
                    ForgotPasswordEmployerActivity.class);
            startActivity(i);
        }
    });
}

// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {

    // Before starting background thread Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginEmployerActivity.this);
        pDialog.setMessage("Authenticating...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    // Checking login in background
    protected String doInBackground(String... params) {
        runOnUiThread(new Runnable() {
            public void run() {

                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                EmployerFunctions employerFunctions = new EmployerFunctions();
                JSONObject json = employerFunctions.loginUser(email,
                        password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        loginErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if (Integer.parseInt(res) == 1) {
                            loginVerify = true;
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
                                    getApplicationContext());
                            JSONObject json_user = json
                                    .getJSONObject("user");

                            // Clear all previous data in database
                            employerFunctions
                                    .logoutUser(getApplicationContext());
                            dbe.addUser(
                                    json_user.getString(KEY_NAME),
                                    json_user.getString(KEY_CNAME),
                                    json_user.getString(KEY_EMAIL),
                                    json.getString(KEY_UID),
                                    json_user.getString(KEY_CREATED_AT));

                        } else {
                            // Error in login
                            loginErrorMsg
                                    .setText("Invalid username/password");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    // After completing background task Dismiss the progress dialog
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
        if ( loginVerify == true ) 
        {
        // Launch Employer homePage Screen
        Intent homepage = new Intent(getApplicationContext(),
                HomepageEmployerActivity.class);

        // Close all views before launching Employer
        // homePage
        homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homepage);

        // Close Login Screen
        finish();
        }
    }
}

}

4

3 回答 3

7

您正在调用意图在 doInBackgorund() 内启动一个新活动,该活动在非 UI 线程上运行,并且 Activity 需要在 UI 线程上运行。这就是为什么您的登录活动永远不会停止的原因。

将代码放入onPostExecute()onProgressUpdate()中的新活动。

这是您可以做的事情。声明一个全局变量loginVerfied = false;

当你的 doInBackground 验证用户的真实性时, make loginVerified = true,否则 keep it false

然后在里面onPostExecute()

if(loginVerifed == true)
{
       Intent homepage = new Intent(getApplicationContext(),HomepageEmployerActivity.class                               
       homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(homepage);
       finish();
}

编辑 :

此外,您已经声明class LoginEmployer extends AsyncTask<String, String, String>了 ,因此您需要使用它来调用它new LoginEmployer.execute("");(您缺少双引号并且没有将任何字符串传递给 Task ,因此它与它的参数不匹配)。AsyncTask 定义中的第一个参数是调用execute()函数时传递给它的值的数据类型。第二个参数是与后台线程运行期间显示进度相关的数据类型。第三个参数指定结果的返回值。

更多关于 AsyncTask在这里

所以,这就是你现在需要做的。

像这样声明异步任务。

class LoginEmployer extends AsyncTask<String, Void, String>并使用new LoginEmployer.execute(""). 确保return null从您的doInBackground() 开始

希望这现在可以解决您的问题!

于 2012-08-31T18:42:38.143 回答
1

向您的 AsyncTask 添加检查器,例如

// Background ASYNC Task to login by making HTTP Request 
class LoginEmployer extends AsyncTask<String, String, String> { 

boolean validUser = false;

然后,一旦在您的后台任务中验证了用户,请将值设置为 true

 if (Integer.parseInt(res) == 1) { 
      // user successfully logged in 
      // Store user details in SQLite Database 

     validUser = true;  //set valid to true

现在在 postExecute 检查用户是否有效

protected void onPostExecute(String file_url) { 
    // dismiss the dialog once done 
    pDialog.dismiss(); 
    if ( validUser )
    {
        Intent homepage = new Intent( LoginEmployerActivity.this, 
        HomepageEmployerActivity.class); 

        // Close all views before launching Employer 
        // homePage 
         homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(homepage); 
    }
于 2012-08-31T18:50:11.000 回答
0

我认为您没有在此处添加可以帮助您切换到另一个 Activity 的代码Intent

protected void onPostExecute(String file_url) { 

    // dismiss the dialog once done             // Intent Code Missing.

    pDialog.dismiss(); 

你应该在 UI 线程中做 UI 工作,在 Non-UI 线程中做非 UI 工作,这是从 HoneyComb 版本的 android 到来的规则。

您已在 中添加了以下代码doInBackground(),应该在onPostExcute()

Intent homepage = new Intent( getApplicationContext(), HomepageEmployerActivity.class); 
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(homepage);
于 2012-08-31T18:41:14.860 回答