Is it possible to take data from a edit text field and insert it into a SQLite db as a constant. I'm am trying to insert data into a SQLite primary key table and need for that data to be a constant for the db to accept it. I can't find any examples that would how me how to accomplish this.
i gotta say, i'm not quite sure what you mean by constant. just about every tutorial advises that you insert into the database with this method:
ContentValues values = new ContentValues();
values.put(DB_COLUMN, EtString);
long id = db.insert(DB_TABLE, null, values);
EtString is the string you get from the edittext field (with .getText, .toString or otherwise). This method would also provide a id for the string in the table that you could reference. But just know that if there's an _id field already in your database table, each row of information already gets an id without you doing anything.
Here's a good tutorial for this stuff:
http://www.vogella.com/articles/AndroidSQLite/article.html
Related
I am creating a table using the following query:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE person_info ( uniqueId INTEGER,first_name TEXT,last_name TEXT,
address TEXT)";
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
I am inserting the values as follows:
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put("first_name", "Anshul");
values.put("last_name", "Jain");
values.put("address", "Bangalore");
return db.insert(TABLE_NAME, null, values);
Note that I am not giving any value for uniqueId column. Thus, uniqueId column values are null.
When I query the database and try to the type of each column using cursor.getType(i), it returns Cursor.FIELD_TYPE_NULL for uniqueId column. According to the documentation, if all the column values are null, then it will return this value. But ideally it should return Cursor.FIELD_TYPE_INTEGER because that's what I declared while creating the database.
Is there any other way of retrieving the correct column type when all the values of a column are null.
Most SQL database engines (every SQL database engine other than
SQLite, as far as we know) uses static, rigid typing. With static
typing, the datatype of a value is determined by its container - the
particular column in which the value is stored.
SQLite uses a more general dynamic type system. In SQLite, the
datatype of a value is associated with the value itself, not with its
container.
SQLite Docs
This behavior of returning Cursor.FIELD_TYPE_NULL(which according to you is not ideal) is absolutely ideal because SQLite is designed in that way only.
Querying the database to get the type of a Container using cursor.getType(i) will only work if the Container is not NULL otherwise it returns Cursor.FIELD_TYPE_NULL (as in your case).
You can use PRAGMA table_info(table_name) for retrieving the datatype.
Check this SO answer -- Getting the type of a column in SQLite
I was curious if androids SQLiteDatabase insert method automatically handles type conversion.
Here is my example:
I have a csv file with a column name of age. Its type will be an INTEGER.
Lets say I have already created the database and table.
Now I am parsing the csv file with CSVReader, which parses each line and inserts each value into an index of a String[].
In order to insert each line of data into the database, I have to use a ContentValue object, which allows me to store values in it.
//Parse each line and store in line...
ContentValue values = new ContentValue();
values.put(KEY_AGE, line[1]); // Assume line[1] is the age
database.insert(table, null, values);
If I store the age value as a string (as seen above), and then insert it into the table, does Android handle the conversion to INTEGER before inserting it into the database?
I am asking this because I am trying to insert a bunch of tables into a database, and it looks much cleaner when I can just iterate through an array then explicitly state each put call, i.e:
Also if anyone has any design suggestions feel free to tell me.
CLEAN
int i = 0;
for(String s : TransitContract.Routes.COLUMN_ARRAY) {
values.put(s, line[i]);
i++;
}
UGLY
values.put(TransitContract.Routes.KEY_ROUTE_ID, line[0]);
values.put(TransitContract.Routes.KEY_AGENCY_ID, line[1]);
values.put(TransitContract.Routes.KEY_SHORT_NAME, line[2]);
values.put(TransitContract.Routes.KEY_LONG_NAME, line[3]);
values.put(TransitContract.Routes.KEY_DESCRIPTION, line[4]);
values.put(TransitContract.Routes.KEY_ROUTE_TYPE, Integer.parseInt(line[5]));
values.put(TransitContract.Routes.KEY_URL, line[6]);
values.put(TransitContract.Routes.KEY_COLOR, line[7]);
values.put(TransitContract.Routes.KEY_TEXT_COLOR, line[8]);
return mDatabase.insert(TransitContract.Routes.TABLE_NAME, null, values);
When you declare a column as INTEGER, SQLite will automatically convert strings to numbers, if possible.
See the documentation for Type Affinity.
If your ContentProvider doesn't restrict it (i.e. pass it directly to the SQLiteDatabase.insert() method), it should work. SQLite is not that picky about the types used in queries/inserts and the actual column type.
However, it would be best practice to parse and check the values before inserting. Otherwise you might actually insert a string which can't be parsed as integer and therefore retrieving the value might fail.
References:
Boolean datatype accepting string value and integer value
SQLite table with integer column stores string
I have a case that I would like to insert record in SQLite with database.insert(table, null, values).
TABLE t2 (_id, field1, field2)
..
val.setVal1(null);
val.setVal2(val2);
..
if(val.getVal1==null){
values.put(field1, _id);
}else{
values.put(field1, var.val1);
}
values.put(field2, var.val2);
database.insert("t2", null, values);
Is possible to do sth like this "values.put(field1, _id);"?
_id is generated at database.insert().
Note: I am looking for solution for one insert call. Insert and update row with (field1=_id) is easy.
i think i see now. you're asking if you can enter a value into a specific SQLite row _id field if it's available in your val object. Else, you want the database to automatically create a unique id for that column while inserting, like normally done. Is this correct?
To that end, i would seriously reconsider this purpose. You should never be specifying values for the _id column because it needs to be unique or else you'll get exceptions thrown. Moreover, it's only purpose is to be a unique identifier for the system, so you personally knowing this value should be of no use to you.
If you still need this functionality, i'd suggest making another field in your table (much like the _id column but not it), which you can fill with randomly generated numbers or val.getVal1 values.
I am trying to insert text messages from an inbox to a SQLite Database, but due to some special characters/symbols it doesn't insert properly.
I went through some question in Stackoverflow but nothing seems useful.
I got this code, but it is not working.
data.execSQL("INSERT INTO recor(text) VALUES('"+DatabaseUtils.sqlEscapeString(messag)+"')");
My database has only one field in it and am trying to insert details of messages along with it. I am putting the details (type, time, number, message) to a single string message and recor is my table name.
This is what I get as toast when I use a try catch loop.
Error is near:
"FROM":syntax error:INSERT INTO recor(text) VALUES("FROM 15555215556 Message:-MSG")
Uses the DatabaseAdapter's insert method instead. e.g.
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, value);
dbAdapter.insert(TABLE_NAME, null, values);
it looks like your column name is 'text'? this must be wrong, as text is a keyword in sqlite.
Your final SQL string seems to include two sets of quotes around the string you are inserting, so I assume the DatabaseUtils.sqlEscapeString method adds its own quotes around the string.
Therefore, your code should be:
data.execSQL("INSERT INTO recor(text) VALUES("+DatabaseUtils.sqlEscapeString(messag)+")");
I am new to android and i have just learned how to use the database and i have a couple of questions:
How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why.
When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'.
Thank you
ok, from first,
"How can we apply keys on the data in the database in android just like we give in Oracle database? Is it possible? If no please tell me why."
Ans - We can apply the all rule which one applies to a any other database, like oracle, mysql etc... So you can have both concept of primary key and foreign key in Android's SQLite database.
2.When i am deleting the first row in a database (Whose id is '1') the below rows id's are not coming in serial number i.e., id for the second row (Now first row) is '2' why not '1'?
Ans : as per the database rules whenever you delete any records from row then its key is remains same, its not changed and whatever data after that records are also has a same key or ID so whenever you want to access that data the ID or key remain same.
EDIT: and If you want to modify that key or ID you can use UPDATE query for that.
EDIT: update(String table, ContentValues values, String whereClause, String[] whereArgs)
Updating Values
To execute an update statement, we have two ways:
1. To execute db.execSQL
2. To execute db.update method:
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?",
new String []{String.valueOf(emp.getID())});
}
The update method has the following parameters:
1. String Table: The table to update a value in
2. ContentValues cv: The content values object that has the new values
3. String where clause: The WHERE clause to specify which record to update
4. String[] args: The arguments of the WHERE clause
Convenience method for updating rows in the database.
Hope you will understand it.
Thanks,