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();
}
Related
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("notification_description"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
this is my code currently i am getting from 0 to n data in staring array i want to get in reverse array data from n to 0 so that i can Print please suggest me how i will get data
Try this method :
public ArrayList<String> getAllDescription()
{
ArrayList<String> array_list = new ArrayListString>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * " + " FROM " + NOTIFICATIONTABLE+ " DESC;", null);
res.moveToFirst();
while (res.isAfterLast() == false)
{
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Or If you want to reverse arrayList then you can also do it By just a single line of code .
Collections.reverse("yourArrayList");
Hope it will help you.
i am getting from 0 to n data in staring array i want to get in
reverse array data from n to 0
Why not using ASC or DESC in db query to get result in sequence as want according to notification_description column.
do it as:
cursor = db.query(NOTIFICATIONTABLE,
new String[]{"notification_id",
"notification_title",
"notification_description",
"notification_isread",
"date"}, null, null, null,
null, "notification_description DESC");
You can insert the data from end of theString[]...
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
///////////////////////
result[(cursor.getCount()-1)-i] = cursor.getString(cursor.getColumnIndex("notification_description"));
///////////////////////
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
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();
I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}
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
I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.
I use this code to populate the TextViews inside the table rows.
Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);
I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.
How can I iterate through the resulting cursor?
Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:
while (cursor.moveToNext()) {
// Extract data.
}
Reference from SQLiteDatabase.
You can use below code to go through cursor and store them in string array and after you can set them in four textview
String array[] = new String[cursor.getCount()];
i = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
array[i] = cursor.getString(0);
i++;
cursor.moveToNext();
}
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
// use cursor to work with current item
}
Iteration can be done in the following manner:
Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Found a very simple way to iterate over a cursor
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
// access the curosr
DatabaseUtils.dumpCurrentRowToString(cursor);
final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
}
I agree to chiranjib, my code is as follow:
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
do{
//do logic with cursor.
}while(cursor.moveToNext());
}
public void SQLfunction() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"column1","column2" ...};
String sqlTable = "TableName";
String selection = "column1= ?"; //optional
String[] selectionArgs = {Value}; //optional
qb.setTables(sqlTable);
final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
if(c !=null && c.moveToFirst()){
do {
//do operations
// example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
}
while (c.moveToNext());
}
}
NOTE: to use SQLiteQueryBuilder() you need to add
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
in your grade file