Java 将“记住我”选项集成到LoginActivity

Java 将“记住我”选项集成到LoginActivity,java,android,sharedpreferences,Java,Android,Sharedpreferences,这是我的LoginActivity类,我想在这个类中添加记住我的选项 public class LoginActivity extends Activity { ProgressDialog prgDialog; // Error Msg TextView Object TextView errorMsg; // Email Edit View Object EditText emailET; // Passwprd Edit View Object EditText pwdET; St

这是我的LoginActivity类,我想在这个类中添加记住我的选项

  public class LoginActivity extends Activity {

ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;

String email;
// Get Password Edit View Value
String password;
Button button;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    // Find Error Msg Text View control by ID
    errorMsg = (TextView) findViewById(R.id.login_error);
    // Find Email Edit View control by ID
    emailET = (EditText) findViewById(R.id.txt_email);
    // Find Password Edit View control by ID
    pwdET = (EditText) findViewById(R.id.txt_pwd);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False

    prgDialog.setCancelable(false);

    button = (Button) findViewById(R.id.btlogin);

    final Button button = (Button) findViewById(R.id.btlogin);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            try {

                // Get Email Edit View Value
                String email = emailET.getText().toString();
                // Get Password Edit View Value
                String password = pwdET.getText().toString();

                // When Email Edit View and Password Edit View have values
                // other than Null
                if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
                    // When Email entered is Valid
                    if (Utility.validate(email)) {

                        new LoginAsyncTask(LoginActivity.this).execute(
                                email, password);

                        Toast.makeText(getApplicationContext(),
                                "Asynctask started", Toast.LENGTH_SHORT)
                                .show();

                    }
                    // When Email is invalid
                    else {
                        Toast.makeText(getApplicationContext(),
                                "Please enter valid email",
                                Toast.LENGTH_LONG).show();
                    }
                }
                // When any of the Edit View control left blank
                else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Please fill the form, don't leave any field blank",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception ex) {

            }

        }
    });

    TextView registerScreen = (TextView) findViewById(R.id.link_to_register);

    // Listening to register new account link
    registerScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Switching to Register screen
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
        }
    });
}

public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private JSONObject responseJson = null;
    private Context contxt;
    private Activity activity;

    public LoginAsyncTask(Context context) {

        // API = apiURL;
        this.contxt = context;
    }

    // async task to accept string array from context array
    @Override
    protected JSONObject doInBackground(String... params) {

        String path = null;
        String response = null;
        HashMap<String, String> request = null;
        JSONObject requestJson = null;
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        StringEntity requestString = null;
        ResponseHandler<String> responseHandler = null;

        // get the username and password
        Log.i("Email", params[0]);
        Log.i("Password", params[1]);

        try {

            path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
            new URL(path);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

        try {

            // set the API request
            request = new HashMap<String, String>();
            request.put(new String("Email"), params[0]);
            request.put(new String("Password"), params[1]);
            request.entrySet().iterator();

            // Store locations in JSON
            requestJson = new JSONObject(request);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(path);
            requestString = new StringEntity(requestJson.toString());

            // sets the post request as the resulting string
            httpPost.setEntity(requestString);
            httpPost.setHeader("Content-type", "application/json");

            // Handles the response
            responseHandler = new BasicResponseHandler();
            response = httpClient.execute(httpPost, responseHandler);

            responseJson = new JSONObject(response);

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try {
            responseJson = new JSONObject(response);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return responseJson;

    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        String myResJson;
        try {

            myResJson = responseJson.getString("status");
            String test = myResJson;
            if (test.equals("200")) {
                Intent intent = new Intent(contxt, ActivityMenu.class);
                contxt.startActivity(intent);
            } else {
                Intent intent = new Intent(contxt, LoginActivity.class);
                contxt.startActivity(intent);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
   }
  }

我需要帮助来整合这两个类。我试过了,但没有成功

这是我的生日礼物

  public class LoginActivity extends Activity {

ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;

String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);

    // Find Error Msg Text View control by ID
    errorMsg = (TextView) findViewById(R.id.login_error);
    // Find Email Edit View control by ID
    emailET = (EditText) findViewById(R.id.txt_user);
    // Find Password Edit View control by ID
    pwdET = (EditText) findViewById(R.id.txt_pwd);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False

    prgDialog.setCancelable(false);

    button = (Button) findViewById(R.id.btlogin);

    final Button button = (Button) findViewById(R.id.btlogin);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            try {

                // Get Email Edit View Value
                String email = emailET.getText().toString();
                // Get Password Edit View Value
                String password = pwdET.getText().toString();

                // When Email Edit View and Password Edit View have values
                // other than Null
                if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
                    // When Email entered is Valid
                    if (Utility.validate(email)) {

                        if (emailET.getText().toString().equals(email)
                                && pwdET.getText().toString()
                                        .equals(password)) {
                            CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
                            if (ch.isChecked())
                                rememberMe(email, password); // save email
                                                                // and
                                                                // password
                            // show logout activity
                            showLogout(email);

                        }

                        new LoginAsyncTask(LoginActivity.this).execute(
                                email, password);

                        Toast.makeText(getApplicationContext(),
                                "Asynctask started", Toast.LENGTH_SHORT)
                                .show();

                    }
                    // When Email is invalid
                    else {
                        Toast.makeText(getApplicationContext(),
                                "Please enter valid email",
                                Toast.LENGTH_LONG).show();
                    }
                }
                // When any of the Edit View control left blank
                else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Please fill the form, don't leave any field blank",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception ex) {

            }

        }
    });

    TextView registerScreen = (TextView) findViewById(R.id.link_to_register);

    // Listening to register new account link
    registerScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Switching to Register screen
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
        }
    });
   }

