共享偏好与用户级错误

时间:2016-09-24 07:35:08

标签: php android

我的共享偏好有一些错误,即使用户不在用户名和密码上放置值,它仍然会转到OwnerTabs,我不知道为什么。你能帮帮我吗这是我的代码。

authenticate.php

    <?php 
require 'database-config.php';

$username = "";
$password = "";

if(isset($_POST['username'])){
$username = $_POST['username'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}

$q = 'SELECT * FROM tbl_user WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));

if($query->rowCount() == 0){
header('Location: Login.php?err=1');
}else{
$row = $query->fetch(PDO::FETCH_ASSOC);
$_POST['sess_userrole'] = $row['roles'];

if($_POST['sess_userrole'] == "renter"){
echo "renter";

}else if ($_POST['sess_userrole'] == "owner"){
echo "owner";

}
}
?>          

MainActivity.java

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

final String TAG = this.getClass().getName();
Button btnLogin;
EditText etUsername, etPassword;
TextView tvRegister;
CheckBox cbRemember;
SharedPreferences pref;
SharedPreferences.Editor editor;
boolean checkFlag;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    etUsername = (EditText) findViewById(R.id.etFirstname);
    etPassword = (EditText) findViewById(R.id.etPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    tvRegister = (TextView) findViewById(R.id.tvRegister);
    cbRemember = (CheckBox) findViewById(R.id.cbRemember);
    cbRemember.setOnCheckedChangeListener(this);
    checkFlag = cbRemember.isChecked();
    etUsername.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, etUsername.getText().toString());
        }
    });

    pref = MainActivity.this.getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
    editor = pref.edit();


    String username = pref.getString("username", "");
    String password = pref.getString("password", "");

    HashMap postData = new HashMap();
    postData.put("username", username);
    postData.put("password", password);

    if (!username.equals("") && (!password.equals(""))) {
        PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
                new AsyncResponse() {
                    @Override
                    public void processFinish(String s) {

                        if (s.contains("renter")) {
                            Log.d(TAG, s);
                            Log.d(TAG,pref.getString("username", ""));
                            Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
                            Intent in = new Intent(MainActivity.this, RenterTabs.class);
                            startActivity(in);
                            MainActivity.this.finish();

                        } else if (s.contains("owner")) {
                            Log.d(TAG, s);
                            Log.d(TAG,pref.getString("username", ""));
                            Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
                            Intent in = new Intent(MainActivity.this, OwnerTabs.class);
                            startActivity(in);
                            MainActivity.this.finish();
                        } else {
                            Toast.makeText(MainActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        task1.execute("http://carkila.esy.es/carkila/authenticate.php");
    }

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HashMap postData = new HashMap();
            postData.put("username", etUsername.getText().toString());
            postData.put("password", MD5.encrypt(etPassword.getText().toString()));

            PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
                    new AsyncResponse() {
                        @Override
                        public void processFinish(String s) {
                            Log.d(TAG,s);
                            if (s.contains("renter")) {
                                if (checkFlag) {
                                    editor.putString("username", etUsername.getText().toString());
                                    editor.putString("password", MD5.encrypt(etPassword.getText().toString()));
                                    editor.apply();
                                }
                                Intent in = new Intent(MainActivity.this, RenterTabs.class);
                                startActivity(in);
                                finish();

                            } else if (s.contains("owner")) {

                                if (checkFlag) {
                                    editor.putString("username", etUsername.getText().toString());
                                    editor.putString("password", MD5.encrypt(etPassword.getText().toString()));
                                    editor.apply();
                                }
                                editor.putString("username", etUsername.getText().toString());
                                editor.putString("password", MD5.encrypt(etPassword.getText().toString()));
                                editor.apply();

                                Intent in = new Intent(MainActivity.this, OwnerTabs.class);
                                startActivity(in);
                                finish();
                            } else {
                                Toast.makeText(MainActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            task1.execute("http://carkila.esy.es/carkila/authenticate.php");
        }
    });

    tvRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent in = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(in);
        }
    });

}

@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    checkFlag = b;
    Log.d(TAG, "checkflag: " + checkFlag);
}
}

1 个答案:

答案 0 :(得分:1)

你的PHP代码应该是这样的,

<?php 
require 'database-config.php';

if(isset($_POST['username']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $q = 'SELECT * FROM tbl_user WHERE username=:username AND password=:password';

    $query = $dbh->prepare($q);

    $query->execute(array(':username' => $username, ':password' => $password));

    if($query->rowCount() == 0) {
        echo "-1";
    } else {
        $row = $query->fetch(PDO::FETCH_ASSOC);
        $_POST['sess_userrole'] = $row['roles'];
        if($_POST['sess_userrole'] == "renter") {
            echo "renter";
        } else if ($_POST['sess_userrole'] == "owner") {
            echo "owner";
        }
    }
} else {
    echo "-1";
}
?>

您没有将usernamepassword保存到SharedPreferences。所以你永远不会回来。您应该在登录成功后保存它。

你的Android代码应该是这样的,

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    final String TAG = this.getClass().getName();
    Button btnLogin;
    EditText etUsername, etPassword;
    TextView tvRegister;
    CheckBox cbRemember;
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    boolean checkFlag;
    HashMap<String, String> postData = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        etUsername = (EditText) findViewById(R.id.etFirstname);
        etPassword = (EditText) findViewById(R.id.etPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        tvRegister = (TextView) findViewById(R.id.tvRegister);
        cbRemember = (CheckBox) findViewById(R.id.cbRemember);
        cbRemember.setOnCheckedChangeListener(this);
        checkFlag = cbRemember.isChecked();
        etUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, etUsername.getText().toString());
            }
        });

        pref = MainActivity.this.getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
        String username = pref.getString("username", "");
        String password = pref.getString("password", "");

        if (!username.equals("") && (!password.equals(""))) {
            postData.put("username", username);
            postData.put("password", password);
            authenticate(postData);
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postData.put("username", etUsername.getText().toString());
                postData.put("password", MD5.encrypt(etPassword.getText().toString()));

                authenticate(postData);
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent in = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(in);
            }
        });

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        checkFlag = b;
        Log.d(TAG, "checkflag: " + checkFlag);
    }

    private void authenticate(final HashMap<String, String> postData){
        PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
                new AsyncResponse() {
                    @Override
                    public void processFinish(String s) {
                        Log.d(TAG, s);
                        if (s.contains("renter")) {

                            if(checkFlag){
                                // Login success, Save to prefs
                                editor = pref.edit();
                                editor.putString("username", postData.get("username"));
                                editor.putString("password", postData.get("password"));
                                editor.commit();
                            }

                            Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
                            Intent in = new Intent(MainActivity.this, RenterTabs.class);
                            startActivity(in);
                            MainActivity.this.finish();

                        } else if (s.contains("owner")) {

                            if(checkFlag){
                                // Login success, Save to prefs
                                editor = pref.edit();
                                editor.putString("username", postData.get("username"));
                                editor.putString("password", postData.get("password"));
                                editor.commit();
                            }

                            Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
                            Intent in = new Intent(MainActivity.this, OwnerTabs.class);
                            startActivity(in);
                            MainActivity.this.finish();
                        } else if (s.equals("-1")) {
                            Toast.makeText(MainActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        task1.execute("http://carkila.esy.es/carkila/authenticate.php");
    }
}