开始的意图后,异步任务获得超过 [英] Starting intent after Async task gets over

查看:116
本文介绍了开始的意图后,异步任务获得超过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了我的Andr​​oid应用程序登录的活动。当用户输入正确的凭据,登录活动将切换到该网页,但我不知道为什么我的code将不会切换并且在我的logcat中显示任何错误。该清单也被正确定义。

I created a login activity for my Android app. After the user enters the correct credentials, the login activity will switch over to the homepage but I don't know why my code won't switch and there is no error shown in my logcat. The manifest was also properly defined.

这是我的登录活动:

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

MOVING意向声明onPostExecute方法后可进行编辑code

EDITED CODE AFTER MOVING INTENT STATEMENT TO onPostExecute METHOD

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

}

推荐答案

您所呼叫的意图,开始一个新的活动doInBackgorund(),它运行在非UI线程和活动需要在一个界面内运行线。这就是为什么你登录活动从未停止过。

You are calling the intent to start a new activity inside the doInBackgorund() which runs on a non-UI thread and the Activity needs to be run on a UI thread. That is why your Login activity is never stopped.

把code转到新的活动里面的 onPostExecute() onProgressUpdate()

Put the code to go to the new activity inside onPostExecute() or onProgressUpdate().

下面是一些你可以做的。 声明一个全局变量 loginVerfied = FALSE;

Here is something you can do. Declare a global variable loginVerfied = false;

当你doInBackground验证用户的真实性,使 loginVerified = TRUE ,否则保持

When your doInBackground verifies that the authenticity of the user, make loginVerified = true , otherwise keep it false.

然后在 onPostExecute()

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

修改

EDIT :

此外,您已声明类LoginEmployer扩展的AsyncTask&LT;字符串,字符串,字符串&GT; ,所以你需要使用调用它的 新LoginEmployer.execute(); (你缺少的双引号,不传递任何字符串的任务,因此不匹配它的参数)。 在AsyncTask的定义中的第一个参数是值的数据类型传递给它的时候执行()函数被调用。第二个参数是与在后台线程运行到时显示进度的数据类型。第三个参数指定结果的返回值。

Also, you have declared class LoginEmployer extends AsyncTask<String, String, String>, so to call it you need to use new LoginEmployer.execute(""); (you are missing the double quotes and not passing any String to the Task so it does not match it's parameters). The first parameter in the definition of the AsyncTask is the datatype of the value being passed to it when execute() function is called. The second parameter is the datatype related to displaying progress during the time when the background thread runs. And the third parameter specifies the return value of the result.

更多关于AsyncTask的这里

More about AsyncTask here.

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

So, here is what you need to do now.

声明异步任务是这样的。

Declare the Async Task like this.

类LoginEmployer扩展的AsyncTask&LT;字符串,太虚,字符串&GT; 并打电话到它使用的 新LoginEmployer.execute() 。确保为 返回NULL 从您的 doInBackground()

希望这能解决你的问题吧!

Hope this solves your problem now!

这篇关于开始的意图后,异步任务获得超过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