数据库文件无法创建Android

时间:2015-09-29 19:19:30

标签: java android sqlite

我正在Android平台上实现一个软件,我正在使用SQLLite数据库。我已经把每个代码都连接到DBUserAdapter类和其他loginScreen和registerScreen类中的数据库,它们分别有登录和注册方法的编码。

当我单击“注册”按钮时,显示数据库文件不可用的日志。任何人都可以帮我解决这个问题。在此先感谢.. :))

这是我的DBUserAdapter.java类

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

import java.sql.SQLException;

/**
* Created by Miuranga Salgado on 9/29/2015.
*/
public class DBUserAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PASSHINT = "passHint";
public static final String TAG = "DBAdapter";

public static final String DATABASE_NAME = "usersdb";
public static final String DATABASE_TABLE = "userInfo";
public static final int DATABASE_VERSION = 1;

public static final String DATABASE_CREATE = "CREATE TABLE "+DATABASE_TABLE+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, username varchar(100)TEXT NOT NULL, password varchar(100)TEXT NOT NULL, passHint varchar(100)TEXT NOT NULL);";

private Context context = null;
private DatabaseHelper dbHelper;
public SQLiteDatabase db;

public DBUserAdapter(Context context){
    this.context = context;
    dbHelper = new DatabaseHelper(context);
}

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading Database from Version "+oldVersion+" to "+newVersion+", Which will Destroy all old Data");
        db.execSQL("DROP TABLE IF EXISTS userInfo");
        onCreate(db);
    }
}

public void open() throws SQLException{
    db = dbHelper.getWritableDatabase();
}

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

public SQLiteDatabase getDatabaseInstance(){
    return db;
}

public boolean AddUser(String username, String password, String passHint){
    try {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_USERNAME, username);
        initialValues.put(KEY_PASSWORD, password);
        initialValues.put(KEY_PASSHINT, passHint);
        db.insert(DATABASE_TABLE, null, initialValues);
        db.close();
        return true;
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return false;
}

public boolean Login(String username, String password) throws SQLException{
    Cursor cursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username, password});
    if(cursor != null){
        if (cursor.getCount() > 0){
            return true;
        }
    }
    return false;
}

public String getPassword(String userName){
    Cursor cursor = db.query(DATABASE_TABLE, null, "username=?", new String[]{userName}, null, null, null);
    if (cursor.getCount()<1){
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
    return password;
}

public boolean register(String username, String password, String passHint)throws SQLException{
    Cursor cursor = db.rawQuery("INSERT INTO "+DATABASE_TABLE+" VALUES('?', '?', '?', '?');", new String[]{username, password, passHint});
    if(cursor != null){
        if(cursor.getCount() > 0){
            return true;
        }
    }
    return false;
}
}

这是我的loginScreen.java类

public class loginScreen extends Activity {

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

    final EditText loginUser = (EditText) findViewById(R.id.inputUser);
    final EditText loginPass = (EditText) findViewById(R.id.inputPass);

    Button btnLogin = (Button) findViewById(R.id.loginBtn);
    Button btnRegister = (Button) findViewById(R.id.registerBtn);
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String username = loginUser.getText().toString();
            String password = loginPass.getText().toString();
            //String relPassword = userAdapter.getPassword(username);
            try {
                if (username.length() > 0 && password.length() > 0) {
                    DBUserAdapter dbAdapter = new DBUserAdapter(loginScreen.this);
                    dbAdapter.open();
                    if (dbAdapter.Login(username, password)) {
                        Toast.makeText(loginScreen.this, "Successfully Logged In", Toast.LENGTH_LONG).show();

                    } else {
                        Toast.makeText(loginScreen.this, "Invalid Username or Password", Toast.LENGTH_LONG).show();
                    }
                    dbAdapter.close();
                }
            } catch (Exception e) {
                Toast.makeText(loginScreen.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
            //if(password.equals(relPassword)) {
            //    Toast.makeText(loginScreen.this, "Successfully Logged In", Toast.LENGTH_LONG).show();
            //}
            //else {
            //    Toast.makeText(loginScreen.this, "Sorry, Invalid Username or Password", Toast.LENGTH_LONG).show();
            //}
        }
    });

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(loginScreen.this, registerScreen.class);
            startActivity(intent);
        }
    });
}
}

这是registerScreen.java类

public class registerScreen extends Activity{

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

    final EditText regUsername = (EditText)findViewById(R.id.regUserName);
    final EditText regPassword = (EditText)findViewById(R.id.regPassword);
    final EditText regPassHint = (EditText)findViewById(R.id.regPassHint);

    Button regButton = (Button)findViewById(R.id.btnCreateAcc);
    regButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String username = regUsername.getText().toString();
            String password = regPassword.getText().toString();
            String passHint = regPassHint.getText().toString();
            try {
                if (username.length() > 0 && password.length() > 0 && passHint.length() > 0){
                    DBUserAdapter dbAdapter = new DBUserAdapter(registerScreen.this);
                    dbAdapter.open();
                    if(dbAdapter.AddUser(username, password, passHint)){
                        Toast.makeText(registerScreen.this, "You're Registered Successfully", Toast.LENGTH_LONG).show();
                    }
                    else {
                        Toast.makeText(registerScreen.this, "User Not Registered", Toast.LENGTH_LONG).show();
                    }
                    dbAdapter.close();
                }
            }
            catch (Exception e){
                Toast.makeText(registerScreen.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
            }

    });
}
}

这是错误日志

      09-30 00:28:57.821       482-482/supprioritizer.warnerit.com.supermarketprioritizer E/SQLiteLog﹕ (1) no such table: userInfo
09-30 00:28:57.829      482-482/supprioritizer.warnerit.com.supermarketprioritizer E/SQLiteDatabase﹕ Error inserting passHint=123 password=123 username=Randula
    android.database.sqlite.SQLiteException: no such table: userInfo (code 1): , while compiling: INSERT INTO userInfo(passHint,password,username) VALUES (?,?,?)
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:891)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:502)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
            at supprioritizer.warnerit.com.supermarketprioritizer.DBUserAdapter.AddUser(DBUserAdapter.java:73)
            at supprioritizer.warnerit.com.supermarketprioritizer.registerScreen$1.onClick(registerScreen.java:37)
            at android.view.View.performClick(View.java:4797)
            at android.view.View$PerformClick.run(View.java:19899)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5309)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

2 个答案:

答案 0 :(得分:2)

您的查询的问题是您在此处使用了一些错误的数据类型varchar(100)TEXT。您应该使用varchar(100)TEXT

String DATABASE_CREATE = "CREATE TABLE "+DATABASE_TABLE+"(_id INTEGER
PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT
NULL, passHint TEXT NOT NULL)";

答案 1 :(得分:2)

1。 更改您的创建表字符串,它无效,请尝试:

"CREATE TABLE "+DATABASE_TABLE+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, passHint TEXT NOT NULL);"

2。 升级数据库,尝试在构造函数中执行此操作:

public static final int DATABASE_VERSION = 2;
DatabaseHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}