【问题标题】:Starting a new activity after info is received in other thread在其他线程中收到信息后启动新活动
【发布时间】:2013-06-20 16:25:19
【问题描述】:

这是我的代码的一部分:单击按钮后,将启动新线程和与服务器的连接。如果连接成功,应用程序应该开始新的活动并结束当前活动。有人可以解释哪种方式最适合这样做吗?

    transThread.submit(new Runnable()
            {
                public void run()
                {
                    guiProgressDialog(true);
                    if(user.length() < 4) guiNotifyUser("Username must have at least 4 characters!");
                    else if(pass.length() < 4) guiNotifyUser("Password must have at least 4 characters!");
                    else if(!pass.equals(passrtp)) guiNotifyUser("Password is not same in both fields!");
                    else if(!isValidEmail(mail)) guiNotifyUser("Your email is not valid email address!");
                    else if(fname.equals("") || lname.equals("")) guiNotifyUser("All fields are mandatory!");
                    else {
                        try {
                            final String message = AutoDiaryHttpHelper.signUp(user, md5(pass), mail, fname, lname);
                            guiNotifyUser(message);
//if message equals something start new activity

                        }
                        catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                    guiProgressDialog(false);
                }
            });

            break;

【问题讨论】:

    标签: android multithreading android-activity


    【解决方案1】:

    您可以为此使用runOnUiThreadHere is a SO answer 展示了如何做到这一点。

    我个人喜欢为此使用AsyncTask。您可以在doInBackground() 中完成您的工作,然后将一个值返回到onPostExecute() 并从那里启动Activity,或者在UI 上执行您需要的任何操作。

    AsyncTask Docs

    Here is an answer of mine 显示了使用AsyncTask 的基本结构和重要细节

    从注释中的代码编辑

    如果没有 logcat,我无法说出确切的错误,但我看到的第一个问题是当您在 AsyncTask 中初始化 context 时。你不想使用getApplicationContext(),尤其是你现在的样子。我想你会得到一个NPE,因为context 尚未初始化。您在构造函数中传递了Context,所以您只需这样做

    this.context = context
    

    但是,您的AsyncTask 看起来像是RegisterActivity 的内部类,这意味着它可以访问RegisterActivity 及其Context 的所有成员变量。这意味着要启动您的Activity,您可以使用RegisterActivity.this 而不是context

        @Override
        protected void onPostExecute(String result)
        {                     
              super.onPostExecute(result);                       
              //if (result == "Successful registration!")                    
              //String i;
              //i = "da";
              context.startActivity(new Intent(RegisterActivity.this,LoginActivity.class));  // change this here
    

    如上所述,context 不需要您的构造函数,如果它是一个内部类,但如果它是一个单独的文件,它会像

    class RegisterTask extends AsyncTask<String, Void, String>{
    
                Context context;
                private RegisterTask(Context context){
                        this.context = context;  // use the variable (context) passed in the constructor above
    

    【讨论】:

    • 一个愚蠢的问题.. 如果我已经在扩展 Activity 类,我还应该如何扩展 AsyncTask?
    • 你不需要extend AsyncTask...你可以简单地把它变成你Activity的内部类
    • 好的,这就是我尝试做的方法,但不知何故我犯了错误(我会发布整个课程,所以我会在 pastebin 上做 - 请只关注 AsyncTask 部分):@ 987654325@据我所见,应用程序在我调用新活动的地方出现崩溃如果您能为我指出代码中的错误(或更好地解释它们),那就太好了。
    • 您的AsyncTask 是您的RegisterActivity 的内部类还是单独的文件?
    • @NenadMilosavljevic 看到我的编辑。特别是onPostExecute() 方法。
    【解决方案2】:

    这是解决我的问题的代码(感谢 CodeMagic - 我不确定这是否是最好的方法): 内部类:

    class RegisterTask extends AsyncTask<String, Void, String>{
    
    
        @Override
        protected String doInBackground(String... params) {
            String message = null;
            EditText username = (EditText) findViewById( R.id.register_username_text );
            EditText password = (EditText) findViewById( R.id.register_password_text );
            EditText passwordrtp = (EditText) findViewById( R.id.register_repeatpassword_text );
            EditText email = (EditText) findViewById( R.id.register_email_text );
            EditText firstname = (EditText) findViewById( R.id.register_firstname_text );
            EditText lastname = (EditText) findViewById( R.id.register_lastname_text );
            final String user = username.getText().toString();
            final String pass = password.getText().toString();
            final String passrtp = passwordrtp.getText().toString();
            final String mail = email.getText().toString();
            final String fname = firstname.getText().toString();
            final String lname = lastname.getText().toString();
    
            guiProgressDialog(true);
            if(user.length() < 4) guiNotifyUser("Username must have at least 4 characters!");
            else if(pass.length() < 4) guiNotifyUser("Password must have at least 4 characters!");
            else if(!pass.equals(passrtp)) guiNotifyUser("Password is not same in both fields!");
            else if(!isValidEmail(mail)) guiNotifyUser("Your email is not valid email address!");
            else if(fname.equals("") || lname.equals("")) guiNotifyUser("All fields are mandatory!");
            else {
                try {
                    message = AutoDiaryHttpHelper.signUp(user, md5(pass), mail, fname, lname);
                    guiNotifyUser(message);//prosla vodi na sledeci activity "Succesfull registration"
    
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
            guiProgressDialog(false);
    
    
    
            return message;
        }
    
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
    
            if (result.equalsIgnoreCase("Successful registration!"))
            {
    
                RegisterActivity.this.startActivity(new Intent(context,LoginActivity.class));
                RegisterActivity.this.finish();
            }
    
    
        }
    }
    

    并从按钮监听器调用:

    public void onClick(View v) {
    
        switch(v.getId())
        {
        case R.id.register_register_button:
    
            RegisterTask registerTask = new RegisterTask();
            registerTask.execute();
    
            break;
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多