我想在我的Android代码中实现一个记住我的功能,但我不知道从哪里开始

时间:2016-05-11 17:07:08

标签: java android session checkbox remember-me

我想在我的Android代码中实现一个记住我的功能,但我不知道从哪里开始,因为我的代码是复杂的类型。我不知道在哪里放东西所以请帮帮我

我想只在登录时才记下电话号码和密码,所以请帮助我。这是我的代码,请告诉我在我的代码中将您的建议放在哪里,如果您编辑它会更好谢谢

这是登录代码:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.net.Uri; 
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;



import static example.R.layout.login;

public class login extends Activity {

TextView signup_text;
Button login_button;
EditText PHONE_NO, PASSWORD;
AlertDialog.Builder builder;


@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.login);
    signup_text = (TextView) findViewById(R.id.sign_up);
    signup_text.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(login.this, register.class));
        }
    });
    PHONE_NO = (EditText) findViewById(R.id.phone_no);
    PASSWORD = (EditText) findViewById(R.id.password);
    login_button = (Button) findViewById(R.id.login_button);


    login_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String phone_no = PHONE_NO.getText().toString();
            String password = PASSWORD.getText().toString();


            if (phone_no.equals("") || password.equals("")) {

                builder = new AlertDialog.Builder(login.this);
                builder.setTitle("Something went wrong...");
                builder.setMessage("Please fill all the fields...");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();


                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            } else {

                BackgroundTask backgroundTask = new BackgroundTask(login.this);
                backgroundTask.execute("login", phone_no, password);

            }


        }
    });


}
}

这是backgroundtask.java

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
 import android.os.AsyncTask;

 import android.widget.CheckBox;
  import android.widget.EditText;


 import org.json.JSONArray;
 import org.json.JSONException;
  import org.json.JSONObject;
  import com.google.gson.*;


 import android.content.SharedPreferences;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.OutputStream;
  import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
  import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.ProtocolException;
  import java.net.URL;
  import java.net.URLEncoder;



public class BackgroundTask extends AsyncTask<String,Void,String> {
String register_url = "http://10.0.0.4/loginapp/register.php";
String login_url = "http://10.0.0.4/loginapp/login.php";



Context ctx;

ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;


public BackgroundTask(Context ctx) {

    this.ctx = ctx;
    activity = (Activity) ctx;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    builder = new AlertDialog.Builder(activity);
    progressDialog = new ProgressDialog(ctx);
    progressDialog.setTitle("Please Wait");
    progressDialog.setMessage("Connecting to server .... ");
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    progressDialog.show();
}


@Override
protected String doInBackground(String... params) {

    String method = params[0];
    if (method.equals("register")) {

        try {
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String owner_name = params[1];
            String shop_name = params[2];
            String phone_no = params[3];
            String shop_address = params[4];
            String opening_time = params[5];
            String closing_time = params[6];
            String password = params[7];
            String data = URLEncoder.encode("owner_name", "UTF-8") + "=" + URLEncoder.encode(owner_name, "UTF-8") + "&" +
                    URLEncoder.encode("shop_name", "UTF-8") + "=" + URLEncoder.encode(shop_name, "UTF-8") + "&" +
                    URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
                    URLEncoder.encode("shop_address", "UTF-8") + "=" + URLEncoder.encode(shop_address, "UTF-8") + "&" +
                    URLEncoder.encode("opening_time", "UTF-8") + "=" + URLEncoder.encode(opening_time, "UTF-8") + "&" +
                    URLEncoder.encode("closing_time", "UTF-8") + "=" + URLEncoder.encode(closing_time, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {


                stringBuilder.append(line + "\n");

            }
            httpURLConnection.disconnect();

            Thread.sleep(5000);
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    } else if (method.equals("login")) {
        try {
            URL url = new URL(login_url);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String phone_no, password;
            phone_no = params[1];
            password = params[2];
            String data = URLEncoder.encode("phone_no", "UTF-8") + "=" + URLEncoder.encode(phone_no, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {


                stringBuilder.append(line + "\n");

            }
            httpURLConnection.disconnect();

            Thread.sleep(5000);
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    return null;
}


@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String json) {

    progressDialog.dismiss();
    try {


        JSONObject jsonObject = new JSONObject(json);
        JSONArray jsonarry = jsonObject.getJSONArray("server_response");
        JSONObject JO = jsonarry.getJSONObject(0);
        String code = JO.getString("code");
        String message = JO.getString("message");

        if (code.equals("reg_true")) {

            showDialog("Registration Success", code, message);

        } else if (code.equals("reg_false")) {


            showDialog("Registration Failed", code, message);

        } else if (code.equals("login_true")) {


            Intent intent = new Intent(activity, HomeActivity.class);
            intent.putExtra("message", message);
            activity.startActivity(intent);
        } else if (code.equals("login_false")) {
            showDialog("Login Error", code, message);
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }
}

public void showDialog(String title, String code, String message) {

    builder.setTitle(title);
    if (code.equals("reg_true") || code.equals("reg_false")) {

        builder.setMessage(message);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                activity.finish();
            }

        });


    } else if (code.equals("login_false")) {

        builder.setMessage(message);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText phone_no, password;
                phone_no = (EditText) activity.findViewById(R.id.phone_no);
                password = (EditText) activity.findViewById(R.id.password);
                phone_no.setText("");
                password.setText("");
                dialog.dismiss();
            }
        });


    }
    AlertDialog alertDialog = builder.create();
    alertDialog.show();


}



}

请帮忙谢谢

2 个答案:

答案 0 :(得分:1)

  1. 点击登录/登录后,只需检查是否记得我CheckBox,如果选中,则SharedPreferences中存储用户名/电子邮件和密码。

    < / LI>
  2. onCreate()的{​​{1}}中,检查LoginActivity中是否存有任何用户名/电子邮件或密码,如果有,请填写SharedPreferences那些用户名/电子邮件和密码。

答案 1 :(得分:0)

    public class Log_in extends AppCompatActivity {
    public static String  PREFS_NAME="NAME";
    public static String PREF_USERNAME="";
    public static String PREF_PASSWORD="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        EditText txtuser=(EditText)findViewById(R.id.txt_user);
        EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
        CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);

        SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
        String username = pref.getString(PREF_USERNAME, null);
        String password = pref.getString(PREF_PASSWORD, null);

        if (username != null || password != null) {
            txtuser.setText(username);
            txtpwd.setText(password);
            ch.setChecked(true);
        }
        else {
            ch.setChecked(false);
        }
    }
    public void doLogin(View view){
        EditText txtuser=(EditText)findViewById(R.id.txt_user);
        EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
        String username = txtuser.getText().toString();
        String password = txtpwd.getText().toString();
        CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
        String type = "login";
        if(ch.isChecked()){
            rememberMe(username,password);
        }
        else{
            clear();
        }
        BackgroundTask bt = new BackgroundTask(this);
        bt.execute(type, username, password);
    }
    public void rememberMe(String user, String password){
        getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
                .edit()
                .putString(PREF_USERNAME,user)
                .putString(PREF_PASSWORD,password)
                .commit();
    }
    public void clear(){
        SharedPreferences sharedPrefs =getSharedPreferences(Log_in.PREFS_NAME,MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.clear();
        editor.commit();
    }

}
相关问题