Hi I'm doing an Android application and I have a database. I'm able to do queries but the inserts don't seem to be working. I have a table named profile with the fields "id", "name" and "original".
This is the method:
public void addProfile(String name)
{
myDataBase.rawQuery("INSERT INTO profile(name, original) values('"+name+"', '0')", null);
}
And what I'm doing:
DataBaseHelper myDbHelper = new DataBaseHelper(activity);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
for(Profile p : profiles){
myDbHelper.addProfile(p.getName());
System.out.println("Commiting profile "+ p.getName());
In LogCat it correctly appears "Commiting profile test".
I'm opening the database with:
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
I've searched everywhere for the erro and I can't seem to find it. Is it because I have an "id" instead of "_id" on the table? Wouldn't that only affect the SELECTs? In my Selects I use select id as _id but in insert I don't know how to do it.
It is not allowed to use rawQuery to insert data. You should use execSQL
Related
Hi guys i'have problem with this little block of code
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
db = databaseHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insert("DELIVERY_SLIP", null, initialValues);
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
I have unique constraint on my table "DELIVERY_SLIP
So , when i'm trying to insert some row which already exist , it return some error like "Oh shit , you're inserting the same , i'm sorry men , i can't do it"
http://cdn.imghack.se/images/3b51afd07d1f1a8bd021c9e9dfc57e98.png
Here my log
It's this line
databaseHelper.close();
When database helper close , this return the log.
I just want to avoid to log it, I already tested with a tryCatch on sqliteConstraintException
But, nothing worked.
Thanks by advance
Instead of insert(), use insertWithOnConflict() with some conflict resolution algorithm appropriate for your use, such as SQLiteDatabase.CONFLICT_IGNORE.
I am very new and trying to learn how to use Select, Join, and Where with sqlite in android. Ideally this is what I want to return from the Database:
People who have the role id of 4 (Ranged):
select people.[name]
from people
join people_role
on people.[id] = people_role.[people_id]
where role_id = 4
What would the code be for returning People that have the role_id of 4?
1- Create your database using SQLiteBrowser.
2- Keep the Database in assets folder
3- Follow this solution.
4- Find getTestData() in TestAdapter calss & replace it with :
public Cursor getTestData()
{
try
{
String sql ="select people.[name]
from people
join people_role
on people.[id] = people_role.[people_id]
where role_id = 4 ";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
I have two instances of SQLiteDatabase database. And I need to copy data from one to another.
I need to execute this query:
INSERT INTO `toDB`.`tableName` SELECT * FROM `fromDB`.`tableName`
so, How can I do this my database instances? How to replace toDB and fromDB ?
Never tried that but it should work this way:
you have to ATTACH the other database at SQLite level so sqlite can access it directly.
For example you open the database that shall be the toDB and you issue the following command (via execSQL)
ATTACH DATABASE '/data/data/your.package/databases/dbname.db' AS fromDB
you should have access to the other database now and can do
INSERT INTO main.tableName SELECT * FROM fromDbB.tableName
the database you opened originally has the name "main" automatically.
You can and should get the path to your databases via Context#getDatabasePath since there is no guarantee that this path is the same on all devices.
Yes, you can do this as following:
DatabaseHelper dbHelper = DatabaseHelper.create(CMOSApplication.getInstance());
SQLiteDatabase db = null;
try {
db = dbHelper.getWritableDatabase();
db.execSQL("attach database ? as oldDB",
new String[] { CMOSApplication.getInstance().getDatabasePath("cmos_database").getPath() });
db.execSQL("insert into task select * from oldDB.task");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(db != null){
try {
db.execSQL("detach oldDB");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If we already have a database file in .sql format, how can we load this in our android app & use its data?
I also had this same problem and I did what jaydeep said. But I m not able to proceed..Please help me. I added 1 method in this to retrieve 1 record which is as follows:
public Cursor getTitle(String g,String k) throws SQLException {
Cursor c = myDataBase.rawQuery(
"select * from titles where food LIKE '%"+g+"%' and area LIKE '%"+k+"%' ",
null);
if (c != null) {
c.moveToFirst();
}
return c;
}
where titles is id name of table in database n food area n rest are fields. and in main file i did as follows:
{
Datahelper myDbHelper = new Datahelper(this);
final String tem="Chinese";
final String tem2="Bur Dubai";
final ListView list = (ListView)findViewById(R.id.list);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c = myDbHelper.getTitle(tem,tem2);
if (c.moveToFirst()) DisplayTitle(c);
else Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
}
public void DisplayTitle(Cursor c) {
final TextView ter=(TextView)findViewById(R.id.ter);
c.moveToPosition(0);
while (c.isAfterLast() == false) {
ter.append(c.getString(3)+"\n");
c.moveToNext();
}
c.close();
}
Please help me.
ListView code:
if (c.moveToFirst())
{
final String [] restarr=c.getColumnNames();
String[] fields = new String[] {db.KEY_REST};
list.setAdapter(new ArrayAdapter<String>(this, R.layout.main, restarr));
SimpleCursorAdapter rest = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fields, new int[] {android.R.id.text1});
list.setAdapter(rest);
}
You need SQLite version of the database. I bet your current database you want to ship to the application, has schema written with pure SQL syntax which quite different from SQLite.
If my assumption is true, then you need to extract the schema and convert it to SQLite. This takes some minor changes in the syntax but logic stays the same.
Here is nice tutorial how you can ship your external local database in your android application:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Mind the version and extension of the database file.
I was following this tutroial about using your own SQLite database. I did these steps as described in the tutorial:
Preparing my database
Copying the same EXACT DataBaseHelper class to my project package. You can see the class code there
Then, I just added one method to the DataBaseHelper class which is fetchData. It is simply fetching a whole table with the given name:
public Cursor fetchData(String table) {
String[] selectionArgs = new String[] {"*"};
return myDataBase.query(table, null, null, selectionArgs, null, null, null);
}
After that, in one of my activity classes I did this:
DataBaseHelper myDbHelper;
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
TextView txt = (TextView) findViewById(R.id.txt);
try {
//I will use my method to fetch a table named: myTable
Cursor c = myDbHelper.fetchData("myTable");
if((Object)c.getCount() != null)
txt.setText(c.getCount());
else
txt.setText("null");
} catch(Exception e) {
txt.setText("error");
}
However, I keep getting 'error' in the TextView. Is there a problem in my way?
My problem is nothing related to SQLite. It was silly mistake :-\
The error is in the second line here:
if((Object)c.getCount() != null)
txt.setText(c.getCount());
It must be like this:
txt.setText(""+c.getCount());
the setText() method accepts a ChaSequence and the getCount() method returns Integer which are not in compatible type. you can work around that tha easy way, by adding empty string :)
Thanks Guys.
public Cursor fetchData(String table) {
return myDataBase.query(table, null, null, null, null, null, null);
}
Seems you got wrong idea about the selectionArgs parameter. In documentation, it says:
You may include ?s in selection, which
will be replaced by the values from
selectionArgs, in order that they
appear in the selection. The values
will be bound as Strings.
Your trying to cast an int as an Object, then comparing the cast value to null. I would say that you code is likely to break right there.