I have a conundrum, I do know how to call method from other activity.. crating object etc..
But I have dbHelper.java that deal with creating sql little tables etc and start like:
public class dbHelper extends SQLiteOpenHelper {
.
.
.
}
it works fine but i have method there that check when the DB version change and recreate DB tables etc..
like:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// pri zmene verzie DB dropne tabulku
Log.w("DATA", "Upgrading database from version " + oldVersion + " to " + newVersion);
db.execSQL("DROP TABLE IF EXISTS plan");
db.execSQL("DROP TABLE IF EXISTS contacts");
this.onCreate(db);
}
but I need to store also shared preference that I use to tell application that its new start... however its kind of strange i try :
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("FS", "1");
editor.commit();
But MODE_PRIVATE get underlined as error, even when I try call method from other activity creating object like this for example: dataManager db = new dataManager(this); where is method to store shared preference I get still underlined it as error...
Any idea what might be the issue ? I'm learning java but still no idea :-/
Vlad
MODE_PRIVATE is a constant which is declared in Context class. Just change MODE_PRIVATE to Context.MODE_PRIVATE
This works fine inside the Activity's method, cause' Activity is a subclass of Context
Related
So I'm trying to setup my SQLite database but I'm receiving errors which I'm finding difficult to correct.
See the error log here
Theres an image of the error being thrown and heres my code setup for my DatabaseHelper
I've also received some other errors in my log which I'm not sure what they are related to - any info be great
see the logcat output here
code of the error anyway
E/SQLiteLog: (1) table my_manager has no column named
location_description in "INSERT INTO my_manager(location_name,location_county,location_description)
VALUES (?,?,?)"
2020-11-28 19:56:32.986 5665-5665/? E/SQLiteDatabase: Error inserting location_name=Blarney Stone
location_county=Cork location_description=Stone in big wall
android.database.sqlite.SQLiteException: table my_manager has no column named location_description
(code 1 SQLITE_ERROR): , while compiling: INSERT INTO
my_manager(location_name,location_county,location_description) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1045)
a....
And here is my source code:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "my_manager.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_manager";
private static final String COLUMN_ID = "location_id";
private static final String COLUMN_LOCATION = "location_name";
private static final String COLUMN_COUNTY = "location_county";
private static final String COLUMN_DESCRIPTION = "location_description";
public MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_LOCATION + " TEXT, " +
COLUMN_COUNTY + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT );";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addLocation(String location, String county, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_LOCATION, location);
cv.put(COLUMN_COUNTY, county);
cv.put(COLUMN_DESCRIPTION, description);
long result = db.insert(TABLE_NAME, null, cv);
if (result == -1){
Toast.makeText(context, "Failed!" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully" , Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
}
When you first run your app the onCreate is executed and the schema at the time of first execution is set and the DATABASE_VERSION is associated with that schema.
Every time the super is invoked in the constructor (super(context, DATABASE_NAME, null, DATABASE_VERSION);) the SQLiteOpenHelper code looks at the database version number and if its greater than last defined than the onUpgrade is invoked.
During initial development it is common to alter the schema as you are adding to your App before first release. In this mode you have two choices:
Uninstall and reinstall App everytime the schema changes (loss of data). This causes the initial onCreate to be invoked with new schema again associated with version.
Bump the version (just needs to be higher than previous version) and the onUpgrade is invoked where you'd likely ALTER TABLE (to add/modify columns) or CREATE TABLE to add new tables.
The second option is normally used when an app is already released and the schema needs to be altered (without data loss). The end user would receive an App update and the onUpdate is invoked (because of the bumped version) and any alterations are applied to their existing database without loss of data (assuming you onUpgrade did not intentionally destroy data).
If data loss during initial development is not an issue than the uninstall/reinstall option seems easiest.
If you just alter schema without bumping version then essentially nothing is affected - and therefore when you perform a query on a new column, for example, it complains that it doesn't exist because it was never added.
I am writing an android app. For that I need to populate an SQLite database with data from a txt file. So in the onCreate function of the database, I am creating the database and then populating it with the data. This is what the onCreate's declaration looks like:
public void onCreate(SQLiteDatabase db) {
But when I use this line inside onCreate,:
db = this.getWritableDatabase();
I get this error at runtime in Logcat: "java.lang.IllegalStateException: getDatabase called recursively(812)".
So now I am unable to populate the database from inside onCreate, and am stuck. Any help will be appreciated.
onCreate() gets called the first time you call getReadableDatabase or getWriteableDatabase. What is certainly happening is that onCreate is getting called recursively because the db hasn't been created yet and your
db = this.getWritableDatabase();
call triggers the creation inside the creation.
If you need to prefill the db, just use the db argument of onCreate as a writeable database.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(YOUR_STATEMENT);
.
.
}
If you need to perform a lot of db operations, using
db.beginTransaction();
.
.
db.setTransactionSuccessful();
} catch (SQLException e) {
} finally {
db.endTransaction();
}
is generally faster.
This is my method in DBMethods class:
public void getResult(EditText keyWord2){
EditText keyWord = null;
String SQL ="localSearch.php?query="+keyWord.getText();
mDb.rawQuery(SQL, null);
}
And this is my method in which I am opening Database and all that in webServices class.
public void startSearch(View v){
keyWord = (EditText)findViewById(R.id.searchField);
String data = null;
DBMethods mDbHelper = new DBMethods(this);
mDbHelper.createDatabase();
mDbHelper.open();
mDbHelper.getResult(keyWord);
mDbHelper.close();
}
When I try to fetch data from the database by entering some keyword in the search bar, a force close error occurs.
EditText keyWord = null;
String SQL ="localSearch.php?query="+keyWord.getText();
Keyword is null, this will give null pointer exception.
I think your SQL variable must be
localSearch.php?query="+**keyWord2**.getText();
Make sure that you uninstall the already installed same application in your Emulator. Because once we Run our app that Sqlite DB installed in our Emulator and can't be edited. So uninstall your app and then Run again your app after changing .
I am trying to make my first Android app. I noticed that the SQLiteOpenHelper.onCreate() method is not called to create tables if the database not exists. However, the onCreate() method did not work even thought I tried to debug.
Please look at the code below and give me any suggestions. Any help will be appreciated.
public class NameToPinyinActivity extends Activity {
DatabaseOpenHelper helper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nametopinyin);
Button searchButton = (Button) findViewById(R.id.search);
searchButton.setOnClickListener(new ButtonClickListener());
helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
}
public class DatabaseOpenHelper extends SQLiteOpenHelper {
/** DB Name */
private static final String DB_NAME = "pinyin";
/** CREATE TABLE SQL */
private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(CREATE_TABLE_SQL);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}
I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable
SQLiteDatabase db;
In the SQLiteOpenHelper subclass and calling
db = getWritableDatabase();
in the constructor.
The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?
I hope this helps!
Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.
as simple as that database will be created in memory when you actually need that.:)
I had a similar problem where onCreate wasn't executed. Maybe this is of any use for someone even though it turned out being a different problem.
I was working on the database before and had already created one long time before. So now after making changes in onCreate() I was hoping to find the new tables created. But the SQLiteOpenHelper never called onCreate() again. Reason was, the database already existed. I was still working with the same device as before and consequently with the already existing (old) databse.
But there is hope. When the system sees a database with that name already exists, it also checks whether the version number is correct. In that case I simply forgot the database already existed. My solution was simply changing the version number. So onUpgrade() was called offering options for onCreate() changes.
So options were either uninstalling the complete app (and with it the database) or call onCreate again after upgrading the version number (and for example dropping) the old table and calling onCreate() again.
In any case, if onCreate() is not called, check twice if the database exists. Otherwise it's not called again.
I had a similar problem however it was not the OnCreate call that was the issue.
In the example code above, Kevin explained that the OnCreate is not called if the database already exists. However if, like me, you are using multiple tables from separate activities, then though you may have created the database already, the table associated with this activity may yet have not been created. Hence when you attempt to set the cursor data on a non-existent table, you will invoke an exception.
My solution was define a separate class called CreateTable which is called both from the OnCreate override and from the constructor after the
db = getWritableDatabase();
Call getWritableDatabase(); in the constructor
public DataBaseH(#Nullable Context context) {
super(context, dataBaseName, null, dataBaseVersion);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable="CREATE TABLE IF NOT EXISTS "+tableName+ " ( "+
id+ " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
name+ " TEXT,"+
familyName+ " TEXT,"+
age+ " INTEGER);";
db.execSQL(createTable);
Log.i(TAG,"db.exect");
}
I was having a similar problem with onCreate() not executing when the app was very first run, so my database never got created. This is NOT the same as when onCreate() is not executing because the database already existed, because the database did not yet exist. Specifically, my DataProvider onCreate() was not executing, so the OpenHelper never got called either.
I verified I had everything set up the way that everyone described in the previous answers, but nothing resolved my problem. Posting this answer in case anyone else forgets one small detail like I did.
What resolved the problem for me was adding a entry in AndroidManifest.xml for my Data Provider, nested inside the tags, along with all of my entries. The only attributes I needed were:
android:name=".DataManagement.DbDataProvider"
android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
android:exported="false"
(Make sure to change the values for the above attributes to match your project)
I cleaned, built, ran, and onCreate() methods for the data provider and open helper classes executed properly, and the database was created on first application launch!
I had the same problem.. the resolution for me was to add .db as extension of the database name
In my case, it was not being called because the database already existed! So, if possible, make sure to delete your app and install it back and only then check if it is being called or not.
I had the same problem where it seemed that the onCreate was not executed. I thought so because my logs were not displayed. Turned out that there was something wrong with the blank spaces in my SQL_create String.
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
db.execSQL(SQL_CREATE);
}
catch (Exception ex) {
Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
}
}
This is my corrected SQL-String:
enterpublic static final String SQL_CREATE =
"CREATE TABLE " + TABLE_VOCAB_LIST +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_GERMAN + " TEXT NOT NULL, " +
COLUMN_SPANISH + " INTEGER NOT NULL, "+
COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here
I had forgotten one blank space and when I added it everything worked fine.
You can change AUTOINCREMENT to AUTO INCREMENT
Note
SQLiteOpenHelper Called onCreate when the database is created for the first time. If you create table in onCreate method you can't create new SQLiteDatabase. You can see example
#Override
public void onCreate(SQLiteDatabase db) {
String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
"id TEXT PRIMARY KEY, " +
"name TEXT )";
db.execSQL(stringCreateTable);
}
I am trying to learn about SQLite databases, but I really hate dealing with any back-end stuff, with a passion. I'm already hitting walls with a seemingly simple problem.
Here is the code that I think matters from the DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Library";
public static final String TABLE_NAME = "books";
public static final String TITLE = "title";
public static final String AUTHOR = "author";
public static final String ISBN = "isbn";
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, title TEXT, author TEXT, isbn TEXT)");
}
public boolean insertBook(String title, String author, String isdn) {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, title);
cv.put(AUTHOR, author);
cv.put(ISBN, isdn);
db.insert(TABLE_NAME, null, cv);
db.close();
return true;
} catch (Exception exp) {
exp.printStackTrace();
return false;
}
}
}
And this is the code in my main activity
dbHelper = new DatabaseHelper(this);
dbHelper.insertBook("Harry Potter", "JK", "1000");
dbHelper.insertBook("Hamlet", "Shakespeare", "500");
Eclipse is telling me that there is an error in the insertBook() method. It says that there is no such table books: .... I have no idea what I am doing wrong here. What makes it more frustrating is that only a couple of minutes before it was working perfectly, then (I think) I dropped the table and it just create it again for whatever reason, even though this code has not changed since I first created it (I think...).
There is an older version of the database on your device, which does have the (empty) database in place, but not the books table. If that's an option for you, just uninstall and reinstall the app.
Later, when you'd like to add a new table to the database during production on end-user devices, but keep existing data, the designated hook to add new tables, alter the schema or upgrade your data is the onUpgrade method of your SQLiteOpenHelper.
I have written a ORM framework for that. https://github.com/ahmetalpbalkan/orman
You can easily write Android applications using SQLite with that. It uses your Java classes (Book, in this case) as database tables (entities).
It even creates your table automatically and you just say book1.insert(), done.
You must uninstall the applcation and then reinstall it. It should work after that.
try this one
for example for insert:
public boolean insertBook(String title, String author, String isdn) {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, title);
cv.put(AUTHOR, author);
cv.put(ISBN, isdn);
***try
{
db.insert(TABLE_NAME, null, cv);
}
catch ( SQLiteException e)
{
onCreate(db);
db.insert(TABLE_NAME, null, cv);
}***
db.close();
return true;
} catch (Exception exp) {
exp.printStackTrace();
return false;
}
}
Nothing about this made any sense, as the table existed from the very beginning of the DB, so we tried different things:
uninstalling app
claning cache / data
changing database version number
forcing to copy the database even if it already existed
If for some reason, you dropped the table, you might want to delete the database to force the application to recreate it correctly. Use adb shell and find the database in /data/data/[package_name]/databases/. You can just delete the file.
I had this problem, but cleaning the project did not fixed it.
It turned out I passed DATABASE_NAME instead of TABLE_NAME.
Make sure that onCreate method called. I am also facing similar type of problem when creating multiple table. If you create a separate class make sure you first clear all the storage data of your app and then again run it ..It will work fine for me.
Also had the issue where I already had the app built with an existing DB, but wanted to add another table.
Besides having the onUpgrade method, I also had to increment the private static final Integer DB_VERSION, which is used when instantiating the DatabaseHelper, like so:
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
Also from the official documentation, my onUpgrade method looks like this:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_2);
// create new tables
onCreate(db);
}
Then, after building the app, the new version of the database worked.
Note:
External Database You Access Time must add for the path in Sqliteopenhelper class
public final static String DATABASE_PATH = "/data/data/com.example.shortcuts/databases/";
com.example.shortcuts=Your Package name
db.execSQL(
"CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT)"
);
remove space after the table name, it should be like this.
db.execSQL(
"CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT)"
);