near "/" syntax error in Android - android

The below code in my project calls a function in my database class to insert two values into my sqlite database
saveButton = (Button) findViewById(R.id.Save);
saveButton.setOnClickListener(new View.OnClickListener( ) {
#Override
public void onClick(View v) {
addCig = (EditText) findViewById(R.id.cigName );
myDbHelper1.insertNewCig(addCig.toString(), fileName );
}
});
Here is the insert into function. I am getting an error that reads (near "/": syntax error). Can anybody help me look into it and see what is wrong with my code.
public void insertNewCig(String name, String file)
{
//DB_PATH = "/data/data/com.example.newdb/databases/"
//DB_NAME = "cigarettes"
String myPath = DB_PATH + DB_NAME;
String row1 = "INSERT INTO " + myPath + " (" + KEY_FIRST + ", " + KEY_LAST + ") VALUES(" + name + ", " + file + ")";
myDataBase.execSQL(row1);
}

myPath should be the name of a table in your database, not the name and path of the database file. You also need to add single quotes around the values you are inserting, otherwise SQLite won't recognize that they are literal string values and not something else (e.g. column names). This is one of many reasons not to try to build raw SQL statements by hand in code.
Since you have a SQLiteDatabase, you may as well use its insert() methods instead of execSQL(). In that case you would give it a ContentValues instead of constructing a raw statement, which obviates the need to wrap the string values with single quotes.
ContentValues values = new ContentValues();
values.put(KEY_FIRST, name);
values.put(KEY_LAST, file);
myDataBase.insert(TABLE_NAME, null, values);

Related

