SQL Lite android应用程序登录 [英] SQL Lite android app login

查看:153
本文介绍了SQL Lite android应用程序登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个游戏的时刻,我想要的是我的登录屏幕,以便能够检查我已经存储在我的数据库中的用户名和密码是正确的,当它是正确的,登录按钮是点击打开一个新的活动。我已经建立了数据库,也是一个登录我只需要弄清楚如何检查我的数据库,而不仅仅是字段中的文本。



添加的登录信息存储在数据库中:



用户名:test



密码:1234



感谢提前ps我完全是新的Java和SQL lite这只是为了学校工作,没有办法在现实世界中使用我只想要简单:)



登录屏幕活动:

 包com.C05025.noughtsandcrosses; 

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;

public class LogInScreen extends Activity {

EditText txtUsername;
EditText txtPassword;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
txtUsername =(EditText)findViewById(R.id.EditUsername);
txtPassword =(EditText)findViewById(R.id.EditPassword);
}

public void newLogIn(View view){
if(txtUsername.getText()。toString()。equals(test)&&
txtPassword.getText()。toString()。equals(1234)){
Intent intent = new Intent(LogInScreen.this,MainMenu.class);
startActivity(intent);
}
}

数据库类:

 包com.C05025.noughtsandcrosses; 

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME =userDB.db;
private static final String TABLE_USERS =users;

public static final String COLUMN_NAME =name;
public static final String COLUMN_PASSWORD =password;

public DBHandler(Context context,String name,CursorFactory factory,
int version){
super(context,DATABASE_NAME,factory,DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db){
String CREATE_USER_TABLE =CREATE TABLE+ TABLE_USERS +(
+ INTEGER PRIMARY KEY,+ COLUMN_NAME +TEXT,
+ COLUMN_PASSWORD +INTEGER+);
db.execSQL(CREATE_USER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase arg0,int arg1,int arg2){

}

public void addUser(LogIn user){

ContentValues values = new ContentValues();
values.put(COLUMN_NAME,user.getName());
values.put(COLUMN_PASSWORD,user.getPassword());

SQLiteDatabase db = this.getWritableDatabase();

db.insert(TABLE_USERS,null,values);
db.close();
}

public LogIn findUser(String Username){
String query =Select * FROM+ TABLE_USERS
+WHERE+ COLUMN_NAME += \
+用户名+\;

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query,null);

LogIn User = new LogIn();

if(cursor.moveToFirst()){
cursor.moveToFirst();
User.setName(cursor.getString(1));
User.setPassword(Integer.parseInt(cursor.getString(2)));
cursor.close();
}
else {
User = null;
}

db.close();
return User;
}
}


解决方案



创建类 DBAdapter.java 并添加以下代码。

  public class DBAdapter {
private static final String DATABASE_NAME =您的数据库名称;
private static final String DATABASE_CREATE_USERS =create table TABLE_NAME(
UserID integer primary key autoincrement,+Username text,Password text); ;

private static final String DATABASE_SELECT_USERS =users;
public static final String USER_ID =UserID;
public static final String USER_NAME =Username;
public static final String USER_PASSWORD =Password;

private final上下文上下文;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;

DBAdapter(Contex ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

私人静态类DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db){
System.out.println(Creating table);
db.execSQL(DATABASE_CREATE_USERS);
}

public void onUpgrade(SQLiteDatabase arg0,int arg1,int arg2){

}
}

DBAdapter open()throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}

public void close(){
DBHelper.close();
}

public Cursor fetchUser(String username,String password){
Cursor myCursor = db.query(DATABASE_SELECT_USERS,
new String [] {USER_ID,USER_NAME, USER_PASSWORD},
USER_NAME +='+用户名+'AND+
USER_PASSWORD +='+密码+',null,null,null,null);

if(myCursor!= null){
myCursor.moveToFirst();
}
return myCursor;
}

public void InsertData(String username,String password){
String sql =INSERT INTO users(Username,Password)VALUES('+ username + + password +');
db.execSQL(sql);
}
}

,然后创建您的Java文件



Login.java

  b $ b {

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final EditText txt_username =(EditText)findViewById(R.id.editText1);
final EditText txt_psw =(EditText)findViewById(R.id.editText2);

Button btn_signin =(Button)findViewById(R.id.button1);

//点击按钮时实现Button Listener的内部类。
btn_signin.setOnClickListener(new OnClickListener(){
public void onClick(View v){
DBAdapter db = new DBAdapter(getBaseContext());
db.open
db.InsertData(Chao,1234);
Log.v(LoginDetails,txt_username.getText()。toString()+../ ..
+ txt_psw.getText()。toString());

//使用我们在DBAdapter中创建的fetchUser方法访问用户
Cursor cur = db.fetchUser(txt_username.getText (),
txt_psw.getText()。toString());

//如果要查看具有这些登录详细信息的用户数,请使用此行
System。 out.println(cur.getCount()+ cur.getCount());

if(cur.getCount()!= 0){
String usn = cur.getString 1);
if(usn.equals(Chao)){

}
else {

}

系统。 out.println(Query succedded);
Toast.makeText(getBaseContext(),Success!Valid User name and password,Toast.LENGTH_LONG).show();

db.close();
}
else
Toast.makeText(getBaseContext(),请输入有效的用户名和密码,Toast.LENGTH_LONG).show();
} //关闭onClick方法
}); //关闭onClickListener
}
}