public void onStart() {
    super.onStart();
    // read email and password from SharedPreferences
    getUser();
}

public void getUser() {
    SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    String email = pref.getString(PREF_EMAIL, null);
    String password = pref.getString(PREF_PASSWORD, null);

    if (email != null || password != null) {
        // directly show logout form
        showLogout(email);
    }
}

public void rememberMe(String user, String password) {
    // save email and password in SharedPreferences
    getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
            .putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
            .commit();
}

public void showLogout(String email) {
    // display log out activity
    Intent intent = new Intent(this, ActivityMenu.class);
    intent.putExtra("user", email);
    startActivity(intent);
}

public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private JSONObject responseJson = null;
    private Context contxt;
    private Activity activity;

    public LoginAsyncTask(Context context) {

        // API = apiURL;
        this.contxt = context;
    }

    // async task to accept string array from context array
    @Override
    protected JSONObject doInBackground(String... params) {

        String path = null;
        String response = null;
        HashMap<String, String> request = null;
        JSONObject requestJson = null;
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        StringEntity requestString = null;
        ResponseHandler<String> responseHandler = null;

        // get the email and password
        Log.i("Email", params[0]);
        Log.i("Password", params[1]);

        try {

            path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
            new URL(path);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

        try {

            // set the API request
            request = new HashMap<String, String>();
            request.put(new String("Email"), params[0]);
            request.put(new String("Password"), params[1]);
            request.entrySet().iterator();

            // Store locations in JSON
            requestJson = new JSONObject(request);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(path);
            requestString = new StringEntity(requestJson.toString());

            // sets the post request as the resulting string
            httpPost.setEntity(requestString);
            httpPost.setHeader("Content-type", "application/json");

            // Handles the response
            responseHandler = new BasicResponseHandler();
            response = httpClient.execute(httpPost, responseHandler);

            responseJson = new JSONObject(response);

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try {
            responseJson = new JSONObject(response);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return responseJson;

    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        String myResJson;
        try {

            myResJson = responseJson.getString("status");
            String test = myResJson;
            if (test.equals("200")) {
                Intent intent = new Intent(contxt, ActivityMenu.class);
                contxt.startActivity(intent);
            } else {
                Intent intent = new Intent(contxt, LoginActivity.class);
                contxt.startActivity(intent);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

       }
  }
 }
公共类LoginActivity扩展活动{
进程对话;
//错误消息TextView对象
文本视图错误消息;
//电子邮件编辑视图对象
编辑文本电子邮件;
//Passwprd编辑视图对象
编辑文本pwdET;
字符串电子邮件;
//获取密码编辑视图值
字符串密码;
按钮;
公共静态字符串PREFS_NAME=“mypre”;
公共静态字符串PREF_EMAIL=“EMAIL”;
公共静态字符串PREF_PASSWORD=“PASSWORD”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
setContentView(R.layout.activity\u登录);
//按ID查找错误消息文本视图控件
errorMsg=(TextView)findViewById(R.id.login\u错误);
//按ID查找电子邮件编辑视图控件
emailET=(EditText)findViewById(R.id.txt\u用户);
//按ID查找密码编辑视图控件
pwdET=(EditText)findViewById(R.id.txt_pwd);
//实例化进度对话框对象
prgDialog=新建进度对话框(此对话框);
//设置进度对话框文本
setMessage(“请稍候…”);
//将可取消设置为False
prgDialog.setCancelable(假);
按钮=(按钮)findViewById(R.id.btlogin);
最终按钮按钮=(按钮)findViewById(R.id.btlogin);
setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
试一试{
//获取电子邮件编辑视图值
字符串email=emailET.getText().toString();
//获取密码编辑视图值
字符串密码=pwdET.getText().toString();
//当电子邮件编辑视图和密码编辑视图具有值时
//非空
if(Utility.isNotNull(电子邮件)和&Utility.isNotNull(密码)){
//当输入的电子邮件有效时
if(实用程序验证(电子邮件)){
if(emailET.getText().toString().equals)(电子邮件)
&&pwdET.getText().toString()
.equals(密码)){
复选框ch=(复选框)findViewById(R.id.ch_rememberme);
if(ch.isChecked())
记住(电子邮件,密码);//保存电子邮件
//及
//密码
//显示注销活动
退出(电子邮件);
}
新建LoginAsyncTask(LoginActivity.this)。执行(
电子邮件、密码);
Toast.makeText(getApplicationContext(),
“异步任务已启动”,Toast.LENGTH\u SHORT)
.show();
}
//当电子邮件无效时
否则{
Toast.makeText(getApplicationContext(),
“请输入有效电子邮件”,
Toast.LENGTH_LONG).show();
}
}
//当任何“编辑视图”控件留空时
否则{
Toast.makeText(
getApplicationContext(),
“请填写表格,不要将任何字段留空”,
Toast.LENGTH_LONG).show();
}
}捕获(例外情况除外){
}
}
});
TextView注册表屏幕=(TextView)findViewById(R.id.link\u to\u注册表);
//正在侦听注册新帐户链接
registerScreen.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
//切换到寄存器屏幕
意图i=新意图(getApplicationContext(),
RegisterActivity.class);
星触觉(i);
}
});
}
public void onStart(){
super.onStart();
//从SharedReferences读取电子邮件和密码
getUser();
}
public void getUser(){
SharedReferences pref=GetSharedReferences(PREFS\u名称、模式\u私有);
String email=pref.getString(pref_email,null);
字符串密码=pref.getString(pref_密码,null);
如果(电子邮件!=null | |密码!=null){
//直接显示注销表单
退出(电子邮件);
}
}
public void rememberMe(字符串用户、字符串密码){
//在SharedReferences中保存电子邮件和密码
GetSharedReferences(首选项名称、模式专用项).edit()
.putString(首选电子邮件,用户).putString(首选密码,密码)
.commit();
}
公开作废显示注销(字符串电子邮件){
//显示注销活动
意向意向=新意向(此,ActivityMenu.class);
intent.putExtra(“用户”,电子邮件);
星触觉(意向);
}
公共类LoginAsyncTask扩展异步任务{
私有JSONObject responseJson=null;
私人语境;
私人活动;
公共LoginAsyncTask(上下文){
//API=apirl;
this.contxt=上下文;
}
//从上下文数组接受字符串数组的异步任务
@凌驾
受保护的JSONObject doInBackground(字符串…参数){
字符串路径=null;
字符串响应=null;
HashMap请求=null;
JSONObject requestJson=null;
DefaultHttpClient httpClient=null;
HttpPost HttpPost=null;
StringEntity requestString=null;
ResponseHandler ResponseHandler=null;
//获取电子邮件和密码
Log.i(“电子邮件”,参数[0]);
Log.i(“密码”,参数[1]);
试一试{
path=“http://1
  public class LoginActivity extends Activity {

ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;

String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);

    // Find Error Msg Text View control by ID
    errorMsg = (TextView) findViewById(R.id.login_error);
    // Find Email Edit View control by ID
    emailET = (EditText) findViewById(R.id.txt_user);
    // Find Password Edit View control by ID
    pwdET = (EditText) findViewById(R.id.txt_pwd);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False

    prgDialog.setCancelable(false);

    button = (Button) findViewById(R.id.btlogin);

    final Button button = (Button) findViewById(R.id.btlogin);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            try {

                // Get Email Edit View Value
                String email = emailET.getText().toString();
                // Get Password Edit View Value
                String password = pwdET.getText().toString();

                // When Email Edit View and Password Edit View have values
                // other than Null
                if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
                    // When Email entered is Valid
                    if (Utility.validate(email)) {

                        if (emailET.getText().toString().equals(email)
                                && pwdET.getText().toString()
                                        .equals(password)) {
                            CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
                            if (ch.isChecked())
                                rememberMe(email, password); // save email
                                                                // and
                                                                // password
                            // show logout activity
                            showLogout(email);

                        }

                        new LoginAsyncTask(LoginActivity.this).execute(
                                email, password);

                        Toast.makeText(getApplicationContext(),
                                "Asynctask started", Toast.LENGTH_SHORT)
                                .show();

                    }
                    // When Email is invalid
                    else {
                        Toast.makeText(getApplicationContext(),
                                "Please enter valid email",
                                Toast.LENGTH_LONG).show();
                    }
                }
                // When any of the Edit View control left blank
                else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Please fill the form, don't leave any field blank",
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception ex) {

            }

        }
    });

    TextView registerScreen = (TextView) findViewById(R.id.link_to_register);

    // Listening to register new account link
    registerScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Switching to Register screen
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
        }
    });
   }

