0

好的,所以我已经查看了大概 30 个不同的 SQLite 教程,甚至还有一些关于它的随机讨论。我不是一个程序员,我发现如果我能找到已经在做某事的人,并根据需要进行调整并给予信任,那么它可能比仅仅重新创建轮子更有效率。我敢肯定,我不是唯一一个有这种感觉的人。

在 Eclipse 中,我正在尝试为我的数据库管理类的上下文创建一个构造函数。这是完整的代码。它还没有完成,但在错误消失之前我无法取得进展,所以我们开始吧:

package com.bluej.movingbuddy;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.SQLException;
import android.util.Log;

public class MBDatabaseManager {



//Database Version
private final static int DATABASE_VERSION = 1;

//Database Name
private final static String DATABASE_NAME = "dbMovingBuddy";

//items and weights table name
private final static String tblInW = "ItemsAndWeights";
//items and weights table columns
private final static String InWID = "ID";
private final static String InWItem = "Item";
private final static String InWDesc = "Description";
private final static String InWWeightOne = "Weight1";
private final static String InWWeightTwo = "Weight2";
private final static String InWWeightThree = "Weight3";
private final static String InWWeightAvg = "WeightAvg";

//allowances table name
private final static String tblAllowances = "Allowances";
//allowances table columns
private final static String AllowancesID = "ID";
private final static String AllowancesRank = "Rank";
private final static String AllowancesWithDep = "WithDep";
private final static String AllowancesNoDep = "NoDep";

//estimator table name
private final static String tblEstimator = "Estimator";
//estimator table columns
private final static String EstimatorID = "ID";
private final static String EstimatorRoom = "Room";
private final static String EstimatorItem = "Weight";

//inventory table name
private final static String tblInventory = "Inventory";
//inventory table column
private final static String InventoryID = "ID";
private final static String InventoryItem = "Item";
private final static String InventoryWeight = "Weight";
private final static String InventoryValue = "Value";
private final static String InventoryImage1 = "Image1";
private final static String InventoryCondition = "Condition";
private final static String InventoryImage2 = "Image2";
private final static String InventoryNotes = "Notes";
private final static String InventoryMovingInstructions = "MovingInstructions";

//stunt table name
private final static String TABLE_NAME = "database_table";
//stunt table column names
private final static String TABLE_ROW_ID = "id";
private final static String TABLE_ROW_ONE = "table_row_one";
private final static String TABLE_ROW_TWO = "table_row_two";

public MBDatabaseManager(Context context) {
    // TODO Auto-generated constructor stub
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    //This string is used to create the database. It should be changed to suit your needs.

    //create items and weights table
    String dbCreateItemsAndWeights = "create table " +
    tblInW +
    " (" +
    InWID + " integer primary key autoincrement not null," +
    InWItem + " text," +
    InWDesc + " text," +
    InWWeightOne + " integer," +
    InWWeightTwo + " integer," +
    InWWeightThree + " integer," +
    InWWeightAvg + " integer" +
    ");";

    db.execSQL(dbCreateItemsAndWeights);

    //allowances table
    String dbCreateAllowances = "create table " +
    tblAllowances +
    " (" +
    AllowancesID + " integer primary key autoincrement not null," +
    AllowancesRank + " text," +
    AllowancesWithDep + " integer," +
    AllowancesNoDep + " integer" +
    ");";

    db.execSQL(dbCreateAllowances);

    //estimator table
    String dbCreateEstimator = "create table " +
    tblEstimator + 
    " (" +
    EstimatorID + " integer primary key autoincrement not null," +
    EstimatorRoom + " text," +
    EstimatorItem + " integer" +
    ");";

    db.execSQL(dbCreateEstimator);

    //inventory table
    String dbCreateInventory = "create table " +
    tblInventory + 
    " (" +
    InventoryID + " integer primary key autoincrement not null," +
    InventoryItem + " text," + 
    InventoryWeight + " integer," +
    InventoryValue + " integer," +
    InventoryImage1 + " blob," +
    InventoryCondition + " text," + 
    InventoryImage2 + " blob," + 
    InventoryNotes + " text," +
    InventoryMovingInstructions + " text" +
    ");";

    db.execSQL(dbCreateInventory);      

    //stunt table
    String newTableQueryString = "create table " +
    TABLE_NAME +
    " (" +
    TABLE_ROW_ID + " integer primary key autoincrement not null," +
    TABLE_ROW_ONE + " text," +
    TABLE_ROW_TWO + " text" +
    ");";

    db.execSQL(newTableQueryString);        

}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS " + tblInW);
    db.execSQL("DROP TABLE IF EXISTS " + tblAllowances);
    db.execSQL("DROP TABLE IF EXISTS " + tblEstimator);
    db.execSQL("DROP TABLE IF EXISTS " + tblInventory);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    onCreate(db);
}

// Adding a row to the database table
public void addRow(String rowStringOne, String rowStringTwo){

    SQLiteDatabase db = this.getWritableDatabase();

    //this is a key value pair holder used by android's SQLite functions
    ContentValues values = new ContentValues();
    values.put(TABLE_ROW_ONE, rowStringOne);
    values.put(TABLE_ROW_TWO, rowStringTwo);

    //ask the database object to insert the new data
    try {
        db.insert(TABLE_NAME,  null, values);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }
}


