0

我正在尝试使用我的 sqlite 数据库实现会话(共享首选项)。

我有想保存到共享首选项的用户名和密码字段。但是,我只想在登录有效的情况下这样做。

如果是有效登录,请登录用户(按指定转到下一个活动)并将其保存在共享首选项中。这是我的目标;但是,我无法实现这一点。

这是我的代码:

package com.example.votingapp;

import com.example.votingapp.library.DatabaseHandler;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText inputUserName;
    EditText inputUserPass;
    Button btnLogin;
    Button btnRegister;
    DatabaseHandler database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setting default screen to activity_main.xml
        setContentView(R.layout.activity_main);

        //Importing all assets like buttons, text fields
        inputUserName = (EditText) findViewById(R.id.UserName);
        inputUserPass = (EditText) findViewById(R.id.UserPass);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegister = (Button) findViewById(R.id.btnRegister);

        //SharedPreferences
        SharedPreferences settings = getSharedPreferences("MYPREFS", 0);

        String username = settings.getString("username", null);
        String password = settings.getString("password", null);

        if(!(username==null) && !(password==null)){
            Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
            startActivity(dashboard);
            finish();
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String userName = inputUserName.getText().toString();
                String userPass = inputUserPass.getText().toString();
                boolean validLogin = validateLogin(userName, userPass, MainActivity.this);

                //SharedPreferences
                SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
                SharedPreferences.Editor editor = settings.edit();

                if(validLogin){
                    editor.putString("username", userName);
                    editor.putString("password", userPass);
                    editor.commit();

                }else{
                    inputUserName.setText(settings.getString("username", ""));
                    inputUserPass.setText(settings.getString("password", ""));
                }



                if(userName.equals("") || userName == null){
                    Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
                }else if(userPass.equals("") || userPass == null){
                    Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
                }else{
                    if(validLogin){ 
                        //Show a dialog of login successful
                        Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();         
                        Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
                        //Close views before starting Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        finish();
                    }
                }

            }
            });//Login Button On SetListener

        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(Register);
                finish();
            }
        });//Register Button onClickListener

    }//On Create


    public boolean validateLogin(String userName, String userPass, Context context) {

        DatabaseHandler database = new DatabaseHandler(getApplicationContext());
        SQLiteDatabase db = database.getReadableDatabase();

        //SELECT
        String[] columns = {"userId"};

        //WHERE clause
        String selection = "userName=? AND userPass=?";

        //WHERE clause arguments
        String[] selectionArgs = {userName, userPass};
        Cursor c = null;

        try{
        //SELECT userId FROM login WHERE username=userName AND password=userPass
        c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
        c.moveToFirst();
        c.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        int i = c.getCount();
        if(i <= 0){
            Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }//validate Login

}//Mainactivity
4

3 回答 3

1

您没有将文本字段的用户名和密码存储到 SharedPreferences,但您的代码将空值存储到 sharedPreferences。试试这个代码

package com.example.votingapp;

import com.example.votingapp.library.DatabaseHandler;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText inputUserName;
    EditText inputUserPass;
    Button btnLogin;
    Button btnRegister;
    DatabaseHandler database;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setting default screen to activity_main.xml
        setContentView(R.layout.activity_main);

        //Importing all assets like buttons, text fields
        inputUserName = (EditText) findViewById(R.id.UserName);
        inputUserPass = (EditText) findViewById(R.id.UserPass);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegister = (Button) findViewById(R.id.btnRegister);




        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String userName = inputUserName.getText().toString();
                String userPass = inputUserPass.getText().toString();

                if(userName.equals("") || userName == null){
                    Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
                }else if(userPass.equals("") || userPass == null){
                    Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
                }else{
                    boolean validLogin = validateLogin(userName, userPass, MainActivity.this);
                    if(validLogin){ 

                        //SharedPreferences
                        SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
                        inputUserName.setText(settings.getString("username", ""));
                        inputUserPass.setText(settings.getString("password", ""));

                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString("username", userName);
                        editor.putString("password", userPass);
                        editor.commit();

                        String username = settings.getString("username", null);
                        String password = settings.getString("password", null);

                        if(!(username==null) && !(password==null)){
                            Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
                            startActivity(dashboard);
                            finish();
                        }
                        //Show a dialog of login successful
                        Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();         
                        Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
                        //Close views before starting Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        finish();
                    }
                }

            }
            });//Login Button On SetListener

        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(Register);
                finish();
            }
        });//Register Button onClickListener

    }//On Create


    public boolean validateLogin(String userName, String userPass, Context context) {

        DatabaseHandler database = new DatabaseHandler(getApplicationContext());
        SQLiteDatabase db = database.getReadableDatabase();

        //SELECT
        String[] columns = {"userId"};

        //WHERE clause
        String selection = "userName=? AND userPass=?";

        //WHERE clause arguments
        String[] selectionArgs = {userName, userPass};
        Cursor c = null;

        try{
        //SELECT userId FROM login WHERE username=userName AND password=userPass
        c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
        c.moveToFirst();
        c.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        int i = c.getCount();
        if(i <= 0){
            Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }//validate Login

}//Mainactivity
于 2013-11-12T05:36:42.580 回答
0

您可以使用它来存储它,而不是存储UserName和在数据库PasswordSharedPreferences

于 2013-11-12T06:09:14.117 回答
0

在 ValidateLogin() 中,您正在关闭游标,在关闭它之后,您正在调用 cursor.getCount()。这是错误的。检查我编辑的代码。

package com.example.votingapp;

import com.example.votingapp.library.DatabaseHandler;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText inputUserName;
    EditText inputUserPass;
    Button btnLogin;
    Button btnRegister;
    DatabaseHandler database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setting default screen to activity_main.xml
        setContentView(R.layout.activity_main);

        //Importing all assets like buttons, text fields
        inputUserName = (EditText) findViewById(R.id.UserName);
        inputUserPass = (EditText) findViewById(R.id.UserPass);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegister = (Button) findViewById(R.id.btnRegister);

        //SharedPreferences
        SharedPreferences settings = getSharedPreferences("MYPREFS", 0);

        String username = settings.getString("username", null);
        String password = settings.getString("password", null);

        if(username!=null && password!=null){
            Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
            startActivity(dashboard);
            finish();
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                String userName = inputUserName.getText().toString();
                String userPass = inputUserPass.getText().toString();
                boolean validLogin = validateLogin(userName, userPass, MainActivity.this);

                if(validLogin){

                    //SharedPreferences
                    SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("username", userName);
                    editor.putString("password", userPass);
                    editor.commit();

                }else{
                    inputUserName.setText(settings.getString("username", ""));
                    inputUserPass.setText(settings.getString("password", ""));
                }



                if(userName.equals("") || userName == null){
                    Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
                }else if(userPass.equals("") || userPass == null){
                    Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
                }else{
                    if(validLogin){ 
                        //Show a dialog of login successful
                        Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();         
                        Intent dashboard = new Intent(MainActivity.this, DashboardActivity.class);
                        //Close views before starting Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        finish();
                    }
                }

            }
            });//Login Button On SetListener

        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent Register = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(Register);
                finish();
            }
        });//Register Button onClickListener

    }//On Create


    public boolean validateLogin(String userName, String userPass, Context context) {

        DatabaseHandler database = new DatabaseHandler(getApplicationContext());
        SQLiteDatabase db = database.getReadableDatabase();

        //SELECT
        String[] columns = {"userId"};

        //WHERE clause
        String selection = "userName=? AND userPass=?";

        //WHERE clause arguments
        String[] selectionArgs = {userName, userPass};
        Cursor c = null;

        try{
        //SELECT userId FROM login WHERE username=userName AND password=userPass
        c = db.query(DatabaseHandler.TABLE_USERS, columns, selection, selectionArgs, null, null, null);
        c.moveToFirst();

        int i = c.getCount();
c.close();        
if(i <= 0){
            Toast.makeText(getApplicationContext(), "Incorrect Login..\nTry Again", Toast.LENGTH_SHORT).show();
            return false;
            }

        return true;
        }catch(Exception e){
            e.printStackTrace();
return false;
        }
    }//validate Login

}//Mainactivity
于 2013-11-12T06:21:17.337 回答