Android: how do I fix timestamp addition to my SQLite database? [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I am trying to add a TIMESTAMP Column to my SQLite database. The column is to be used to capture timestamp data using "System.currentTimeMillis();". App is crashing and the error is from the cursor code shown below in the line with ** **. The error reads "Unable to start activity ComponentInfo{...ListActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 6 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it."
Initially I set up the variable as a String in the model file. Then I tried a long and neither worked. What am I missing here?
UserData file:
...
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
DatabaseHelper.java file:
...
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + DBContract.DBEntry.TABLE_NAME +
"(" + DBContract.DBEntry.COLUMN_NAME_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DBContract.DBEntry.COLUMN_NAME_TODO +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_NOTE1 +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_NOTE2 +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_DUEDATE +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_DUETIME +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_TIMESTAMP +
" TEXT" + ")";
...
public void insertIntoDB(String todo, String note1, String note2, String duedate, String duetime, long timestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBContract.DBEntry.COLUMN_NAME_TODO, todo);
values.put(DBContract.DBEntry.COLUMN_NAME_NOTE1, note1);
values.put(DBContract.DBEntry.COLUMN_NAME_NOTE2, note2);
values.put(DBContract.DBEntry.COLUMN_NAME_DUEDATE, duedate);
values.put(DBContract.DBEntry.COLUMN_NAME_DUETIME, duetime);
values.put(DBContract.DBEntry.COLUMN_NAME_TIMESTAMP, timestamp);
db.insert(DBContract.DBEntry.TABLE_NAME, null, values);
db.close();
}
...
Cursor cursor = db.rawQuery(query,null);
try {
if (cursor.moveToFirst()) {
do {
UserData userData = new UserData();
userData.setTodo(cursor.getString(1));
userData.setNote1(cursor.getString(2));
userData.setNote2(cursor.getString(3));
userData.setDuedate(cursor.getString(4));
userData.setDuetime(cursor.getString(5));
**userData.setTimestamp(cursor.getLong(6));**
modelList.add(0, userData);
} while (cursor.moveToNext());
...
ListAdapter.java file:
...
public void onBindViewHolder(final ListViewHolder holder, final int position) {
...
holder.cardBlankText5.setText((int) dbList.get(position).getTimestamp());
Activity.java file:
...
public void onClickSave(View v) {
...
long timestamp=System.currentTimeMillis();
helper = new DatabaseHelper(Activity.this);
helper.insertIntoDB(todo,note1,note2,duedate,duetime,timestamp);
startActivity(new Intent(Activity.this,ListActivity.class));
}
Having DBContract.DBEntry.COLUMN_NAME_TIMESTAMP as a DATETIME type should work. I usually have utility method that takes the cursor and column name and returns a Date object:
public static Date getDateColumn(Cursor c, String column) {
Date d = null;
Long time = c.getLong(c.getColumnIndexOrThrow(column));
if (time != null && time != 0) {
d = new Date();
d.setTime(time);
}
return d;
}
The second thing to check is whether or not that field is being asked for in your query. Sharing the value of query could shed some light, but usually you get things like this when the column you are asking for isn't in the projection.
e.g. select columnA, columnB from mytable; and then you try to get something from columnC which isn't in the results.
Don't try to get Long from column declared as TEXT. Declare it as INTEGER.
Or use getString() and convert value to Long.

Replace function in SQLITE

I was trying to duplicate this SQLite statement from the line of code below:
Cursor cursor = db.rawQuery("update tbl_details SET ticket = replace(ticket, " + tempID + ", " + ticket + ")", null);
to this one:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ticket", "replace(ticket, " + tempID + ", " + ticket + ")");
db.update("tbl_details", cv, null, null);
return true;
What I am trying to do is to get a New ID and replace all instances of the old temporary ID in the database. But the code above is changing all the records in ticket column.
Please help. Thank you!
You can use ContentValues to bind literal values only, not expressions like replace(...).
To run the raw UPDATE SQL, just use execSQL() instead of rawQuery(). rawQuery() alone won't actually run the code until the returned Cursor is moved.

SQLite Database getting deleted in Android

Hello everyone,
I have built a sample app which takes input from user and save it in a table in a database.I have created my own database for my app and saved data in it. Every thing seems to be fine. The other day, I started Eclipse IDE and started running my application. I was not able to see any data in my application.
When I see in file explorer(DDMS), there was no database ( my database, table, data in it every thing lost). I heard that SQLite database is persistent. I used general syntax for creating database and table. Please any one suggest me why this has happened.
This is my MainActivity.java,
public class MainActivity extends Activity {
public final android.content.Context Context = MainActivity.this;
public String ReadingMode = "";
public String Value = "";
public String DialogStatus = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveWaterReadingToDB = (Button) findViewById(R.id.saveReading);
saveWaterReadingToDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String TABLE_NAME = "WaterElectricity";
String COLUMN_NAME_READING_ID = "_Id";
String COLUMN_NAME_READING_MODE = "ReadingMode";
String COLUMN_NAME_PASTDATETIME = "StartDateTime";
String COLUMN_NAME_READINGVALUE = "ReadingValue";
final SQLiteDatabase DB = Context.openOrCreateDatabase(
"WaterElectricityReadingDataBase.db",
MODE_WORLD_READABLE, null);
final String CREATE_TABLE = "create table if not exists "
+ TABLE_NAME + " (" + COLUMN_NAME_READING_ID
+ " integer primary key autoincrement,"
+ COLUMN_NAME_READING_MODE + " text not null,"
+ COLUMN_NAME_PASTDATETIME + " date not null, "
+ "EndDateTime date not null, "
+ COLUMN_NAME_READINGVALUE + " integer not null" + ");";
DB.execSQL(CREATE_TABLE);
}
});
}
Thanks.
All databases may be deleted every time you restore/re-run your emulator.
Closing eclipse has nothing to do with your database deleting, as it's all saved in your emulators directory.
Your emulators database is actually stored on a piece of virtual memory. To see this (In windows) go to username/.android/avd and you will see all of your AVD's set up as directories (containing all files pertaining to that emulator)
Make sure this is unchecked:
File Path with Files:
SD Card img file (containing the actual db)?:
This is just me taking an educated guess on which file is the actual sdcard file. Someone feel free to correct me.