public void onStart() {
    super.onStart();
    // read email and password from SharedPreferences
    getUser();
}

public void getUser() {
    SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    String email = pref.getString(PREF_EMAIL, null);
    String password = pref.getString(PREF_PASSWORD, null);

    if (email != null || password != null) {
        // directly show logout form
        showLogout(email);
    }
}

public void rememberMe(String user, String password) {
    // save email and password in SharedPreferences
    getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
            .putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
            .commit();
}

public void showLogout(String email) {
    // display log out activity
    Intent intent = new Intent(this, ActivityMenu.class);
    intent.putExtra("user", email);
    startActivity(intent);
}

public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private JSONObject responseJson = null;
    private Context contxt;
    private Activity activity;

    public LoginAsyncTask(Context context) {

        // API = apiURL;
        this.contxt = context;
    }

    // async task to accept string array from context array
    @Override
    protected JSONObject doInBackground(String... params) {

        String path = null;
        String response = null;
        HashMap<String, String> request = null;
        JSONObject requestJson = null;
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        StringEntity requestString = null;
        ResponseHandler<String> responseHandler = null;

        // get the email and password
        Log.i("Email", params[0]);
        Log.i("Password", params[1]);

        try {

            path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
            new URL(path);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

        try {

            // set the API request
            request = new HashMap<String, String>();
            request.put(new String("Email"), params[0]);
            request.put(new String("Password"), params[1]);
            request.entrySet().iterator();

            // Store locations in JSON
            requestJson = new JSONObject(request);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(path);
            requestString = new StringEntity(requestJson.toString());

            // sets the post request as the resulting string
            httpPost.setEntity(requestString);
            httpPost.setHeader("Content-type", "application/json");

            // Handles the response
            responseHandler = new BasicResponseHandler();
            response = httpClient.execute(httpPost, responseHandler);

            responseJson = new JSONObject(response);

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try {
            responseJson = new JSONObject(response);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return responseJson;

    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        String myResJson;
        try {

            myResJson = responseJson.getString("status");
            String test = myResJson;
            if (test.equals("200")) {
                Intent intent = new Intent(contxt, ActivityMenu.class);
                contxt.startActivity(intent);
            } else {
                Intent intent = new Intent(contxt, LoginActivity.class);
                contxt.startActivity(intent);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

       }
  }
 }