Cursor.getCount() is negative (= -1) - android

I tried to load a list of values from a table, but the cursor returns a length of -1?
Is there a possibility to view a sqlite database on a android emulator?
The Code which is buggy:
final Cursor c = db.query(
ACCESS_TOKEN_TABLE,
new String[] { ACCESS_TOKEN_COL_ID, ACCESS_TOKEN_COL_VALUE },
ACCESS_TOKEN_COL_SERVER_ID + "=" + serverId,
null,
null,
null,
null);
public static final String COL_ID = "_id";
public static final String ACCESS_TOKEN_TABLE = "accesstoken";
public static final String ACCESS_TOKEN_COL_ID = COL_ID;
public static final String ACCESS_TOKEN_COL_SERVER_ID = "server_id";
public static final String ACCESS_TOKEN_COL_VALUE = "value";
And there is one entry in the database. The value of ServerID is 1 and there exists one entry, where the ServerID is 1.
Sincerely
xZise
PS: Two questions only to open the database.

you have an sqlite3 command if you "adb -e shell" with a CLI interface to the db.
better yet - i know of an eclipse plugin that can view sqlite database content using the ddms. but my personal favorite is to pull the db file out of the emulator, and use sqlite database browser to view the contents.

getCount() = -1 -> nothing to count... (are you sure your query is OK?)
Don't know about viewing sqlite db with Android emulator but you can use apps like Root Explorer to view Databases.

