如何创建数据库并在sqlite android中填充它?

时间:2015-08-31 09:45:48

标签: android sqlite

我在为我的Android应用程序创建sqlite数据库时遇到问题。我正在使用SQLiteOpenHelper类,我已经成功创建了数据库,我确信通过logCat,但我认为我没有创建一个表并用虚拟数据填充它只是为了模拟一个登录程序。我只想创建数据库并在其中创建一个表并在表中插入一些数据,我想在另一个活动的onCreate方法中执行此操作。我会告诉你我的尝试。

以下是SQLiteOpenHelper类: -

public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "qpc.db";
public static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD = "password";
public DBHandler dbHandler;


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



@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_USERS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USERNAME + "Text ,"
            + COLUMN_PASSWORD + "Text );";
    db.execSQL(query);

    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_USERNAME,"test");
    contentValues.put(COLUMN_PASSWORD,"123");
    db.insert(TABLE_USERS,null,contentValues);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
    onCreate(db);
}


public void open() throws SQLException
{
    dbHandler.getWritableDatabase();
}


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

public boolean login(String username, String password){
    SQLiteDatabase db = getReadableDatabase();
    String query = "SELECT "+ COLUMN_ID + " FROM " + TABLE_USERS +
            " WHERE username= "+ COLUMN_USERNAME +
            " AND password= "+ COLUMN_PASSWORD + ";";


    Cursor cursor = db.rawQuery(query,new String[]{username,password});
    int count = cursor.getCount();
    if(cursor != null) {
        if (count > 0) {
            return true;
        }
    }
    return false;
}

以下是我在LoginActivity

中的称呼方式
public class LoginActivity extends ActionBarActivity {
    private static Button loginBtn;
    public static EditText usernameTxt,passwordTxt;
    private static String writtenUsername,writtenPassword;
    private Users user;
    private DBHandler dbHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //identifying login button
    loginBtn = (Button) findViewById(R.id.loginButton);

    //identifying username editText
    usernameTxt = (EditText) findViewById(R.id.username);

    //identifying password editText
    passwordTxt = (EditText) findViewById(R.id.password);

    dbHandler = new DBHandler(this, null, null, 1);


    //check if database exists
   File dbtest = getApplicationContext().getDatabasePath("qpc.db");
    if(dbtest.exists())
    {
    Log.d("Database23", "exists");
    }
    else {
        Log.d("Database23", "doesn't exist");
    }
}

//handling login button
public void attemptLogin(View view){
    //getting what was written in username and password editText
    writtenUsername = usernameTxt.getText().toString();
    writtenPassword = passwordTxt.getText().toString();
    try {
        if (!writtenUsername.matches("") && !writtenPassword.matches("")) {
            if (dbHandler.login(writtenUsername, writtenPassword) == true) {
                Toast.makeText(this, "yes", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "no", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
        }
    }catch(Exception e){
        Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:1)

create table查询中的间距错误。 试试这个。

String query = "CREATE TABLE " + TABLE_USERS + "("
        + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + COLUMN_USERNAME + " Text,"
        + COLUMN_PASSWORD + " Text);";

还要编写一个单独的方法来插入记录。不要在onCreate中这样做。

干杯

答案 1 :(得分:1)

你的错误是什么

您在数据库查询中添加 "EXTRA-SPACE" [CREATE TABLE]

 @Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_USERS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USERNAME + "Text ,"
            + COLUMN_PASSWORD + "Text );";
    db.execSQL(query);

首先请阅读android.database.sqlite和演示用途Android SQLite Database Tutorial