sqlite android basics ...我错过了什么吗?

时间:2012-08-25 20:54:36

标签: android sqlite

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

在eclipse中,我试图为我的db管理类的上下文创建一个构造函数。这是代码的全部内容。它还没有完成,但我无法继续前进,直到错误消失为止,所以我们走了:

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吓坏了,说&#34;构造函数对象未定义&#34;当我使用eclipse来修复它时,它会删除所有上下文的东西并变成super();.我还没有完全了解所有相关内容,但我很确定这会让我无法快速完成任务。

当我尝试

SQLiteDatabase db = this.getWritableDatabase();

它也给了我一个错误,说&#34;方法getWritableDatabase()未定义类型MBDatabaseManager&#34;

我不知道自己错过了什么。我确定这是显而易见的事情。请协助。我需要第二或第三组眼睛。

非常感谢。

2 个答案:

答案 0 :(得分:0)

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

您尝试拨打的超级构造函数为public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version),您的通话正确无误,并且在继承SQLiteOpenHelper后仍然有效。

答案 1 :(得分:0)

没有超级(Object)ctor接受您传递的参数,也没有名为getWritableDatabase的方法。

你的意思是继承SQLiteOpenHelper吗?