If the cursor is -1 the SQL statement is not returning any results. Maybe if you were to add the code you are using for your SQL select statement.
As for the second, viewing the DB - yes it is possible:
In Eclipse, DDMS view, click on the name of the emulator in the Devices tab (If the Devices tab isn't showing: Window->Show View->Devices)
Next click on the File Explorer tab (If the tab isn't showing: Window->Show View->File Explorer)
Now browse through the file tree. You need to go to:
data/data/com.package.name/databases
Now click on the name of the database you want to inspect. You will need to copy it to your computer. (To do this, click the picture of a floppy disc with an arrow on it. Save it somewhere you can find.)
You will need an SQLite browser, like the SQLite Manager add-on for Firefox
In Firefox, open the SQLite Manager (Tools->SQLite Manager)
In SQLite Manager, click Database, Connect Database (You may have to change the file type from SQLite DB Files (.sqlite;) to All Files as the Android DB doesn't have to have the .sqlite extension on the file)
Another option is to use the Questiod SQLite Browser plugin for eclipse - I have just added this - makes the above process twice as easy!

Ahr.... I was two lines to high:
So the problem isn't that the cursor returns a negative length, the problem is that it doesn't can give me the indexes of the columns.
I'm very sorry. Because of an totally other question, I posted a new question:
Cursor doesn't find columns?
Sincerely
xZise

Related

Insert rows to a database table : check if it worked?

I have in my database two tables : one is full of content and the other just is empty (I have only built the name of the fields and that's it). The whole database is in the assets folder of my application.
I have a method supposed to add a new element to this empty table every time I click on a button.
OnClickListener poi_favoritesbutton_listener = new OnClickListener(){
#Override
public void onClick(View v) {
DatabaseAdapter.insertInTable(ID_NAME, ID_CAT1, ID_CAT2, ID_CAT3, ID_CUISINE);
}
};
Here is the method :
public static long insertInTable(String ID_NAME, String ID_CAT1,
String ID_CAT2, String ID_CAT3, String ID_CUISINE) {
ContentValues data = new ContentValues();
data.put(FAV_NAME, ID_NAME);
data.put(FAV_CAT1, ID_CAT1);
data.put(FAV_CAT2, ID_CAT2);
data.put(FAV_CAT3, ID_CAT3);
data.put(FAV_CUISINE, ID_CUISINE);
if (myDatabase == null) {
}
return myDatabase.insert("DATABASE_FAVTABLE", null, data);
}
I think it should be correct as I have followed what was discussed on SOF related topics but I'd like not just to "think" and be sure instead! I tried using debug mode / DDMC but no way to actually open my database in real time and check for evolution of its content...
Any suggestion ? Thanks !
ps: i'm using a real device to run my test, emulator is just killing my time.
According to insert() docs:
Returns
the row ID of the newly inserted row, or -1 if an error occurred
so basically all you need is to check if you did not get said -1 in return.
no way to actually open my database in real time and check for evolution of its content
You can pull the database table to the device and see the contents of the table under DDMS tab-> File Explorer

How to store bulk questions in android sqlite db?

I am working on quiz application. In my project I need to store huge number of questions to display on the screen. How can I do that? I have downloaded the sqlite browser and when I tried to import .sql file it is displaying error. Also I have kept the .sql file in assets folder in eclipse.
How to store those questions into my sqlite db?
The thing is that even if you port the .sql file to the assets folder in eclipse its not going to work like that when you are going to use it in a real android mobile rather that an emulator by using the final .apk file.
One method what i did was to enter all the entries using a method. In order not to do this at each load, i check if the number of entries is the same else i drop the table and then enter it new once again. Thats the option that i know of. Maybe there are better options. But this works for sure.
public long createValue(int semester, String subname, int credits)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_SEMESTER, semester);
initialValues.put(KEY_SUBNAME, subname);
initialValues.put(KEY_CREDITS, credits);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
Create a method like the above to enter the values and then call this method with the values to enter. So you can just have n number of calls to this method with the values to enter.
mDb is a SQliteDatabase object
Maybe this will help you out.

SQLiteException: no such table

I am using my own SQLite3 database as opposed to creating a new one each time my app runs, as I have a few tables with static data that I am trying to display. I created my database and placed it in my assets folder. I then created my database helper and when I start my app I can open my database without problem but when I try to open my first table using the following code
private Cursor getData()
{
try
{
myDbHelper = new DatabaseHelper(this);
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query("exhibitor", FROM, null, null, null,null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
catch(SQLiteException e)
{
String err = e.toString();
return null;
}
}
It throws an error saying android.database.sqlite.SQLiteException: no such table: exhibitor: , while compiling: SELECT _id, EXHIBITOR FROM exhibitor ORDER BY EXHIBITOR but when I check the database exhibitor is there.
What am I missing?
Settings -> Applications -> Manage Applications -> (Click on your application) -> Clear data
Whenever you create new table in an existing database the table doesnt create because the OnCreate function of database handler will not be called everytime but only if required(like database not initiated). If that is not the case your newly created table actually hasnt created. Clear the data to force the db to instantiate itself.
Have you moved the database from the assets folder to /data/data/YOUR_PACKAGE/databases/ on the emulator?
This is a good detailed post about moving the database to /data/data/YOUR_PACKAGE/databases/ if it does not exist.
Here is another short and simple solution to it.
Clear Data and uninstall application from your device and re-install application in device...
Settings -> Applications -> Manage Applications -> Your Application Name -> Clear data
Using SQLiteOpenHelper.onCreate() does not create a new database every time your app starts - rather it creates a database if it does not already exist.
It sounds like you might have an empty database created by or for your helper (if there was no database at all, I might expect a different exception), and your separate database that you created outside of Android. Looks like you and your app are not looking in the same place for your data.
Just clearing the data did not work for me.
What worked was:
Uninstall app
Restart device or emulator
Disable Instant run (Not just the main group but all individual instant run settings)
Build -> Clean Project
Build -> Rebuild Project
hapend to me once
change your DATABASE_VERSION
if your DATABASE_VERSION =1 it will see just three table
if your DATABASE_VERSION = 2 it will see just more table but i really didn't know how many
good luck
I just had a simple mistake.
Reason:
Solution:
Just happened to me. I don't exactly know why but changing the DB_VERSION attribute to a bigger number made it work. The thing is: each time i'm changing the fields of the DB (attributes of the SQLiteDB class), i need to change that number.
Here is my answer according to the description of #ReivieraKid.
No, Uninstall, No Restart, Just checking the app memory if it is your real database, if return false, then copy the database to the memory again. Then You will All set. But to apply this method, you have to know the minimum size of your database.
https://stackoverflow.com/a/73332470/7608371

How to delete SQLite database from Android programmatically

I would like to delete the database file from the Android file system programatically? Can I have a shell script launch adb which in turns runs a shell script in the Android space to do the database deletion? Can I get this done from within a JUnit test case (with a system() call)?
How do I delete an entire database in Android? I need to make the whole thing go away so I can test database creation. I can drop tables, but that's not enough. This is in the emulator, not on a phone.
Once you have your Context and know the name of the database, use:
context.deleteDatabase(DATABASE_NAME);
When this line gets run, the database should be deleted.
The SQLiteDatabase.deleteDatabase(File file) static method was added in API 16. If you want to write apps that support older devices, how do you do this?
I tried: file.delete();
but it messes up SQLiteOpenHelper.
Thanks.
NEVER MIND! I later realized you are using Context.deleteDatabase(). The Context one works great and deletes the journal too. Works for me.
Also, I found I needed to call SQLiteOpenHelp.close() before doing the delete, so that I could then use LoaderManager to recreate it.
It's easy just type from your shell:
adb shell
cd /data/data
cd <your.application.java.package>
cd databases
su rm <your db name>.db
Try:
this.deleteDatabase(path);
or
context.deleteDatabase(path);
context.deleteDatabase("database_name.db");
This might help someone. You have to mention the extension otherwise, it will not work.
Also from Eclipse you can use DDMS which makes it really easy.
Just make sure your emulator is running, and then switch to DDMS perspective in Eclipse. You'll have full access to the File Explorer which will allow you to go in and easily delete the entire database.
context.deleteDatabase(DATABASE_NAME); will delete the database only if all the connections are closed. If you are maintaining singleton instance for handling your database helper - it is easy to close the opened Connection.
Incase the databasehelper is used in multiple place by instantiating directly, the deleteDatabase + killProcess will do the job even if some connections are open. This can be used if the application scenario doesn't have any issues in restarting the app.
Delete old Db when uninstall the app.
Setting android:allowBackup="false" in the application tag in AndroidManifest.xml fixed the problem. It seems that for some weird reason the Android OS was restoring from a backup every time I deployed the app.
you can create a file object of current database path and then delete it as we delete file from folder
File data = Environment.getDataDirectory();
String currentDBPath = "/data/com.example.demo/databases/" + DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
boolean deleted = SQLiteDatabase.deleteDatabase(currentDB);
I used Android database delete method and database removed successfully
public bool DeleteDatabase()
{
var dbName = "TenderDb.db";
var documentDirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentDirectoryPath, dbName);
return Android.Database.Sqlite.SQLiteDatabase.DeleteDatabase(new Java.IO.File(path));
}
I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.
//database initialization. Uncomment to clear the database
//deleteDatabase("questions.db");
Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.
If you are going to delete Table or Database , this way is worked:
1- Delete Table - It means keep Database but clean data from a table
* Just in DataHelper class add
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TABLE_NAME);
2- Delete Database - It means clean all records but keep file name
In the Activity
myDb = new DbHelper(this);
myDb.close();
myDb.delAll(getApplicationContext());
recreate();
In DataHelper class add
public void delAll(Context context) {
context.deleteDatabase(DB_NAME);
}
From Application Manager, you can delete whole application with data. Or just data by it self. This includes database.
Navigate to Settings. You can get to the settings menu either in
your apps menu or, on most phones, by pulling down the notification
drawer and tapping a button there.
Select the Apps submenu. On some phones this menu will have a
slightly different name such as Application Manager.
Swipe right to
the All apps list. Ignore the lists of Running and Downloaded apps.
You want the All apps list.
Select the app you wish to disable. A properties screen appears with
a button for Force Stop on the upper left and another for either
Disable or Uninstall updates on the upper right side.
Delete data.

How does android access a sqlite database included in the assets folder

I already have a SQLite database. I put it in the assets folder of my project. I read the Android documentation. It said that for all the databases in Android, the path is data/data/pack_name/database_name.
This confused me. I just placed it in the assets folder, so the path is data/data/assets/database_name?
The package name is not the project name, the package name is the namespace. From Anthony's link.
Remember to change the "YOUR_PACKAGE"
to your application package namespace
(i.e: com.examplename.myapp) in the
DB_PATH string.
For example, from the Hello World tutorial, the project name is HelloAndroid but the package name is com.example.helloandroid
If this application had a database, it would be stored at data/data/com.example.helloandroid/database
To see how it is for the other applications you can start your emulator. On the menu bar you have your avd's name (I think it stands for Android Virtual Device). On mine it s "avdessay:5554"
(On Linux) From command line, type:
adb -s emulator-5554 shell
You have to replace 5554 by whatever port you are using.
if you have the command prompt '#' you can type:
cd data/data
There, you will see that eveything is in a form of a package name.
More info here
When you create a database by utilizing the SQLiteDatabase or SQLiteOpenHelper classes, it creates the database in your data/data/package_name/database.
You can access that resource by using
InputStream myInput = myContext.getAssets().open(your_database_here);
Any other information, look at Using your own SQLite database in Android Applications
The package_name portion of the path, would be the name of your package. You can find the name of the package at the first line in your .java files.
As an example, my class starts with this at the top
package com.forloney.tracker;
So my database is in data/data/com.forloney.tracker/database folder.
Hope this makes sense.
#ScCrow I too followed this example and had the same problems you did until I realized I was not using the DataBaseHelper correctly (or rather it had a quirk I overlooked).
When you use your DatabaseHelper class in your activity, you have to make sure you call createDatabase first! If you look at the code for openDatabase it does NOT check to see if the database exists, so you either have to (attempt to) create the database in each activity you use it in, or modify the openDatabase method to check to make sure the db exists. The link posted does actually instruct you to use it this way but you (like me) may have glossed over that.
Bad:
DBAdapter db = new DBAdapter(this);
db.openDataBase(); //Bad! db not created yet!
Good:
DBAdapter db = new DBAdapter(this);
db.createDataBase(); //needs exception handling
db.openDataBase();
When I try to open my DB, I get "unable to open database file". I assume its not finding the DB and not some other programmer error. In the log I see the following which looks good to me.
sqllite3_open_v2("/data/data/com.isildo.HelloListView/databases/ListsDB" ...
This is the setup
private static String DB_PATH = "/data/data/com.isildo.HelloListView/databases/";
private static String DB_NAME = "ListsDB";
In my projects assets in the Package Explorer, I see the ListsDb database.
So I at least think I have it all correct. I am using the example at
[http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/]
In one of the posts here, someone offers a suggestion about setting some Assets parameters.
{no response to post there}
**To get an ASSETS folder into your APK:
In /nbproject/project.properties,
change assets.dir=
to
assets.dir=assets
assets.available=true
In /nbproject/build-impl.xml, there is line in the “if=assets.available” target that reads
that needs to be changed to**
Is this something we need to do, and if so, can we get a little better direction on the changes required. I could not find the places to make the suggested changes I looked at the project settings, and other things.
Yep, Im new to the environment, so I may just be not finding them. Im using Eclipse on windows.
In your DBAdapter.java, change the return type of openDatabase method to SQLiteDatabase.
When you access the database simply use SQLiteDatabase data = db.openDatabase(), where db is DBAdapter db = new DBAdapter(this).

Categories

Resources