在SQLite数据库Android中存储数据 [英] Storing data in SQLite Database android

查看:77
本文介绍了在SQLite数据库Android中存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to use SQLite database for storing data in Android application. The database is used to store data for a chat application and also to store various states of the messages like sent, delivered, read etc.

我在Android中面临的问题是查询正在正常运行,但是当我尝试使用下面的saveChatMessage函数插入值时,它总是返回rowID = 1.

The problem I am facing in Android is that the queries are running without error but when I try to insert the value using the saveChatMessage function below it always returns rowID = 1.

数据库没有抛出任何错误,但是当我尝试调用getAllUnsentMessages时,它将返回大小为 0 ArrayList.

There are no errors thrown from database, but when I try to call getAllUnsentMessages, it returns an ArrayList of size 0.

我已经尝试过将在联机数据库上触发的查询,但是看起来一切正常.我不知道为什么数据没有被存储.

I have tried the queries that will be fired on online database, but things seem to work fine. I have no Idea why the data is not getting stored.

我的代码如下:

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);
}

}

推荐答案

如果您正在使用事务,则需要在endTransaction()之前调用setTransactionSuccessful()进行实际提交.如果未成功设置,则更改将回滚.

If you're using transactions, you'll need to call setTransactionSuccessful() before endTransaction() to actually commit. Without setting as successful the changes are rolled back.

这篇关于在SQLite数据库Android中存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