启动后意图异步任务获得超过(Starting intent after Async task get

2019-07-31 07:40发布

我创建了一个登录活动为我的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();
        }
    }
}

}

Answer 1:

您正在调用哪一个运行在非UI线程的意图开始doInBackgorund(内一个新的活动)和活动必须在UI线程中运行。 这就是为什么你的登录活动从未停止过。

把代码去新的活动里面onPostExecute()onProgressUpdate()。

这里是你可以做的。 声明一个全局变量loginVerfied = false;

当你的doInBackground验证用户的真实性,使loginVerified = true ,否则保持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(""); (你缺少的双引号和不传递任何字符串的任务,以便它不匹配它的参数)。 在的AsyncTask的定义中的第一个参数是被传递给它的值的数据类型时执行()函数被调用。 第二个参数是有关期间,当后台线程运行时显示进度的数据类型。 第三个参数指定结果的返回值。

更多的AsyncTask 这里 。

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

声明异步任务是这样的。

class LoginEmployer extends AsyncTask<String, Void, String>并且通过使用使给它的呼叫new LoginEmployer.execute("") 确保return nulldoInBackground()。

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



Answer 2:

检查者添加到您的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); 
    }


Answer 3:

认为你已经添加了Intent这里的代码,将帮助您切换到另一个活动。

protected void onPostExecute(String file_url) { 

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

    pDialog.dismiss(); 

你应该做的UI线程和非UI线程非UI工作UI的工作 ,这就是从机器人的Honeycomb版本到来的规则。

您已经添加在下面的代码doInBackground()这应该是在onPostExcute()

Intent homepage = new Intent( getApplicationContext(), HomepageEmployerActivity.class); 
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(homepage);


文章来源: Starting intent after Async task gets over