I am working on a game at the moment and all I want is my login screen to be able to check that the username and password I have already stored in my database is correct and when it is correct and the log in button is clicked to open a new activity. I have my database built and also a login I just need to figure out how to check against my database not just the text in the fields.

I already have a pre-added login stored in the database:

Username: test

Password: 1234

Thanks in advance p.s I am completely new to Java and SQL lite this is only for school work and is in no way going to be used in the real world I only want it to be simple :)

Login Screen Activity:

package com.C05025.noughtsandcrosses;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;

public class LogInScreen extends Activity {

    EditText txtUsername;
    EditText txtPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginscreen);
        txtUsername = (EditText) findViewById(R.id.EditUsername);
        txtPassword = (EditText) findViewById(R.id.EditPassword);
    }

    public void newLogIn(View view) {
        if(txtUsername.getText().toString().equals("test") && 
                txtPassword.getText().toString().equals("1234")) {
            Intent intent = new Intent(LogInScreen.this, MainMenu.class);
            startActivity(intent);
    }   
}

Database Class:

package com.C05025.noughtsandcrosses;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "userDB.db";
    private static final String TABLE_USERS   = "users";

    public static final String COLUMN_NAME     = "name";
    public static final String COLUMN_PASSWORD = "password";

    public DBHandler(Context context, String name, CursorFactory factory,
            int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USER_TABLE = "CREATE TABLE " +    TABLE_USERS + "("
        + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," 
        + COLUMN_PASSWORD + " INTEGER" + ")";
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

    }

    public void addUser(LogIn user) {

        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, user.getName());
        values.put(COLUMN_PASSWORD, user.getPassword());

        SQLiteDatabase db = this.getWritableDatabase();

        db.insert(TABLE_USERS, null, values);
        db.close();
    }

    public LogIn findUser(String Username) {
        String query = "Select * FROM " + TABLE_USERS 
        + " WHERE " + COLUMN_NAME + " =  \""
        + Username + "\"";

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.rawQuery(query, null);

        LogIn User = new LogIn();

        if (cursor.moveToFirst()) {
            cursor.moveToFirst();
            User.setName(cursor.getString(1));
            User.setPassword(Integer.parseInt(cursor.getString(2)));
            cursor.close();
        } 
        else {
            User = null;
        }

    db.close();
    return User;
    }
}

解决方案

You can try below way.

Create class called DBAdapter.java and add following code.

public class DBAdapter {
    private static final String DATABASE_NAME         = "Your database name"; 
    private static final String DATABASE_CREATE_USERS = "create table TABLE_NAME (
    UserID integer primary key autoincrement, " + "Username text, Password text);" ; 

    private static final String DATABASE_SELECT_USERS = "users";
    public static final String USER_ID       = "UserID";
    public static final String USER_NAME     = "Username";
    public static final String USER_PASSWORD = "Password ";

    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;  

    DBAdapter(Contex ctx) {
        this.context = ctx;
        DBHelper     = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            System.out.println("Creating table");
            db.execSQL(DATABASE_CREATE_USERS);
        }

        public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

        }
    }   

    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        DBHelper.close();
    }

    public Cursor fetchUser(String username, String password) {  
        Cursor myCursor = db.query(DATABASE_SELECT_USERS,   
        new String[] { USER_ID, USER_NAME, USER_PASSWORD },   
                         USER_NAME + "='" + username + "' AND " +   
                         USER_PASSWORD + "='" + password + "'", null, null, null, null);  

        if (myCursor != null) {  
            myCursor.moveToFirst();  
        }  
        return myCursor;  
    }  

    public void InsertData(String username, String password) {
        String sql = "INSERT INTO users (Username,Password) VALUES('"+username+"','"+password+"')";
        db.execSQL(sql);
    }
}

and then create your Java file

Login.java

public class Login extends Activity 
{

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final EditText txt_username = (EditText) findViewById(R.id.editText1);
        final EditText txt_psw      = (EditText) findViewById(R.id.editText2);

        Button btn_signin = (Button) findViewById(R.id.button1);

        // Inner class to implement Button Listener when button is clicked.
        btn_signin.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {                   
                DBAdapter db = new DBAdapter(getBaseContext());
                db.open();                              
                db.InsertData("Chao", "1234");              
                Log.v("LoginDetails", txt_username.getText().toString()+"../.."
                      +txt_psw.getText().toString());

                // Accessing user using the fetchUser method we created in DBAdapter
                Cursor cur = db.fetchUser( txt_username.getText().toString(), 
                                           txt_psw.getText().toString());

                // Use this line if you want to see the number of users with these login details
                System.out.println("cur.getCount()   "+cur.getCount());

                if(cur.getCount()!=0) {
                    String usn=cur.getString(1);
                    if(usn.equals("Chao")) {   

                    }
                    else { 

                    }

                    System.out.println("Query succedded");
                    Toast.makeText(getBaseContext(), "Success! Valid User name and password", Toast.LENGTH_LONG).show();

                    db.close();
                }
                else
                    Toast.makeText(getBaseContext(), "Please enter Valid User name and password", Toast.LENGTH_LONG).show();
            } //Closes the onClick method
        }); //Closes the onClickListener
    }
}

这篇关于SQL Lite android应用程序登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