Android SQLiteDatabase.delete method wouldn't delete using where args

Watch how i call the db.delete method; if I do the following a record is successfully deleted:
public void deteleProfile(Long id) throws SQLException {
SQLiteDatabase db = helper.getWritableDatabase();
Integer i = db.delete(ProlificDatabase.TABLE, "_id=?", new String[] {id.toString()});
Log.d(TAG, i + " records deleted where id is " + id);
however if I do this:
public void deteleProfile(Long id) throws SQLException {
SQLiteDatabase db = helper.getWritableDatabase();
Integer i = db.delete(ProlificDatabase.TABLE, "?=?", new String[] {BaseColumns._ID,id.toString()});
Log.d(TAG, i + " records deleted where id is " + id);
no records are deleted. also no exceptions or warnings are raised to say something has gone wrong.
in case you didn't catch it, the difference between the two calls were:
..."_id=?", new String[] {id.toString()});
vs
..."?=?", new String[] {BaseColumns._ID,id.toString()});
documentation for BaseColumns._ID is:
public static final String _ID with a Constant Value: "_id"
The latter way seems to make for neater code, but why doesn't it work?
EDIT:
I suspect the whereargs parameter only applies to the right side of an expression.
Can someone confirm this?
the Strings you provide in whereArgs are escaped and enclosed in '
"?=?", new String[] {BaseColumns._ID,id.toString()});
translates to
'_id'='1234'
which is valid SQLite syntax but does string comparison instead of a table lookup. Since "_id" is not the same String as "1234" (or any other number) the expression will always evaluate to false and nothing will get deleted.
What you should use is the following syntax
Integer i = db.delete(ProlificDatabase.TABLE, BaseColumns._ID + "=?", new String[] {id.toString()});
public void deteleProfile(Long id) throws SQLException
{
SQLiteDatabase db = helper.getWritableDatabase();
Integer i = db.delete(ProlificDatabase.TABLE, "_id=" + id, null);
Log.d(TAG, i + " records deleted where id is " + id);
}
and this link is a good example of SQLite database of android.

No such table SQLite Android

I have built a database helper class with an open() method and extended sqlite helper with onCreate() overridden. (shown below). Despite all of this, I am getting 'SQLiteException, no such table' error. I do not understand, why is the openHelper not helping?
public void open() {
try{
db = openHelper.getWritableDatabase();
} catch (SQLiteException e) {
db = openHelper.getReadableDatabase();
}
}
//other stuff
public static final String database_create = "create table " + database_table + " (" + primary_key + " integer primary key autoincrement, "
+ company_column + " text not null, " + product_column + " text not null);";
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(database_create);
}
the following code is meant to insert an entry temporarily, because the database cannot be empty for other reasons. It seems to execute perfectly, yet the last bit of code, which comes after is what throws the error
CompanyAndProductDatabaseAdapter cpdAdapter = new CompanyAndProductDatabaseAdapter(this);
cpdAdapter.open();
errorguard = cpdAdapter.insertPair("Loading", "...");
cpdAdapter.close();
//other stuff
cpdAdapter.open();
Cursor cursor = cpdAdapter.getAllPairsCursor(); //error here
cursor.requery();
startManagingCursor(cursor);
I don't know why you implemented a open-method, also the database_create is not what it should be.
I assume the first code is part of CompanyAndProductDatabaseAdapter.
Take a look here:
Android - Sqlite database method undefined fot type
That's almost all you need to create/get a DB with inherted SQLiteOpenHelper.
Your problem is this function:
db = openHelper.getWritableDatabase();
db = openHelper.getReadableDatabase();
First: check your path/name of the database is correct. It can create a default database, an empty database ( no tables, no nothing) if the database is not found.
Second: try to open your database this way:
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); // or OPEN_READONLY, depending on situation.

Categories

Resources