简体   繁体   中英

How to create login (MySQL) with multiple types of user in Android

I want to create login activity with multiple types of user. This login is connected with MySQL. The multiple choice is "Reviewer" and "Non-Reviewer". Now I use Spinner and the values I call from string.xml. At the table 'user', there are some column such as 'username', 'password', and 'usertype'. Example, user 'peter' is a "Reviewer", he will able to login if user name, password and user type that he uses is correct. How can i solve this problem? Below is my code.

//login activity public class MainActivity extends AppCompatActivity{

private static final String KEY_USERNAME = "username";

private static final String LOGIN_URL = "http://lienawan.xyz/login.php";

private SharedPreferences.Editor loginPrefsEditor;

private EditText etEmail;
private EditText etPassword;
private CheckBox chkMe;
ArrayAdapter<CharSequence> adapter;

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
    Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title ba
    setContentView(R.layout.activity_main);

    etEmail = findViewById(R.id.etEmail);
    etPassword = findViewById(R.id.etPassword);
    chkMe = findViewById(R.id.chkMe);
    SharedPreferences loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
    loginPrefsEditor = loginPreferences.edit();
    boolean saveLogin = loginPreferences.getBoolean("saveLogin", false);
    if (saveLogin) {
        etEmail.setText(loginPreferences.getString("username", ""));
        etPassword.setText(loginPreferences.getString("password", ""));
        chkMe.setChecked(true);
    }
    Spinner spCategory = findViewById(R.id.spCategory);
    adapter = ArrayAdapter.createFromResource(this,R.array.usertype,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spCategory.setAdapter(adapter);
    spCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    Button btnLogin = findViewById(R.id.btnLogin);
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            login();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);

            String username = etEmail.getText().toString();
            String password = etPassword.getText().toString();

            if (chkMe.isChecked()) {
                loginPrefsEditor.putBoolean("saveLogin", true);
                loginPrefsEditor.putString("username", username);
                loginPrefsEditor.putString("password", password);
                loginPrefsEditor.apply();
            } else {
                loginPrefsEditor.clear();
                loginPrefsEditor.commit();
            }
        }
    });
}

@Override
public void onBackPressed() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Exit");
    builder.setMessage("Do you want to exit?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            finish();

        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    builder.show();
}

private void login() {

    String username = etEmail.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    userLogin(username, password);
}

private void userLogin(final String username, final String password){
    class UserLoginClass extends AsyncTask<String,Void,String> {
        private ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(MainActivity.this,"Login... Please Wait",null,true,true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            if(s.equalsIgnoreCase("success")){
                Intent intent = new Intent(MainActivity.this,DashboardApp.class);
                intent.putExtra(KEY_USERNAME,username);
                startActivity(intent);
            }else{
                Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected String doInBackground(String... params) {
            HashMap<String,String> data = new HashMap<>();
            data.put("username",params[0]);
            data.put("password",params[1]);

            Connection ruc = new Connection();
            String result = ruc.sendPostRequest(LOGIN_URL,data);
            return result;
        }
    }
    UserLoginClass ulc = new UserLoginClass();
    ulc.execute(username, password);
}

}

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $approver = $_POST['approver'];

    require_once('dbConnect.php');

    $sql = "select * from user where username='$username' and password='$password'";

    $check = mysqli_fetch_array(mysqli_query($con,$sql));

    if(isset($check)){
        echo "success";
    }else{
        echo "Invalid Username or Password";
    }

}else{
    echo "error try again";

To get selected value from spinner you write below code in onItemSelected :

 String item;//declare globally out of your all method
@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item
        item = parent.getItemAtPosition(position).toString();

        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
    }

Now,check if item and other value are not null , like below :

    private void login() {

        String username = etEmail.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        //checking if fields are not null 
       if (username.isEmpty() || password.isEmpty() || item.isEmpty()) {
       Toast.makeText(getActivity().getApplicationContext(), "Please enter name or pass or select one type!", Toast.LENGTH_SHORT).show();
        return;
        }else{
          userLogin(username, password,item);//passing value to volley
     }
   }

And in your volley request change like below :

    private void userLogin(final String username, final String password,final String item){
...
 @Override
        protected String doInBackground(String... params) {
            HashMap<String,String> data = new HashMap<>();
            data.put("username",params[0]);
            data.put("password",params[1]);
            data.put("approver",params[2]);//adding item value
            ..
        }
    }
}

At your php side just change your query to :

 $sql = "select * from user where username='$username' and password='$password' and usertype='$approver'";

Hope this helps you !

Note : Also never used plain-text password and try using prepared statement it is safe an secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM