简体   繁体   中英

Storing data in SQLite Database 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.

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 .

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.

My Code is as follows:

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM