I tried to use SQLite on Android. I want to see my database file. So, I use Android File Explorer and browse this link:
Data\data\App_name But in Data\data. I cannot see my app name. (in below code will be: com/app/TimeTracker)
Here my code to test:
first is my main program:
package com.app;
public class TimeTrackerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimeTrackerDatabase database = new TimeTrackerDatabase(this);
}
}
and second is my database helper:
package com.app;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class TimeTrackerDatabase extends SQLiteOpenHelper {
public TimeTrackerDatabase(Context context){
super(context, "timetracker.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(
"CREATE TABLE timerecords"+"id INTEGER PRIMARY KEY, time TEXT, notes TEXT)"
);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
Is there any problem in above two file ? If has, please tell me what. And if not, please tell me how to fix this problem.
thanks :)
#Edit: I add my screenshot of my data folder. (No file in lib folder)
the database related issue will be solved by below updation in your code.
package com.app;
public class TimeTrackerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimeTrackerDatabase database = new TimeTrackerDatabase(this);
SQLiteDatabase db = database.getWritableDatabase(); //Add this line.
}
}
public class TimeTrackerDatabase extends SQLiteOpenHelper {
public TimeTrackerDatabase(Context context){
super(context, "timetracker.db", null, 2);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(
"CREATE TABLE timerecords" +
"(id INTEGER PRIMARY KEY, time TEXT, notes TEXT)"
);
}
Regarding your app not visible in File explorer, you need to search by package name as below
data/data/com.app and here you can see database folder where you can see all your databases created by application
actually your database is not being created due to faulty query.
write your query as:
"CREATE TABLE IF NOT EXISTS timerecords
(id INTEGER PRIMARY KEY, time TEXT, notes TEXT);"
once, the db file is created, then you can browse till the desired location
It's not Data\data\App_name , it'll be Data\data\package_name. So in your case it'll be Data\data\com.app\
Try looking your db file there.
Related
i have a listview in my project that links to database and shows its context from database but my problem is whenever my application runs it records goes twice (ex.2records first run, 4records with same context,...) and i do not know that wat is problem
this is my database class:
new File(DIR_DATABASE).mkdirs();
dataBase = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/information.sqlite", null);
dataBase.execSQL("CREATE TABLE IF NOT EXISTS information (" +
"information_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE ," +
"information_title TEXT)");
dataBase.execSQL("INSERT INTO information (information_title) VALUES ('قسمت اول')");
dataBase.execSQL("INSERT INTO information (information_title) VALUES ('قسمت دوم')");
and its my main class that shows listview:
ListView lstC findViewById(R.id.lstContent);
adapter = new AdapterNote(title);
lstContent.setAdapter(adapter);
readFromDataBase();
adapter.notifyDataSetChanged();
}
private void readFromDataBase() {
Cursor cursor = G.dataBase.rawQuery("SELECT * FROM information", null);
while (cursor.moveToNext()) {
StructNote detail = new StructNote();
detail.title = cursor.getString(cursor.getColumnIndex("information_title"));
title.add(detail);
}
cursor.close();
adapter.notifyDataSetChanged();
}
You need to understand SQLiteOpenHelper for this. This is workflow issue, so it would be better you should go through some tutorial. This is a nice tutorial where you can learn the concept.
In very short i am listing few points that may be useful for you:
In your application you create a subclass of the SQLiteOpenHelper class.SQLiteOpenHelper is a helper class to manage database creation and version management. In subclass override, onCreate() and onUpgrade().
public class MySQLiteHelper extends SQLiteOpenHelper {
public void onCreate(SQLiteDatabase database) {
// create database command.
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// upgrade database command here.
}
}
Create a DAO class that will manage the interaction with the database. Your CRUD methods will go here. See DAO pattern for details. This class will centralize the access to database, hence your activity, fragment will interact with this class to perform operation. Direct access to database won't be allowed.
public class ModelDataSource {
// needed to perform operation on database
private SQLiteDatabase database;
//needed to retrieve database object
private MySQLiteHelper dbHelper;
public boolean insertModel(Model model) {
// perform insert operation on database
}
}
In your activity, you can interact with DAO to perform some action.
public class YourActivity extends Activity {
private ModelDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new ModelDataSource(this);
datasource.open();
boolean insertion_status = datasource.insert(modelobject);
}
}
This question already has answers here:
Where does Android emulator store SQLite database?
(10 answers)
Closed 7 months ago.
Hello i created a database class on andorid that below.
public class Veritabani extends SQLiteOpenHelper {
private static final String Veritabani_Adi = "Veritabanim";
private static final int Veritabani_Version = 1;
public Veritabani(Context context) {
super(context, Veritabani_Adi, null, Veritabani_Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE ARKTABLE (id INTEGER PRIMARY KEY AUTOINCREMENT , ad TEXT, soyad TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST OperatorTablosu");
onCreate(db);
}
}
**then i declare may Veritabani class in my activity as below.**
public class DictionaryActivity extends Activity {
Spinner spnLanguage;
Veritabani objdb;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary);
spnLanguage=(Spinner)findViewById(R.id.spnLanguage);
objdb=new Veritabani(this);
spinnerfill();
}
i don't have an exception on logcate or console.
But when i look may data/data/myappp/ i dont see database directory.
i used android 2.2 version
check In the DDMS perspective if you are using Eclipse. there you can easily find whether your database is created or not.
you want to DDBMS
Go to mnt/sdcard/yourdatabase name.it's database store in sdcard
internal memory means data/yourpackagename/yourdatabasename
I'm having this error when I try to access one table:
02-19 16:46:01.677: E/AndroidRuntime(13159): android.database.sqlite.SQLiteException: no such table: notes: INSERT INTO notes (user,text) VALUES ('john','testingvalue')
But I created the table! I have two tables in the database ('users' and 'notes'), I'm accessing them the same way, but when I try to insert a value in the table 'notes', I have that error.
That's the code:
package com.loopr;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SQL extends SQLiteOpenHelper {
String createUserTable = "CREATE TABLE users (name TEXT)";
String createNotesTable = "CREATE TABLE notes (user TEXT, text TEXT)";
public SQL(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createNotesTable);
db.execSQL(createUserTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int before, int after) {
//Nothing at the moment
}
}
What can I do? Thanks.
Try changing int version and put this in your onUpgrade overridable method:
// Drop the old table.
db.execSQL("DROP TABLE IF EXISTS notes");
// Create a new one.
onCreate(db);
What can you do? Learn to debug on Android. Read the material at this link. Figure out how to use DDMS's File Explorer to pull databases from an emulator. Get a tool like SQLite Manager (firefox) to look at these databases - it's helped me enormously. Also, you can use SQLite Manager to perform raw sql statements on your DB, allowing you to craft sql and test at the same time.
My DBHelper class
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context)
{
super(context,"SIMPLE_DB",null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE SIMPLE_TABLE ( " +
"ID INTEGER PRIMARY KEY " +
"DESC TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Activity class
public class SimpleDatabase extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("INSERT INTO SIMPLE_TABLE VALUES (NULL, 'test');");
Cursor cursor = db.rawQuery("SELECT * FROM SIMPLE_TABLE", null);
TextView text = (TextView)findViewById(R.id.textbox);
text.setText(cursor.getString(0));
}
}
I figure it crashed (application has stopped unexpectedly!) at SQLiteDatabase db = ... because if I commented the code out from there to the end then it worked fine. But I have no idea whatsoever why it does that.
Any help would be appreciated.
Never mind, figured out what I did wrong now.
db.execSQL("CREATE TABLE SIMPLE_TABLE ( " + "ID INTEGER PRIMARY KEY<comma goes here> " + "DESC TEXT);");
Commas are serious businesses. Sorry for the stupid question.
first of all you should ensure that your SQL statement is correct. If sqlite3 is in your path you could execute the command:
$>: sqlite3 testdb.db
after that you are in an shell where you can test your SQL statements if there are syntactically correct. (Hint: refering the example above: it is not correct).
After that you should handle your cursor correctly as described by Aurora.
Maybe you should implement your onUpgrade() method, e.g:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS SIMPLE_TABLE");
onCreate(db);
}
First, to help in your debugging, make sure to use the debug monitor and Log. This will make your life a lot easier in the long run! If you are using Eclipse, select Window -> Open Perspective -> Other -> DDMS. The LogCat will show you what is happening as the program is run. Documentation describes it here. Run your program again and watch the LogCat. It should give you more information and tell you what line of code is crashing.
As far as your code goes, the first thing I notice is that after you get a cursor back, you need to call cursor.moveToFirst(); to select the (first) row. Then when you call cursor.getString(0);, it indicates the zeroeth column of the zeroeth row. If you do not call moveToFirst(); then you cursor.getString(0) is going to get the zeroeth column of the -1st row and be an index out of bounds error. By default, the cursor will start at row -1.
Depending on how you want to move through your cursor, and how many results/rows you get back, you may also need to call cursor.movetoPosition() or cursor.moveToNext(). Check out the documentation on cursors here.
I'm still very new to Object Oriented programming and am having problems with the class inheritance and the scope of variables from one instantiated class to another.
I'm trying to build an android application that can read multiple XML feeds and save them to the phone's SQLite database. Each feed has a different name ("news", "audio_mixes" etc.) and I want to use these names to save each feed's data into separate database tables - each one named after the feed title.
In diagrammatic terms this is what my classes look like:
(source: baroquedub.co.uk)
The Main activity displays two buttons each of which starts an activity - both of which are instances of the TitlesBrowser class. Extras are used to pass different values of the_url and the_feed_type variables.
#Override
public void onCreate(final Bundle icicle) {
super.onCreate(icicle);
this.setContentView(R.layout.main);
this.getNewsButton = (Button) findViewById(R.id.get_news_button);
this.getNewsButton.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
Intent doGetNews = new Intent(Main.this, TitlesBrowser.class);
doGetNews.putExtra("the_url", Main.this.getString(R.string.titles_url));
doGetNews.putExtra("the_feed_type", Main.this.getString(R.string.news_type_var));
startActivity(doGetNews);
}
});
this.getMixtapesButton = (Button) findViewById(R.id.get_mixtapes_button);
this.getMixtapesButton.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
Intent doGetMixtapes = new Intent(Main.this, TitlesBrowser.class);
doGetMixtapes.putExtra("the_url", Main.this.getString(R.string.titles_url));
doGetMixtapes.putExtra("the_feed_type", Main.this.getString(R.string.mixtapes_type_var));
startActivity(doGetMixtapes);
}
});
}
The TitlesBrowser class, in its onCreate method, gets the Extras and saves them to private local variables.
Intent i = getIntent();
private String theUrl = (String) i.getStringExtra("the_url");
private String theFeedType = (String) i.getStringExtra("the_feed_type");</pre>
This class does two things,
1/ it creates an instance of the DatabaseHelper class, and uses a public set method in that class to pass on the value of the locally help theFeedType variable. Having done that it queries the database for any existing data (the theFeedType is the name of each table)
db=new DatabaseHelper(this);
db.setTableName(theFeedType);
dbCursor=db.getReadableDatabase().rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id", null);
2/ then it loads new data from the feed URL by instantiating another class HTTPRequestHelper :
HTTPRequestHelper helper = new HTTPRequestHelper(responseHandler);
helper.performPost(theUrl, theFeedType);
The HTTP requests work fine, and depending on which of the two buttons is clicked, each of the two different activities display the appropriate XML (i.e. retrieve the correct data)
- therefore I know that theUrl and theFeedType variables are local to each instance of the TitlesBrowser class.
One calls:
http://baroquedub.co.uk/get-feed.php?feed=news
and the other one:
http://baroquedub.co.uk/get-feed.php?feed=audio_mixes
The problem is with the DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="baroquedub.db";
private String table_name;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+ table_name + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"id INTEGER, " +
"title TEXT, " +
"details TEXT, " +
"picture TEXT, " +
"viewed BOOLEAN DEFAULT '0' NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w("Baroquedub", "Upgrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS mixtapes");
onCreate(db);
}
public void setTableName(String theName){
this.table_name = theName;
}
}
I would expect it to create a new table each time it is instantiated (whether "news" or "audio_mixes" was passed from its parent TitlesBrowser class.
But it only works once - if I start the application and click on "news" a table called news is created and each time I return to that activity it successfully retrieves data from that same database.
But if I then start the other activity by clicking on the other button (i.e access the other feed) I get an SQL error telling me that a database of that name doesn't exist. In other words the onCreate db.execSQL("CREATE TABLE... method doesn't appear to get called again.
It's as if multiple copies of the DatabaseHelper class aren't being created, although there are two instances of TitlesBrowser.
--
Here's a demonstration of the problem:
http://screencast.com/t/NDFkZDFmMz
This has been really tricky to explain (especially for a newbie!!!) and I hope it makes some sense. I'd be very grateful for any help, advice or guidance.
When you instanciate a SQLiteOpenHelper class you actually access a singleton in the Activity's context. The helper decides when to call the OnCreate / onUpgrade methods - specifically, if the DB doesn't exist or is stale.
Either way, the onCreate method is not called each time you create a new instance of the class - that would really make no sense. You should put the two CREATE TABLE commands in the onCreate method.
(PS I assume the error you're getting is that a table is missing and not the entire database).
A big thank you to adamk for providing the guidance necessary to solve this, in the answer he provided.
He suggested that I add two CREATE TABLE commands in the DatabaseHelper's onCreate method (on for each of my feeds). However, I needed to abstract things a little more so that I could still use multiple instantiations of the TitlesBrowser activity and so that I wouldn't have to rewrite the helper class every time a new feed came on board.
For those interested, here's the solution I came up with.
First of all, I removed the CREATE TABLE commands in the DatabaseHelper's onCreate method. I also removed the private table_name variable (and its associated set method) and I replaced this with a public method called makeTable():
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="baroquedub.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w("Baroquedub", "Upgrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS mixtapes");
onCreate(db);
}
public void makeTable(String theTableName){
SQLiteDatabase thisDB = DatabaseHelper.this.getWritableDatabase();
thisDB.execSQL("CREATE TABLE IF NOT EXISTS "+ theTableName + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"id INTEGER, " +
"title TEXT, " +
"details TEXT, " +
"picture TEXT, " +
"viewed BOOLEAN DEFAULT '0' NOT NULL);");
}
}
In TitlesBrowser, rather than instantiating the DatabaseHelper, setting the table name and then reading in the data:
db=new DatabaseHelper(this);
db.setTableName(theFeedType);
dbCursor=db.getReadableDatabase().rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id", null);
Instead, I reworked all this so that it would more elegantly handle the creation and loading of the database data from each table:
The database Helper is created as before,
then the new databaseLoad() method tries to read from the required table
and if it can't, it calls the DatabaseHelper's public makeTable() method,
before finally trying to load the data again:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
theUrl = (String) i.getStringExtra("the_url");
theFeedType = (String) i.getStringExtra("the_feed_type");
// show saved in DB
db=new DatabaseHelper(this);
databaseLoad();
}
private void databaseLoad(){
try { // table exists
dbCursor=db.getReadableDatabase()
.rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id", null);
displayContent();
} catch (Exception e) { // table doesn't exist
db.makeTable(theFeedType);
databaseLoad(); // try again
}
}