How to fetch record from Sqlite - java

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 .

Related

Android SQLITE, unable to open database in Marshmallow only

I built an app. (The app can save favourite items using SQLite Database). I tried running it on Android Nougat and there is no error. When I tried running it on Android Marshmallow, the app won't open (Force close) and when I check the error it says unable to open database. After that, I tried running it on Android Lollipop and there is no error found.
I trace the error and found on the Marshmallow, the database is not created. (I used DB debugger to check the DB). I already add these user permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and nothing happened. Anyone else knows about this??
**NEW EDIT
this is the syntax to check if the db already created or not
public DataHeper(Context context) {
// TODO Auto-generated constructor stub
this.mContext = context;
databasePath = "data/data/"+context.getPackageName()+"/databases/data.sqlite";
databaseFile = new File(databasePath);
if(!databaseFile.exists())
try {
deployDataBase(databaseName, databasePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public int getTotalQuotesNoFilter(){
int i =0;
String query="";
Cursor cursor;
//This is the line that produce error (On Marshmallow only).
//I trace it and found out the db not created, thats why opendatabase produce error
database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
query = "SELECT count(quotes._id) FROM quotes;";
WriteLog.d("ThangTB", "query: "+query);
try {
cursor = database.rawQuery(query, null);
if (cursor != null){
boolean bool = cursor.moveToFirst();
int j = cursor.getInt(0);
i = j;
}
if (cursor!=null) {
cursor.close();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
database.close();
}
return i;
}
SQLite Db needs no user permission. So I guess there is some other issue. Post your code.
From Android M onwards, permissions needs to obtained from User while he/she is using the app, solely mentioning in Manifest wont do.
It is super easy to implement it using this library.
https://github.com/googlesamples/easypermissions
From Marshmallow you need to request permission from user at run time, I also had the same problem check this link, it will help you.
https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/

How to use getWritableDatabase() in onCreate function of SQLite database?

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.

Android: How to close a cursor that returns from Class to Activity

I have: Accounts.java
public class Accounts{
private SQLiteDatabase dbConfig;
public Cursor list(Context context, String db, String where, String order) {
DBHelper dbHelper = new DBHelper(context, db);
dbConfig = dbHelper.getReadableDatabase();
Cursor c = dbConfig.query("accounts", new String[]{ "iId","sName"}, where, null, null, null, order);
return c;
}
}
and: MainActivity.java
Accounts account = new Accounts();
Cursor cursor = account.list(getApplicationContext(), globalDB, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
}
cursor.close();
Running my application I get some logcat messages like:
close() was never explicitly called on database...
What is the best way to prevent it? How can I close a Cursor that returns from other class?
Thanks
After account.list() exits, the underlying database connection is still open, but there are no remaining references to it. So, it has leaked.
You can close the database once you're finished with it, or you can keep it open for the lifetime of your application by having a single global database connection which you open once, share amongst all your activities, and never close.
I recommend the latter approach. It results in much simpler code.
instead of calling cursor.close(); you can call and create a Accounts.close() method that closes both cursor and database

How to solve this exception?

I have been getting this exception, DatabaseObjectNotClosedException:
close() was never explicitly called on database '/data/data/com.project.test/databases/database'
E/SQLiteDatabase(13921): android.database.sqlite.DatabaseObjectNotClosedException:
Application did not close the cursor or database object that was opened here
I tried closing the database helper and cursors, but I will get runtime exception. This happens when I leave the activity and revisit it after hitting the back button.
How can I close my cursors and helpers properly?
I have tried two methods:
first, closing the cursors after each individual use, and closing the database helper onpause.
second, closing the cursors onpause along with the databasehelper, but both didn't work.
can someone help me with this?
EDIT:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this.getActivity();
context = this.getActivity().getApplicationContext();
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDbHelper = new DatabaseHelper(context);
mDbHelper.open();
populateList();
}
public void populateList() {
directoryCursor = mDbHelper.fetchAllRootDirectories();
activity.startManagingCursor(directoryCursor);
adapter = new DirectoryListAdapter(this.getActivity(), directoryCursor);
this.setListAdapter(adapter);
}
......
private UpdateDatabaseListener updateDatabaseListener = new UpdateDatabaseListener() {
public void onUpdate(int from, int to) {
.....
findExistingRecordCursor = mDbHelper.findExistingRecords(from, to);
activity.startManagingCursor(findExistingRecordCursor);
if(findExistingRecordCursor.getCount() == 0) {
....
}
}
}
I have a database helper opened in the onCreate() function.
cursors used when populating the listview,
cursors used to find existing records,
cursors to get information.
UPDATE:
I have tried closing onPause and onDestroy, it still crashes with runtimeexception.
Are you closing the SQLiteDatabase object or not. If not try to close SQLiteDatabase Object like this
SQLiteDatabase db = SQLiteHelper classobject.getWriteableDatabase();
// block of code
db.close();
and run your application.
Could you please post your code so that it will be more helpful to understand your problem.
Sorry for the late reply.
From what I see, you have opened the db using
mDbHelpher.open()
After that you did populatelist()
did you try doing mDbHelpher.close() after that?
Same thing with the cursors. Because your error clearly says that the db or the cursor was left open.
As soon as you are done using the db, you should close. This should not give the problem even after you visit another activity and then press back button.
Also you said you get runtime exception when you close the db or the cursor. Is it the same exception or different?

Android SQLiteOpenHelper: Why onCreate() method is not called?

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);
}

Categories

Resources