//DELETING A ROW FROM THE DATABASE TABLE
//
// This is an example of how to delete a row from a database table
// using this class. In most cases, this method probably does not need to be rewritten.
//
// @param rowID the SQLite database identifier for the row to delete.
//
public void deleteRow(long rowID){

    // ask the database object to delete the row of given rowID
    try {
        db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }

}

//UPDATING A ROW IN THE DATABASE TABLE
//
// This is an example of how to update a row in the database table
// using this class. You should edit this method to suit your needs.
//
// @param rowID the SQLite database identifier for the row to update.
// @param rowStringOne the new value for the row's first column
// @param rowStringTwo the new value for the row's second column

public void updateRow(long rowID, String rowStringOne, String rowStringTwo){

    //this is a key value pair holder used by android's SQLite functions
    ContentValues values = new ContentValues();
    values.put(TABLE_ROW_ONE,  rowStringOne);
    values.put(TABLE_ROW_TWO,  rowStringTwo);

    //ask the database object to update the database row of given rowID
    try {
        db.update(TABLE_NAME,  values, TABLE_ROW_ID + "=" + rowID, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.e("DB Error", e.toString());
        e.printStackTrace();
    }
}

//RETRIEVING A ROW IN THE DATABASE TABLE
//'
// This is an example of how to retrieve a row from a database table using this class. You should edit this method to suit your needs.
//
// @param rowID the id of the row to retrieve
// @return an array containing the data from the row

public ArrayList<Object> getRowAsArray(long rowID){

    //create an array list to store data from the database row.
    //I would recommend creating a JavaBean compliant object 
    //to store this data instead. That way you can ensure data types are correct.
    ArrayList<Object> rowArray = new ArrayList<Object>();
    Cursor cursor;

    try {
        // this is a database call that creates a "cursor" object.
        // the cursor object stores the information collected from the 
        // database and is used to iterate through the data.
        cursor = db.query(
                TABLE_NAME,
                new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
                TABLE_ROW_ID + "=" + rowID,
                null, null, null, null, null);

        //move the pointer to position zero in the cursor.
        cursor.moveToFirst();

        // if there is data available after the cursor's pointer, add
        // it to the ArrayList that will be returned by the method.

        if (!cursor.isAfterLast()){
            do{

                rowArray.add(cursor.getLong(0));
                rowArray.add(cursor.getString(1));
                rowArray.add(cursor.getString(2));

              } while (cursor.moveToNext());

            }

        //let java know that you are through with the cursor.
        cursor.close();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }

    //return the ArrayList containing the given row from the database.
    return rowArray;


    }

//RETRIEVING ALL ROWS FROM THE DATABASE TABLE
//
//This is an example of how to retrieve all data from a database table using this class.
//You should edit this method to suit your needs.
//
// the key is automatically assigned by the database

public ArrayList<ArrayList<Object>> getAllRowsAsArrays(){

    //create an ArrayList that will hold all of the data collected from the database
    ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();

    //this is a database call that creates a "cursor" object.
    //the cursor object stores the information collected from the database and is used to iterate through the data.
    Cursor cursor;

    try{
        //ask the database object to create the cursor.
        cursor = db.query(
                TABLE_NAME,
                new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
                null, null, null, null, null
                );

        //move the cursor's pointer to position zero.
        cursor.moveToFirst();

        //if there is data after the current cursor position add it to the ArrayList.
        if (!cursor.isAfterLast()){

            do
            {
                ArrayList<Object> dataList = new ArrayList<Object>();

                dataList.add(cursor.getLong(0));
                dataList.add(cursor.getString(1));
                dataList.add(cursor.getString(2));

                dataArrays.add(dataList);
            } 

            //move the cursor's pointer up one position.
            while (cursor.moveToNext());

        }
    }
    catch (SQLException e){

        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }

    //return the ArrayList that holds the data collected from the database.
    return dataArrays;
}

}

因此,现在我再次查看它时出现了两个错误。当我制作构造函数时

public MBDatabaseManager(Context context) {
    // TODO Auto-generated constructor stub
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

Eclipse 吓坏了,说“构造函数对象未定义”,当我使用 eclipse 修复它时,它删除了所有上下文内容并变成了 super();。我还没有完全理解所有内容,但我很确定这不会让我很快。

另外,当我尝试

SQLiteDatabase db = this.getWritableDatabase();

它也给了我一个错误,说“方法 getWritableDatabase() 未定义 MBDatabaseManager 类型”

我不知道我错过了什么伙计们。我敢肯定,这很明显。请协助。我需要第二或第三双眼睛。

非常感谢。

4

2 回答 2

0

例如,您忘记扩展基类public class MBDatabaseManager extends SQLiteOpenHelper

您尝试调用的超级构造函数 ispublic SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)并且您的调用是正确的,并且在继承SQLiteOpenHelper.

于 2012-08-25T20:58:49.110 回答
0

没有 super ( Object) ctor 接受您传递的参数,也没有调用方法getWritableDatabase

你的意思是继承 SQLiteOpenHelper吗?

于 2012-08-25T21:01:14.127 回答