If I try to close the cursor with onSets.close(); in method getData(), the data does not appear in the position. If I do not close the cursor method, then Eclipse complains and says that the base or the cursor is not closed.
But if I add a line c.moveToFirst(); in the method getSets(String toexes_ids, String toprog_dif), the error does not appear. Why is that?
I have two method:
One method in MyDatabase.java
public Cursor getSets(String toexes_ids, String toprog_dif) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"_id", "exes_ids", "sets_ids", "sets_weight", "sets_ones"};
String sqlTables = "Sets";
String selection = "exes_ids = " + toexes_ids + " AND " + "prog_dif = " + toprog_dif;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, selection, null, null, null, null);
c.moveToFirst();
return c;
}
Second method in MainActivity.java
public void getData() {
db = new MyDatabase(this);
onSets = db.getSets(toexes_ids, toprog_dif);
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.itemsets, onSets,
new String[] {"sets_ids", "sets_weight", "sets_ones"},
new int[] {R.id.itemsets_ids, R.id.itemsets_weight, R.id.itemsets_ones});
listSets.setAdapter(adapter);
db.close();
}
Error:
12-29 16:17:09.335: D/dalvikvm(571): GC_CONCURRENT freed 393K, 53% free 2759K/5767K, external 1574K/1802K, paused 5ms+10ms
12-29 16:17:09.355: E/Database(571): close() was never explicitly called on database '/data/data/com.exp.exp_betta/databases/fitsdbsqlite3'
12-29 16:17:09.355: E/Database(571): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-29 16:17:09.355: E/Database(571): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1847)
Try to close the database connection as soon as you finished taking data from it. Remained it open makes the database leaked that's why Eclipse throws the Error For not closing DatabaseObjectNotClosedException
public Cursor getSets(String toexes_ids, String toprog_dif) {
SQLiteDatabase db=getReadableDatabase();
//Querying the database
db.close(); //as you get the cursor you can now close the connection here.
return cursor;
}
public void getData()
{
}
I think you need to close the db instance created in getSets() method
Related
I don't know where are my mistakes. I am trying to store the lyrics.db file in my DB_PATH when the database doesn't exist and my checkDatabase method returns false, or my DB is obsolete.
However, I get the following :-
E/SQLiteLog: (14) cannot open file at line 36356 of [605907e73a]
(14) os_unix.c:36356: (2) open(/data/user/0/id.ac.umn.project_uts_mobile_16862/filesid.ac.umn.project_uts_mobile_16862/databases/lyrics.db) -
(1) Process ts_mobile_16862 : Pid (12455) Uid (10196) Euid (10196) Gid (10196) Egid (10196)
(1) osStat failed "/data/user/0/id.ac.umn.project_uts_mobile_16862/filesid.ac.umn.project_uts_mobile_16862/databases/lyrics.db" due to error (2)
(1) osStat failed "/data/user/0/id.ac.umn.project_uts_mobile_16862/filesid.ac.umn.project_uts_mobile_16862/databases" due to error (2)
(1) osStat failed "/data/user/0/id.ac.umn.project_uts_mobile_16862/filesid.ac.umn.project_uts_mobile_16862" due to error (2)
(1) Stat of /data/user/0/id.ac.umn.project_uts_mobile_16862 : st_mode(40700) st_uid(10196) st_gid(10196) st_ino(265643)
(1) Stat of /data/user/0 : st_mode(40771) st_uid(1000) st_gid(1000) st_ino(262147)
(1) Stat of /data/user : st_mode(40711) st_uid(1000) st_gid(1000) st_ino(196619)
(1) Stat of /data : st_mode(40771) st_uid(1000) st_gid(1000) st_ino(2)
E/SQLiteDatabase: Failed to open database '/data/user/0/id.ac.umn.project_uts_mobile_16862/filesid.ac.umn.project_uts_mobile_16862/databases/lyrics.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 1294): Could not open database
#################################################################
Error Code : 1294 (SQLITE_CANTOPEN_ENOENT)
Caused By : Specified directory or database file does not exist.
(unknown error (code 1294): Could not open database)
#################################################################
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:272)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:213)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:701)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:272)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:239)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:1276)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:1231)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:915)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:864)
at id.ac.umn.project_uts_mobile_16862.DbHelper.checkDatabase(DbHelper.java:50)
at id.ac.umn.project_uts_mobile_16862.DbHelper.createDB(DbHelper.java:85)
at id.ac.umn.project_uts_mobile_16862.show_lyrics.onCreate(show_lyrics.java:22)
at android.app.Activity.performCreate(Activity.java:7258)
at android.app.Activity.performCreate(Activity.java:7249)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1222)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3059)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1724)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
it's my code for load the DB
public class DbHelper extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static String DB_NAME = "lyrics.db";
private SQLiteDatabase vDatabase;
private Context vContext = null;
public DbHelper(Context context) {
super(context, DB_NAME, null, 1);
if( Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getFilesDir().getPath()+context.getPackageName()+"/databases/";
else
DB_PATH = context.getApplicationInfo().dataDir+"/databases/";
this.vContext = context;
}
#Override
public synchronized void close() {
if( vDatabase != null ) {
vDatabase.close();
}
super.close();
}
private boolean checkDatabase() {
SQLiteDatabase dbTemp = null;
try{
String path = DB_PATH + DB_NAME;
dbTemp = SQLiteDatabase.openDatabase(path, null, OPEN_READWRITE);
} catch ( SQLiteException e) { }
if (dbTemp != null ) {
dbTemp.close();
}
return dbTemp != null;
}
public void copyDB() throws SQLiteException{
try {
InputStream myInput = vContext.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
Log.d("LIFECYCLE", outputFileName);
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while( (length=myInput.read(buffer)) > 0 ){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
public void openDB() {
String path = DB_PATH + DB_NAME;
vDatabase = SQLiteDatabase.openDatabase(path, null, OPEN_READWRITE);
}
public void createDB() {
boolean dbExist = checkDatabase();
if ( dbExist ){
}
else {
this.getReadableDatabase();
copyDB();
}
}
public List<Lyric> getAllSong(){
List<Lyric> temp = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor;
try{
cursor = db.rawQuery( "SELECT * FROM lyrics" , null);
if( cursor == null) return null;
cursor.moveToFirst();
do {
Lyric lyric = new Lyric(
cursor.getString(cursor.getColumnIndex("index")),
cursor.getString(cursor.getColumnIndex("song")),
cursor.getString(cursor.getColumnIndex("year")),
cursor.getString(cursor.getColumnIndex("artist")),
cursor.getString(cursor.getColumnIndex("genre")),
cursor.getString(cursor.getColumnIndex("lyrics"))
);
temp.add(lyric);
} while (cursor.moveToNext());
cursor.close();
} catch ( Exception e){ }
db.close();
return temp;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I've already trying to debug this code for almost 15 hours, and even don't get a single clue, where are my mistakes.
how to check, if that path exist? and how to make directory / path if it didn't exist?
Step by Step guide.
1. Create the database using an appropriate SQLite management tool with the table lyrics populated with the required data. Ensuring the database is saved.
In this case NaviCat was used and the following SQL was used to create and populate the lyrics table.
:-
CREATE TABLE IF NOT EXISTS lyrics (
id INTEGER PRIMARY KEY,
song TEXT,
year TEXT,
artist TEXT,
genre TEXT,
lyrics TEXT
);
INSERT INTO lyrics (song, year, artist, genre, lyrics) VALUES
('song1','1970','Fred','Rock','Rock rock rock'),
('song2','1980','Mary','Pop','Pop pop pop'),
('song3','1960','Sue','Folk','Folk folk folk');
Note index is a keyword so is not a valid column name unless it is enclosed, so id has been used instead of index.
2. The file was saved as lyrics.db and copied into the assets folder of the project.
3. DbHelper.java (various modifications)
public class DbHelper extends SQLiteOpenHelper {
private static String DB_NAME = "lyrics.db";
private SQLiteDatabase vDatabase;
private Context vContext;
public DbHelper(Context context) {
super(context, DB_NAME, null, 1);
this.vContext = context;
// Copy the DB if need be when instantiating the DbHelper
if (!checkDataBase()) {
copyDB();
}
vDatabase = this.getWritableDatabase(); //Get the database when instantiating
}
/**
* No need for build version check as getDataBasePath works for all versions
* No need for open and close of Database, just open it once for the lifetime (more efficient)
*/
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
/**
* Does not open the database instead checks to see if the file exists
* also creates the databases directory if it does not exists
* (the real reason why the database is opened, which appears to result in issues)
*/
File db = new File(vContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database
Log.d("DBPATH","DB Path is " + db.getPath());
if (db.exists()) return true; // If it exists then return doing nothing
// Get the parent (directory in which the database file would be)
File dbdir = db.getParentFile();
// If the directory does not exist then make the directory (and higher level directories)
if (!dbdir.exists()) {
db.getParentFile().mkdirs();
dbdir.mkdirs();
}
return false;
}
public void copyDB() throws SQLiteException{
try {
InputStream myInput = vContext.getAssets().open(DB_NAME);
String outputFileName = vContext.getDatabasePath(DB_NAME).getPath(); //<<<<<<<<<< changed
Log.d("LIFECYCLE", outputFileName);
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while( (length=myInput.read(buffer)) > 0 ){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
public List<Lyric> getAllSong(){
List<Lyric> temp = new ArrayList<>();
Cursor cursor = vDatabase.query("lyrics",null,null,null,null,null,null);
//Cursor cursor = db.rawQuery( "SELECT * FROM lyrics" , null); // used query method generally preferred to rawQuery
//if( cursor == null) return null; // Cursor will not be null may be empty
//cursor.moveToFirst(); // changed to use simpler loop
while (cursor.moveToNext()) {
Lyric lyric = new Lyric(
//cursor.getString(cursor.getColumnIndex("index")), //<<<<<<< changed due to column name change
cursor.getString(cursor.getColumnIndex("id")),
cursor.getString(cursor.getColumnIndex("song")),
cursor.getString(cursor.getColumnIndex("year")),
cursor.getString(cursor.getColumnIndex("artist")),
cursor.getString(cursor.getColumnIndex("genre")),
cursor.getString(cursor.getColumnIndex("lyrics"))
);
temp.add(lyric);
}
cursor.close();
//db.close(); // inefficient to keep on opening and closing db
return temp;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Check the comments re modifications
4. Uninstall the existing App or delete the App's data (IMPORTANT)
5. Test it.
The following is an activity that will test the above.
public class MainActivity extends AppCompatActivity {
DbHelper vDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vDBHlpr = new DbHelper(this);
List<Lyric> mylyricslist = vDBHlpr.getAllSong();
for (Lyric l: mylyricslist) {
Log.d("LYRICFROMDB","Song is " + l.getSong() + " Year is " + l.getYear() + " Artist is " + l.getArtist() + " Genre is " + l.getGenre() + " Lyrics are " + l.getLyrics());
}
}
}
The log should include (first run) :-
03-17 19:42:11.067 16057-16057/? D/DBPATH: DB Path is /data/data/com.example.so55199382lyrics/databases/lyrics.db
03-17 19:42:11.067 16057-16057/? D/LIFECYCLE: /data/data/com.example.so55199382lyrics/databases/lyrics.db
03-17 19:42:11.086 16057-16057/? D/LYRICFROMDB: Song is song1 Year is 1970 Artist is Fred Genre is Rock Lyrics are Rock rock rock
03-17 19:42:11.086 16057-16057/? D/LYRICFROMDB: Song is song2 Year is 1980 Artist is Mary Genre is Pop Lyrics are Pop pop pop
03-17 19:42:11.086 16057-16057/? D/LYRICFROMDB: Song is song3 Year is 1960 Artist is Sue Genre is Folk Lyrics are Folk folk folk
or for subsequent runs :-
03-17 19:49:11.275 16136-16136/? D/DBPATH: DB Path is /data/data/com.example.so55199382lyrics/databases/lyrics.db
03-17 19:49:11.279 16136-16136/? D/LYRICFROMDB: Song is song1 Year is 1970 Artist is Fred Genre is Rock Lyrics are Rock rock rock
03-17 19:49:11.279 16136-16136/? D/LYRICFROMDB: Song is song2 Year is 1980 Artist is Mary Genre is Pop Lyrics are Pop pop pop
03-17 19:49:11.279 16136-16136/? D/LYRICFROMDB: Song is song3 Year is 1960 Artist is Sue Genre is Folk Lyrics are Folk folk folk
Note run twice so you check both the copy process and handling of the existing db.
The above was tested on emulators running Android Lollipop and Pie
I've already trying to debug this code for almost 15 hours, and even
don't get a single clue, where are my mistakes.
Your issue is that the databases directory doesn't exist when you try opening the database in the checkDatabase method.
The clue is here :-
Error Code : 1294 (SQLITE_CANTOPEN_ENOENT)
Caused By : Specified directory or database file does not exist.
(unknown error (code 1294): Could not open database)
The path is typically data/data/your_package/databases/your_database_file
data/data will exist as it's part of android.
The package sub-directory will exist as part of installing the package.
The databases directory does not initially exist, using a sub-class of SQLiteOpenHelper will, when creating the database, create the databases folder and hence why you see attempts to open the database via such a helper, simply to create the databases directory. However, this can be problematic as from Android Pie on SQLite WAL mode is used by default, which unless the -shm and -wal files are deleted before the copy of the database, result in an empty database being created (-wal/-shm files do not belong/correlate to the copied database so database file is deleted/emptied).
I'd suggest that rather than trying to open the database that you check to see if the File exists and if not to then check if the File's parentfile exists (the databases directory) and if that doesn't exist to use the mkdirs method to create the directory.
The following is an example method that does all the above checking :-
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
/**
* Does not open the database instead checks to see if the file exists
* also creates the databases directory if it does not exists
* (the real reason why the database is opened, which appears to result in issues)
*/
File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database
Log.d("DBPATH","DB Path is " + db.getPath());
if (db.exists()) return true; // If it exists then return doing nothing
// Get the parent (directory in which the database file would be)
File dbdir = db.getParentFile();
// If the directory does not exist then make the directory (and higher level directories)
if (!dbdir.exists()) {
db.getParentFile().mkdirs();
dbdir.mkdirs();
}
return false;
}
Note the above uses the recommended getDatabasePath so there is no need to hard code anything other than the database name (you may wish to adopt this throughout your code).
Learning how to program in android by following a tutorial but i am trying to also update the entry in the data base though not entirely how to do so. Any help please?
package dev.edmt.todolist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by reale on 06/10/2016.
*/
public class DbHelper extends SQLiteOpenHelper {
private static final String DB_NAME="EDMTDev";
private static final int DB_VER = 1;
public static final String DB_TABLE="Task";
public static final String DB_COLUMN = "TaskName";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format("CREATE TABLE %s (ID INTEGER PRIMARY KEY AUTOINCREMENT,%s TEXT NOT NULL);",DB_TABLE,DB_COLUMN);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = String.format("DELETE TABLE IF EXISTS %s",DB_TABLE);
db.execSQL(query);
onCreate(db);
}
public void insertNewTask(String task){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.insertWithOnConflict(DB_TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
public void deleteTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DB_TABLE,DB_COLUMN + " = ?",new String[]{task});
db.close();
}
public ArrayList<String> getTaskList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
}
More specifically this part, cant really say i quite understand the way it works:
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
More specifically this part, cant really say i quite understand the
way it works:
It may work, as in not fail, but as explained below it probably does nothing of any use.
The SQLiteDatabase update method is a convenient way of issuing the SQL to perform an update. It writes/creates the underlying SQl, executes it, and also returns the result (the number of rows updated).
Using your code as an example, to do the similar without using the update method you could create the SQL :-
UPDATE Task SET TaskName = 'your_value' WHERE Task = 'your_value'
Note that this is actually useless as you are effectively saying (assuming for demonstration that the value passed to the editTask method is task001); Update the task row(s) that has/have the value of task001 in the TaskName column to be changed from task001 to task001.
Note the update method uses UPDATE OR IGNORE...... so :-
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint
violation and continues processing subsequent rows of the SQL
statement as if nothing went wrong. Other rows before and after the
row that contained the constraint violation are inserted or updated
normally. No error is returned when the IGNORE conflict resolution
algorithm is used. SQL As Understood By SQLite - ON CONFLICT clause
Suggestion
Perhaps what would be more useful if say you wanted to change a row that before the update, has a value task001. Changing it say to task002.
in this case the SQL could be :-
UPDATE Task SET TaskName = 'your_new_value' WHERE Task = 'your_original_value'
Your editTask method could then be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
db.update(DB_TABLE,values,DB_COLUMN + " = '" + original_task + "'" ,null) > 0;
db.close();
}
e.g. using edittask("task001","task002");
Note how the value original_task is enclosed in single quotes.
However, the recommended way, would be to utilise arguments (which would automatically be enclosed in quotes) so the above could be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
String[] whereargs = new String[]{original_task};
db.update(DB_TABLE,values,DB_COLUMN + "=?",whereargs) > 0;
db.close();
}
each ? coded in the WHERECLAUSE (3rd parameter) replaced by the respective argument in the WHEREARGS (4th parameter) on a 1 by 1 basis.
Additional
In addition to creating the SQL, the update method also invokes the SQL using an appropriate means e.g. it does the equivalent of db.execSQL(your_sql) for you.
Additionally in the case of update it then does the equivalent of :-
Cursor csr = db.rawQuery("SELECT total_changes()",null);
int total_changes = 0;
if(csr.moveToFirst()) {
total_changes = csr.getInt(0);
}
return total_changes;
Hence returning the number of updated rows.
db.update method will create SQL statement according to your given parameters and execute it. You could see the db.update() method to find a better understanding.
This question already has answers here:
Android Cursor Index out of Bound Exception
(3 answers)
Closed 6 years ago.
I'm trying to retrieve data from sqlite data base but but when I call the nameData() logcat shows the exception:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
I don't understand why, any clues?
process:
public class SearchContactByName2 extends AppCompatActivity {
String dbString="",dbString2="";
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.searchcontactbynamelayout2_main);
TextView textView=(TextView)findViewById(R.id.textViewShowName);
TextView textView2=(TextView)findViewById(R.id.textView2ShowNumber);
SearchContactByName objOfSearchContactByName=new SearchContactByName();
ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
allcontact2.moveToFirst();
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
}
database part:
public class ContactDatabase extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME="totalContact.db";
public static final String TABLE_NAME="mecontact";
public static final String NAME="name";
public static final String PHONE="phone";
public ContactDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table mecontact" +
"(id integer primary key autoincrement, name text, phone text)");
}catch(android.database.SQLException e){
System.out.println("table create nhi ho rha");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mecontact");
onCreate(db);
}
public void insertContact(String nam,String mob){
db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(NAME,nam);
contentValues.put(PHONE,mob);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public Cursor showData(){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact", null);
return res;
}
public Cursor nameData(String dataName){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact WHERE name = '"+dataName+"'", null);
return res;
}
}
try below code
if(allcontact2.moveToFirst()){
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());}
Toast.makeText(getBaseContext(), " no data", Toast.LENGTH_LONG).show();
actually your database has no data
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
if(allcontact2.size() > 0){
while(allcontact2.moveToNext()){
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
Along with the answer by sush change nameData method to,
public Cursor nameData(String dataName){
db=this.getReadableDatabase();
//String dataname might contain special characters like a quote
//retreive the cursor this way
Cursor res=db.query("mecontact",new String[]{columnsYouwantToSelect},"name =?",new String[]{dataName},null,null,null);
//if you want to select all the columns in the table replace
//the second parameter with null
return res;
}
Not really answering your question, but more advice on how to prevent trouble in the future. I would suggest you change your oncreate code to this and declare your ID value in the top like you did for the others. This will make sure the database is created correctly and that in the future if changes happen you can easily get values without making typing errors. Code like this is safer to use than pure queries.
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME + " TEXT,"
+ PHONE + " TEXT);" );
I have a JSON Array. I'm using DatabaseHelper to transfer the data but I'm not able to fetch the data. I know I'm making a simple mistake but it's just not visible.
This is the onCreate method
arrayList = database.getAllData();
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.activity_list_item,
android.R.id.text1,
arrayList);
listView.setAdapter(adapter);
And this is the getAllData
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
This is something I did once. Can you get an idea from this? :)
public ArrayList<Item_Record> getAllRecords_ArrayList (String Table_Name) {
// Create an array list
ArrayList<Item_Record> List_Of_Records = new ArrayList<>();
// Create a database object
SQLiteDatabase DB = this.getReadableDatabase();
// Create a cursor file we get from executing this above command
Cursor crsr = DB.query(
Table_Name,
new String[] {COLUMN_DATE, COLUMN_CATEGORY, COLUMN_AMOUNT},
null, null, null, null, COLUMN_DATE);
crsr.moveToFirst();
while (! crsr.isAfterLast()) {
// Add that to the array list
List_Of_Records.add(new Item_Record(
crsr.getString(crsr.getColumnIndex(COLUMN_DATE)),
crsr.getString(crsr.getColumnIndex(COLUMN_CATEGORY)),
crsr.getDouble(crsr.getColumnIndex(COLUMN_AMOUNT))));
// Go to the next row
crsr.moveToNext();
}
// Closes database and cursor and return the list
crsr.close(); DB.close();
return List_Of_Records;
}
I would like to get the values from database of a particular column by executing a query. Is it possible to do it after we do it to the Cursor Adapter or can we attain the values well before itself. Kindly help on this with a snippet or a guide.
Context context = getApplicationContext();
final DataBaseHelper db = new DataBaseHelper(context);
...
...
db.createDataBase();
..
...try catch logic etc
....
final Cursor c = db.getAllRows();
....
c.getString(4) // String value of 5th Column in Database
Cursor Adapter to Array
ArrayList<String> mArrayList = new ArrayList<String>();
c.moveToFirst();
while(!c.isAfterLast()) {
mArrayList.add(c.getString(c.getColumnIndex(DataBaseHelper.KEY_NAME));
c.moveToNext();
}
DataBaseHelper class has following
public Cursor getAllRows()
{
return myDataBase.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_NAME,
KEY_YEAR,
KEY_QUOTE,
KEY_REF},
null,
null,
null,
null,
null);
}