在SQLite数据库android中存储数据

时间:2015-10-16 15:47:25

标签: java android sqlite android-sqlite

我一直在尝试使用SQLite数据库在Android应用程序中存储数据。该数据库用于存储聊天应用程序的数据,还用于存储发送,传递,读取等消息的各种状态。

我在Android中遇到的问题是查询运行没有错误但是当我尝试使用下面的saveChatMessage函数插入值时,它总是返回rowID = 1

数据库没有引发任何错误,但当我尝试拨打getAllUnsentMessages时,会返回ArrayList大小 0

我已经尝试过将在在线数据库上触发的查询,但似乎工作正常。我不知道为什么没有存储数据。

我的代码如下:

public class DatabaseManager extends SQLiteOpenHelper {
private SQLiteDatabase db;
private static final String DATABASE_NAME = "CHAT";
private static final int DATABASE_VERSION = 1;
private static final String DB_ATTRIBUTE_MESSAGE = "body";
private static final String DB_ATTRIBUTE_CLIENT_TS = "clientTS";
private static final String DB_ATTRIBUTE_DELIVERED_STATUS = "delivered";
private static final String DB_ATTRIBUTE_DEVICE_ID = "deviceID";
private static final String DB_ATTRIBUTE_FROM_ID = "fromID";
private static final String DB_ATTRIBUTE_MESSAGE_ID = "messageID";
private static final String DB_ATTRIBUTE_READ_STATUS = "readStatus";
private static final String DB_ATTRIBUTE_SENT_STATUS = "return_m";
private static final String DB_ATTRIBUTE_SERVER_TS = "serverTS";
private static final String DB_ATTRIBUTE_TO_ID = "toID";
private static final String DB_ATTRIBUTE_TOKEN = "token";


private static final String SQL_CREATE_ENTERIES = "CREATE TABLE IF NOT EXISTS " + DATABASE_NAME + " " +
        "(" +
        DB_ATTRIBUTE_MESSAGE + " TEXT, " +             /*message*/
        DB_ATTRIBUTE_CLIENT_TS +" TEXT, " +            /*device Timestamp*/
        DB_ATTRIBUTE_DELIVERED_STATUS + " TEXT, " +    /*delivery status (-1 if Pending, 0 otherwise)*/
        DB_ATTRIBUTE_DEVICE_ID + " TEXT, " +           /*device ID*/
        DB_ATTRIBUTE_FROM_ID + " TEXT, " +             /*from ID (not necessarily Other Person)*/
        DB_ATTRIBUTE_MESSAGE_ID + " TEXT, " +          /*message ID i.e UUID (unique per message)*/
        DB_ATTRIBUTE_READ_STATUS + " TEXT, " +         /*read Status (-1 if Pending, 0 otherwise)*/
        DB_ATTRIBUTE_SENT_STATUS + " TEXT, " +         /*returned from Server*/
        DB_ATTRIBUTE_SERVER_TS + " TEXT, " +           /*server Timestamp*/
        DB_ATTRIBUTE_TO_ID + " TEXT, " +               /*to ID (not necessarily my ID)*/
        DB_ATTRIBUTE_TOKEN + " TEXT" +                 /*token received from Server*/
        ");";

private final static DatabaseManager instance;

private static final SQLiteException DOWNGRAD_EXCEPTION = new SQLiteException(
        "Database file was deleted");

static {
    instance = new DatabaseManager();
    instance.getDB();
}

public static DatabaseManager getInstance() {
    return instance;
}

private DatabaseManager() {
    super(MyApplication.getInstance(), DATABASE_NAME, null, DATABASE_VERSION);
}

/*@Override
public void onLoad() {
    try {
        getWritableDatabase(); // Force onCreate or onUpgrade
    } catch (SQLiteException e) {
        if (e == DOWNGRAD_EXCEPTION) {
            // Downgrade occured
        } else {
            throw e;
        }
    }
}*/

public SQLiteDatabase getDB() {
    //Perform this operation in a background thread, prefereably
    if (db == null)
        db = getInstance().getWritableDatabase();

    return db;
}

@Override
public void onCreate(SQLiteDatabase db) {
    if (db != null) {
        db.execSQL(SQL_CREATE_ENTERIES);
        Log.e("Create Query", SQL_CREATE_ENTERIES);
    }

    Log.e("Database Manager" , "DB Manager onCreate");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}



//save Chat Messages from Me as well as those received from Others, for first time.
public void saveChatMsg(String msg, String myTS, String deliveredStatus, String fromID/*myID*/, String messageID,
                        String readStatus, String return_m, String serverTS, String toID, String token) {
    if (db != null) {

        // Chat Message,
        // clientTS,
        // deliveredStatus,
        // deviceID,
        // fromID,
        // messageID,
        // read,
        // return_m,
        // serverTS,
        // toID,
        // token
        db.beginTransaction();

        ContentValues values = new ContentValues();
        values.put(DB_ATTRIBUTE_MESSAGE, msg);
        values.put(DB_ATTRIBUTE_CLIENT_TS, myTS);
        values.put(DB_ATTRIBUTE_DELIVERED_STATUS, deliveredStatus);
        values.put(DB_ATTRIBUTE_DEVICE_ID, AppConstants.DEVICE_ID);
        values.put(DB_ATTRIBUTE_FROM_ID, fromID);
        values.put(DB_ATTRIBUTE_MESSAGE_ID, messageID);
        values.put(DB_ATTRIBUTE_READ_STATUS, readStatus);
        values.put(DB_ATTRIBUTE_SENT_STATUS, return_m);
        values.put(DB_ATTRIBUTE_SERVER_TS, serverTS);
        values.put(DB_ATTRIBUTE_TO_ID, toID);
        values.put(DB_ATTRIBUTE_TOKEN, token);

        // Inserting Row
        long rowId = db.insert(DATABASE_NAME, null, values);
        Log.e("RowID", rowId + "");
        db.execSQL("INSERT INTO " + DATABASE_NAME + " VALUES (" +
                        "'" + msg + "', " +
                        "'" + myTS + "', " +
                        "'" + deliveredStatus + "', " +
                        "'" + AppConstants.DEVICE_ID + "', " +
                        "'" + fromID + "', " +
                        "'" + messageID + "'" + ", " +
                        "'" + readStatus + "', " +
                        "'" + return_m + "', " +
                        "'" + serverTS + "', " +
                        "'" + toID + "', " +
                        "'" + token + "'" +
                        ");"
        );
        Log.e("Insert Query", "INSERT INTO " + DATABASE_NAME + " VALUES (" +
                "'" + msg + "', " +
                "'" + myTS + "', " +
                "'" + deliveredStatus + "', " +
                "'" + AppConstants.DEVICE_ID + "', " +
                "'" + fromID + "', " +
                "'" + messageID + "'" + ", " +
                "'" + readStatus + "', " +
                "'" + return_m + "', " +
                "'" + serverTS + "', " +
                "'" + toID + "', " +
                "'" + token + "'" +
                ");");

        if (db.inTransaction())
            db.endTransaction();
    } else {
        Log.e("DatabaseManager", "DB is NULL");
    }
}

public void updateChatStatus(String messageID, int deliveredStatus) {
    //db.execSQL();
    if (db != null) {
        switch (deliveredStatus) {
            case 0: //Sent message to server
                db.beginTransaction();
                db.execSQL("UPDATE " + DATABASE_NAME + " SET " + DB_ATTRIBUTE_SENT_STATUS + "='1' WHERE " + DB_ATTRIBUTE_MESSAGE_ID + "='" + messageID + "'");
                if (db.inTransaction())
                    db.endTransaction();
                break;
            case 1: //Sent message to recepients device
                db.beginTransaction();
                db.execSQL("UPDATE " + DATABASE_NAME + " SET " + DB_ATTRIBUTE_SENT_STATUS + "='1', " + DB_ATTRIBUTE_DELIVERED_STATUS + "='1' " +
                        " WHERE " + DB_ATTRIBUTE_MESSAGE_ID + "='" + messageID + "'");
                if (db.inTransaction())
                    db.endTransaction();
                break;
            case 2: //Recepient has read the message
                db.beginTransaction();
                db.execSQL("UPDATE " + DATABASE_NAME + " SET " + DB_ATTRIBUTE_SENT_STATUS + "='1', " + DB_ATTRIBUTE_DELIVERED_STATUS + "='1', " +
                        DB_ATTRIBUTE_READ_STATUS + "='1'" + " WHERE " + DB_ATTRIBUTE_MESSAGE_ID + "='" + messageID + "'");
                if (db.inTransaction())
                    db.endTransaction();
                break;
            default:
                Log.e("DatabaseManager", "Weird DeliveryStatus");
        }
    }
}

public List<MessagesModel> getMessages(String fromID, String toID) {
    ArrayList<MessagesModel> messagesModel = new ArrayList<MessagesModel>();

    Cursor cursor = db.rawQuery("SELECT * FROM " + DATABASE_NAME + " WHERE " + DB_ATTRIBUTE_FROM_ID + "='" + fromID + "'" +
            " OR " + DB_ATTRIBUTE_TO_ID + "='" + fromID + "' AND " + DB_ATTRIBUTE_SENT_STATUS + "='-1' ORDER BY " + DB_ATTRIBUTE_CLIENT_TS, null);

    // Chat Message,
    // clientTS,
    // deliveredStatus,
    // deviceID,
    // fromID,
    // messageID,
    // read,
    // return_m,
    // serverTS,
    // toID,
    // token
    if (cursor == null) {
        return null;
    }
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        MessagesModel model = new MessagesModel();
        model.setMessage(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_MESSAGE)));
        model.setTs(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_CLIENT_TS)));
        model.setMessageUUID(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_MESSAGE_ID)));
        model.setBlueTick(true);
        model.setCode("200"); //Code 401 is used to detect that it is a history item.
        model.setUser_from(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_FROM_ID)));
        model.setUser_to(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_TO_ID)));
        model.setType(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_FROM_ID)).equals(fromID) ? 0: 1);

        cursor.moveToNext();
        messagesModel.add(model);
    }

    cursor.close();

    return (List<MessagesModel>) messagesModel.clone();
}

public List<MessagesModel> getAllUnsentMessages() {
    ArrayList<MessagesModel> allMessages = new ArrayList<MessagesModel>();

    Cursor cursor = db.rawQuery("SELECT * FROM " + DATABASE_NAME + " WHERE " + DB_ATTRIBUTE_SENT_STATUS + "='-1'", null);

    if (cursor == null)
        return null;

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        MessagesModel model = new MessagesModel();
        model.setMessage(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_MESSAGE)));
        model.setTs(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_CLIENT_TS)));
        model.setMessageUUID(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_MESSAGE_ID)));
        model.setBlueTick(true);
        model.setCode("200"); //Code 401 is used to detect that it is a history item. Set Code as per the status of the message
        model.setUser_from(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_FROM_ID)));
        model.setUser_to(cursor.getString(cursor.getColumnIndex(DB_ATTRIBUTE_TO_ID)));

        cursor.moveToNext();
        allMessages.add(model);
    }

    return allMessages;
}

public void execSQL(String query) {
    if (db != null)
        db.execSQL(query);
}

}

1 个答案:

答案 0 :(得分:1)

如果您正在使用交易,则需要在setTransactionSuccessful()之前调用endTransaction()才能实际提交。如果没有设置成功,则会回滚更改。