Here is the code in activity:
//query
final dbhelper helper = new dbhelper(this);
Cursor c = helper.query();
boolean exist =false;
if(c != null && c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}
//insert
ContentValues values = new ContentValues();
if(!finWords.equals("null")){
if(finWords.length()>index){
String selectWord = finWords.substring(index, index+1);
values.put("character", finChar);
values.put("word", selectWord);
helper.insert(values);
Here is the code in SQLiteOpenHelper:
public void insert(ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
db.insert(TBL_NAME, null, values);
Log.d("test", "dbinsert");
db.close();
}
public Cursor query() {
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TBL_NAME, null, null, null, null, null, null);
Log.d("test", "dbquery");
return c;
}
I can insert data into database
but I cannot query them
the logcat say the cursor index out of range
and just output some data for example just output with id 1,2,4,7 then force close the App
but I already insert 14 data
what wrong of my code?
You forgot to negate c.isAfterlast() and unless you pass null back you do not have to check for null cursor.
if(c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(!c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}
Related
I use a string to populate a textview on an listview
String[] text1 = { "Afghanistan", "Algeria" ,"Fred"};
I want to replace the 3 strings in the string array with data from a database. I have tried the following
String text1[];
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAsset3();
int counter = 0;
while (c.moveToNext()) {
text1[counter]=c.getString(0);
counter++;
}
getAsset3 from DBAdapter
public Cursor getAsset3() throws SQLException
{
Cursor mCursor =
db.query(true, "SURVDAT", new String[] {KEY_SR1,KEY_SR2,KEY_SR3,KEY_SR4,KEY_SR5,KEY_SR6,KEY_SR7}, null, null,null, null, null, null);
if (mCursor != null) {
//mCursor.moveToFirst();
}
return mCursor;
}
When I run the app crashes saying Null PointerException
Any ideas where I'm going wrong?
Any help Appreciated
Mark
You didn't initialize text1 in your second snippet, so when you type text1[counter] = c.getString(0); you are trying to get counter'th index of null
You shall do something like
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAsset3();
String text1[] = new String[c.getCount()];
for(int i = 0; cursor.moveToNext(); ++i)
{
text1[i] = c.getString(0);
}
cursor.close();
When I use the getPesoCount() like in the:
Log.v("SQL", String.valueOf(getPesoCount()));
I get aN error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: attemp to re-open an already-closed object: android.database.sqlite.SQLiteQuery(mSql = SELECT * FROM pesoTable)...
public void addPeso(int peso, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PESO, peso); // Contact Name
values.put(KEY_DATE, date); // Contact Phone Number
// Inserting Row
db.insert(TABLE_PESO, null, values);
Log.v("SQL", String.valueOf(getPesoCount()));
db.close(); // Closing database connection
}
public int getPesoCount() {
String countQuery = "SELECT * FROM " + TABLE_PESO;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
If I don't use getPesoCount(), no error occurs.
Can someone help me?
attempt to re-open an already-closed object:
Exception tells you a lot!
If you want to use the cursor further do not call cursor.close(); call it when you are sure that you do not need it anymore.
public void addPeso(int peso, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PESO, peso); // Contact Name
values.put(KEY_DATE, date); // Contact Phone Number
// Inserting Row
db.insert(TABLE_PESO, null, values);
Log.v("SQL", String.valueOf(getPesoCount(db)));
db.close(); // Closing database connection
}
public int getPesoCount(db) {
String countQuery = "SELECT * FROM " + TABLE_PESO;
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop
Please help me with following, I have a database which contain strings ( e.g. fotonames ).
And I want to read entire fotonames column into an arraylist.
How can I do this?
public Cursor getfotoname() throws SQLException
{
String getRT = "SELECT fotonames from "+ TABLE_NAME+";";
Cursor mCur = sqldb.rawQuery(getRT, null);
return mCur;
}
Now when you call
Cursor mCursor=null;
mCursor= DatabaseObject.getfotoname();
ArrayList<WhateverTypeYouWant> mArrayList = new ArrayList<WhateverTypeYouWant>();
for(mCursor.moveToFirst(); mCursor.moveToNext(); mCursor.isAfterLast()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getWhateverTypeYouWant(WHATEVER_COLUMN_INDEX_YOU_WANT));
}
Have a look at this tutorial will help you
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/
this is where you can lear how to fetch all values from one column
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/3/#getrowasarray
or otherway is
fire query like this
public Cursor columnValues() throws SQLException{
// TODO Auto-generated method stub
Cursor mCursor = db.query(Course_Info_Table,
new String[] {Column1 , column2 },
null,null, null, null, null);
//Cursor mCursor = mDb.rawQuery("Select",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
and receive it like
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list12 = new ArrayList<String>();
cursor = dbm.columnValueofCourse();
cursor.moveToFirst();
startManagingCursor(cursor);
for (int i = 0; i < cursor.getCount(); i++) {
String reciv = cursor.getString(cursor
.getColumnIndex("column1"));
String reciv3 = cursor.getString(cursor
.getColumnIndex("column2"));
list1.add(reciv);
list2.add(reciv3);
cursor.moveToNext();
}
what i want to do is do a search of my database for a string then find out what the row id is where that string is.
I thought by doing this
public void getRow(){
ContactDB db = new ContactDB(this);
db.open();
Cursor c = db.getId("1234567890");
String test = c.getString(c.getColumnIndex(db.PHONE_NUMBER));
Log.v("Contact", "Row ID: " + test);
db.close();
database class
public Cursor getId(String where){
return db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
}
that it would give me what i want but i get a "cursor index out of bounds" error, how should i be doing this?
change getId to:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
You need to do c.moveToFirst() before tying to read any information.
Also do c.close() when you're done.