两个表访问Android中的单个数据库

时间:2013-11-06 09:42:37

标签: android database

我已经使用一些教程编写了登录功能来存储用户名和密码。它工作得很好。一段时间后,我需要在单个数据库中管理两个表。我是通过关注这个网站实现的。

但我没有这样的表错误。任何帮助,将不胜感激。这是我的代码:

public class LoginDataBaseAdapter{

 public static final String ROW_ID = "_id";
    public static final String USERNAME = "name";
    public static final String PASSWORD = "password";


    private static final String DATABASE_TABLE = "users";



    public  SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;

    private DatabaseHelper dbHelper;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DatabaseAdapter.DATABASE_NAME,null, DatabaseAdapter.DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase arg0) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
            // TODO Auto-generated method stub

        }
    }

    public LoginDataBaseAdapter(Context _context) 
    {

        this.context = _context;

    }
    public  LoginDataBaseAdapter open() throws SQLException 
    {

        this.dbHelper = new DatabaseHelper(this.context);
        this.db = this.dbHelper.getWritableDatabase();

        return this;
    }
    public void close() 
    {
        dbHelper.close();
    }

     public void createUsers(String name, String pass){
            ContentValues initialValues = new ContentValues();
            initialValues.put(USERNAME, name);
            initialValues.put(PASSWORD, pass);
            db.insert(DATABASE_TABLE, null, initialValues);
        }

     public boolean deleteUser(long rowId) {

            return this.db.delete(DATABASE_TABLE, ROW_ID + "=" + rowId, null) > 0; 
            }

     public Cursor getAllUsers() {

            return this.db.query(DATABASE_TABLE, new String[] { ROW_ID,
                    USERNAME, PASSWORD }, null, null, null, null, null);
        }
     public String getUser(String username) throws SQLException {

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



        }
     public boolean updateUser(long rowId, String name, String pass,
                String year){
            ContentValues args = new ContentValues();
            args.put(USERNAME, name);
            args.put(PASSWORD, pass);


            return this.db.update(DATABASE_TABLE, args, ROW_ID + "=" + rowId, null) >0; 
        }



    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }

    /*public void insertEntry(String userName,String password)
    {
       ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("USERNAME", userName);
        newValues.put("PASSWORD",password);

        // Insert the row into your table
        db.insert("LOGIN", null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
    }
    public int deleteEntry(String UserName)
    {
        //String id=String.valueOf(ID);
        String where="USERNAME=?";
        int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
       // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }   */
/*  public String getSinlgeEntry(String userName)
    {
        Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
        if(cursor.getCount()<1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;                
    }*/
    /*public void  updateEntry(String userName,String password)
    {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("USERNAME", userName);
        updatedValues.put("PASSWORD",password);

        String where="USERNAME = ?";
        db.update("LOGIN",updatedValues, where, new String[]{userName});               
    }
*/


}

这是我的Adapter类:

public class DatabaseAdapter {

//  public static final String DATABASE_NAME = "example"; 

public static final int DATABASE_VERSION = 1;

private static final String CREATE_TABLE_USERS =
   "create table users (_id integer primary key autoincrement, " 
+ LoginDataBaseAdapter.USERNAME+ " TEXT," 
+ LoginDataBaseAdapter.PASSWORD+ " TEXT," 
+ ");";

private static final String CREATE_TABLE_REMIND = "create table remind (_id integer primary key autoincrement, " //$NON-NLS-1$
+MedicationDBAdapter.MEDICINAME+" TEXT," 
+MedicationDBAdapter.MEDICINEDIR+" TEXT," 
+ ");";

public static final String DATABASE_NAME="example.db";




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


public DatabaseAdapter(Context ctx)
{
    this.context = ctx;
    this.DBHelper = new DatabaseHelper(this.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(CREATE_TABLE_USERS);
        db.execSQL(CREATE_TABLE_REMIN);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, 
    int newVersion) 
    {               
        // Adding any table mods to this guy here
    }
} 

/**
 * open the db
 * @return this
 * @throws SQLException
 * return type: DBAdapter
 */
public DatabaseAdapter open() throws SQLException 
{
    this.db = this.DBHelper.getWritableDatabase();
    return this;
}

/**
 * close the db 
 * return type: void
 */
public void close() 
{
    this.DBHelper.close();
}
}

1 个答案:

答案 0 :(得分:0)

尝试这样的东西,看起来更整洁(我有4张桌子):

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String TAG = "DatabaseHelper";
    private static DatabaseHelper sInstance = null;
    private static final String DATABASE_NAME = "dbname";
    private static final int DATABASE_VERSION = 1;

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // create books table
        String sql = "CREATE TABLE [Book] ([_id] INTEGER NOT NULL PRIMARY KEY, [Arabic] TEXT, [English] TEXT)";
        db.execSQL(sql);

        // create hadiths table
        sql = "CREATE TABLE [Hadith] ([_id] INTEGER NOT NULL PRIMARY KEY, [Arabic] TEXT, [English] TEXT, [Urdu] TEXT, [Indonesian] TEXT, [Book] INTEGER NOT NULL, FOREIGN KEY(Book) REFERENCES Book(_id))";
        db.execSQL(sql);

        // add index on hadiths table
        sql = "CREATE INDEX [FK_Book] ON [Hadith]([Book] ASC)";
        db.execSQL(sql);

        // create bookmarks table
        sql = "CREATE TABLE [Bookmark] ([_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [Hadith] INTEGER NOT NULL, [Summary] TEXT)";
        db.execSQL(sql);

        // create settings table
        sql = "CREATE TABLE [Setting] ([_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [Name] TEXT, [Value] TEXT)";
        db.execSQL(sql);

        // add a sample book
        sql = "INSERT INTO Book (_id,Arabic,English) VALUES(1,'كتاب بدء الوحى','Revelation')";
        db.execSQL(sql);

        // insert sample hadith
        sql = "INSERT INTO Hadith (_id,Arabic,English,Urdu,Indonesian,Book) VALUES(1,'English...','Arabic...','Urdu...','Indonesian...',1)";
        db.execSQL(sql);

        // insert sample bookmark
        sql = "INSERT INTO Bookmark (Hadith,Summary) VALUES(1,'Summary...')";
        db.execSQL(sql);

        // insert default settings
        sql = "INSERT INTO Setting (Name,Value) VALUES('FontSize','17')";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w(DatabaseHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS Setting");
        db.execSQL("DROP TABLE IF EXISTS Bookmark");
        db.execSQL("DROP TABLE IF EXISTS Hadith");
        db.execSQL("DROP TABLE IF EXISTS Book");
        onCreate(db);
    }

    public static DatabaseHelper getInstance(Context context)
    {
        // Use the application context, which will ensure that you
        // don't accidentally leak an Activity's context.
        // See this article for more information: http://bit.ly/6LRzfx
        if (sInstance == null)
        {
            sInstance = new DatabaseHelper(context.getApplicationContext());
        }
        return sInstance;
    }

    /**
     * Constructor should be private to prevent direct instantiation.
     * make call to static factory method "getInstance()" instead.
     */
    private DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}

然后使用以下代码从代码的任何部分调用它:

// get list of books from db
DatabaseHelper dbHelper = DatabaseHelper.getInstance(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
final Cursor cursor = db.rawQuery("SELECT * FROM Book", null);
while(cursor.moveToNext())
{
    bookNames.add(cursor.getString(2));
}