Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android按钮自动触发_Android_Android Asynctask - Fatal编程技术网

Android按钮自动触发

Android按钮自动触发,android,android-asynctask,Android,Android Asynctask,我有一个android应用程序的问题。我想制作一个登录屏幕,我有一个异步任务,当按下登录按钮时应该运行该任务。然而,当应用程序启动时,它似乎会自动运行,我不知道为什么 这是我的代码: package com.connect.application; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; im

我有一个android应用程序的问题。我想制作一个登录屏幕,我有一个异步任务,当按下登录按钮时应该运行该任务。然而,当应用程序启动时,它似乎会自动运行,我不知道为什么

这是我的代码:

package com.connect.application;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.connect.utils.*;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
//    private static final String[] DUMMY_CREDENTIALS = new String[]{
//            "foo@example.com:hello",
//            "bar@example.com:world"
//    };

    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    private Boolean mLoggedIn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        // Set up the login form.
        mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(mEmail);

        mPasswordView = (EditText) findViewById(R.id.password);
//        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
//                if (id == R.id.login || id == EditorInfo.IME_NULL) {
//                    attemptLogin();
//                    return true;
//                }
//                return false;
//            }
//        });

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v("TAG/Login clicked", "Login button clicked");
                attemptLogin();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask();

            String[] credentials = new String[2];
            credentials[0] = mEmail;
            credentials[1] = mPassword;

            Log.v("TAG/Auth task started", "Auth task started");
            mAuthTask.execute(credentials);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            // TODO: attempt authentication against a network service.

//            try {
//                // Simulate network access.
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                return false;
//            }
//
//            for (String credential : DUMMY_CREDENTIALS) {
//                String[] pieces = credential.split(":");
//                if (pieces[0].equals(mEmail)) {
//                    // Account exists, return true if the password matches.
//                    return pieces[1].equals(mPassword);
//                }
//            }

            Log.v("TAG/LoginAsync", "Task triggerred");
            LoggedUser.getInstance().setId(1);
            LoggedUser.getInstance().setmUsername("dummy@mail.com");
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                mLoggedIn = true;
                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
package com.connect.application;
导入android.animation.Animator;
导入android.animation.AnimatorListenerAdapter;
导入android.annotation.TargetApi;
导入android.app.Activity;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Build;
导入android.os.Bundle;
导入android.text.TextUtils;
导入android.util.Log;
导入android.view.KeyEvent;
导入android.view.Menu;
导入android.view.view;
导入android.view.inputmethod.EditorInfo;
导入android.widget.EditText;
导入android.widget.TextView;
导入com.connect.utils。*;
/**
*向用户显示登录屏幕的活动,提供注册为
*嗯。
*/
公共类LoginActivity扩展了活动{
/**
*包含已知用户名和密码的虚拟身份验证存储。
*TODO:连接到真实身份验证系统后删除。
*/
//私有静态最终字符串[]伪\u凭据=新字符串[]{
//            "foo@example.com:你好“,
//            "bar@example.com:世界“
//    };
/**
*用于填充电子邮件字段的默认电子邮件。
*/
public static final String EXTRA_EMAIL=“com.example.android.authenticatordemo.EXTRA.EMAIL”;
/**
*跟踪登录任务,确保我们可以根据请求取消它。
*/
private UserLoginTask mAuthTask=null;
//尝试登录时的电子邮件和密码值。
私有字符串mEmail;
私有字符串mPassword;
//用户界面引用。
私有编辑文本mEmailView;
私有编辑文本mPasswordView;
私有视图mloginfo视图;
私有视图mLoginStatusView;
私有文本视图mLoginStatusMessageView;
私有布尔值mLoggedIn=false;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u登录);
//设置登录表单。
mEmail=getIntent().getStringExtra(额外电子邮件);
mEmailView=(EditText)findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView=(EditText)findViewById(R.id.password);
//mPasswordView.setOnEditorActionListener(新的TextView.OnEditorActionListener(){
//@覆盖
//公共布尔onEditorAction(TextView TextView、int id、KeyEvent KeyEvent){
//if(id==R.id.login | | id==EditorInfo.IME_NULL){
//尝试登录();
//返回true;
//                }
//返回false;
//            }
//        });
mLoginFormView=findviewbyd(R.id.login\u表单);
mLoginStatusView=findviewbyd(R.id.login\u状态);
mLoginStatusMessageView=(TextView)findviewbyd(R.id.login\u status\u message);
findviewbyd(R.id.sign_in_按钮)。setOnClickListener(新视图。OnClickListener(){
@凌驾
公共void onClick(视图){
Log.v(“点击标签/登录”,“点击登录按钮”);
尝试登录();
}
});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
super.onCreateOptions菜单(菜单);
getMenuInflater().充气(R.menu.login,menu);
返回true;
}
/**
*尝试登录或注册登录表单指定的帐户。
*如果存在表单错误(无效电子邮件、缺少字段等),则
*出现错误,未进行实际登录尝试。
*/
public void attemptLogin(){
if(mAuthTask!=null){
返回;
}
//重置错误。
mEmailView.setError(null);
mPasswordView.setError(null);
//在尝试登录时存储值。
mEmail=mEmailView.getText().toString();
mPassword=mPasswordView.getText().toString();
布尔取消=假;
视图焦点视图=空;
//检查密码是否有效。
if(TextUtils.isEmpty(mPassword)){
mPasswordView.setError(getString(R.string.error_字段_必填));
focusView=mPasswordView;
取消=真;
}else if(mPassword.length()<4){
mPasswordView.setError(getString(R.string.error\u密码无效));
focusView=mPasswordView;
取消=真;
}
//检查有效的电子邮件地址。
if(TextUtils.isEmpty(mEmail)){
setError(getString(R.string.error_字段_必填));
focusView=mEmailView;
取消=真;
}如果(!mEmail.contains(@)),则为else{
mEmailView.setError(getString(R.string.error\u无效的电子邮件));
focusView=mEmailView;
取消=真;
}
如果(取消){
//出现错误;请不要尝试登录并在第一次登录时集中注意力
//表单字段有错误。
focusView.requestFocus();
}否则{
//显示进度微调器,并启动后台任务以
//执行用户登录尝试。
mLoginStatusMessageView.setText(R.string.login\u progress\u signing\u in);
显示进度(真实);
mAuthTask=新用户登录任务();
字符串[]凭据=新字符串[2];
凭证[0]=mEmail;
凭证[1]=mPassword;
Log.v(“标记/身份验证任务已启动”,“身份验证任务已启动”);
mAuthTask.execute(凭证);
}
}
/**
*显示进度UI并隐藏登录表单。
*/
@TargetApi(构建版本代码蜂窝MR2)
私有void showProgress(最终布尔值显示){
//在蜂巢MR2上我们有