sider
sider

Reputation: 687

Inserting Row into Sqlite DB(Android)

I have table "logs":

private static final String DATABASE_CREATE = 
            "create table if not exists logs (_id integer primary key autoincrement, "+ "date datetime, city text, " + "type text, log text, nick text);";

And method to insert a log:

public long insertLog(String city, int type, String log, String nick) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        ContentValues initialValues = new ContentValues();

        initialValues.put(KEY_DATE, dateFormat.format(date));
        initialValues.put(KEY_CITY, city);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_LOG, log);
        initialValues.put(KEY_NICK, nick);

        return db.insert(DATABASE_TABLE, null, initialValues);

    }

Every time i try to insert a log, i get no exceptions. Method returns every time "1". But when i looked at my table with sqliteviewer i see it empty. What could be reasons for this issue?

Upvotes: 1

Views: 14824

Answers (2)

Code Spy
Code Spy

Reputation: 9964

Complete example here

After defining basic configuration in DataBaseHelper use db object to insert row using below method

// method to insert a record in Table
public static String insertEntry(String user_name, String user_phone, String user_email)
{

    try {


        ContentValues newValues = new ContentValues();
        // Assign values for each column.
        newValues.put("user_name", user_name);
        newValues.put("user_phone", user_phone);
        newValues.put("user_email", user_email);

        // Insert the row into your table
        db = dbHelper.getWritableDatabase();
        long result=db.insert(TABLE_NAME, null, newValues);
        toast("User Info Saved! Total Row Count is "+getRowCount());
        db.close();

    }catch(Exception ex) {
    }
    return "ok";
}

Upvotes: 0

Dixit Patel
Dixit Patel

Reputation: 3192

create table Like this way

private static final String DATABASE_CREATE = 
            "create table if not exists logs (_id integer primary key autoincrement,date text, city text, type text, log text, nick text);";

& insert Like this

public long insertLog(String city, int type, String log, String nick) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        ContentValues initialValues = new ContentValues();

         // convert date to string
        String dateString = dateFormat.format(date);

        initialValues.put(KEY_DATE,dateString);
        initialValues.put(KEY_CITY, city);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_LOG, log);
        initialValues.put(KEY_NICK, nick);

        return db.insert(DATABASE_TABLE, null, initialValues);

    }

EDIT:

call this method

         db.open();
         db.insertLog(....);
         db.close();

Upvotes: 2

Related Questions