SQL Lite 安卓应用登录

SQL Lite android app login(SQL Lite 安卓应用登录)

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

问题描述

我目前正在开发一款游戏,我想要的只是登录屏幕,以便能够检查我已经存储在数据库中的用户名和密码是否正确,以及何时正确并且登录按钮是单击以打开新活动.我已经建立了我的数据库和一个登录名,我只需要弄清楚如何检查我的数据库,而不仅仅是字段中的文本.

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:

用户名:test

密码:1234

提前感谢 p.s 我对 Java 和 SQL lite 完全陌生,这仅用于学校作业,绝不会在现实世界中使用我只希望它简单 :)

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 :)

登录屏幕活动:

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);
    }   
}

数据库类:

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.

创建名为 DBAdapter.java 的类并添加以下代码.

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);
    }
}

然后创建您的 Java 文件

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 安卓应用登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:SQL Lite 安卓应用登录

基础教程推荐