fetching data from sqlite into array in android - android

The code to returns all the data in the table in list.But this isn't working.
I've called this method from CheckData class which is called by main class
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(1),
cursor.getString(2) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
My database contains 3 columns - id(integer primary key), symbol(text) and company_name(text).
My Data Base name is AppDB and table name is scrip.

Here are the good tutorial to LEARN use of Android-SQLite.
so,I also advise you the same As I answered here

Related

how to get String array in reverse order in Sqlite in android

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

Unable to fetch data while Query excuting in android Sqlite

public String[] getNewsLink(String prodcuttye) {
Cursor cursor = mDb.query(SQLITE_TABLE, new String[] { "productname" }, "ProdctType='"
+ prodcuttye + "'", null, null, null, null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("productname"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
mDb.close();
}
return result;
}
This function for fetch data in String array i am trying to excute this Query am getting data when i am call the in Sqlite browser[ select productname from MyShopingTable where ProdctType= 'Basmati Rice'] But when i try to run this Query in function i am getting cursor count 0 so i am unable to get data please tell me where am doing wrong please suggest me
Try changing your query like following :
Cursor c = mDb.query("SELECT * FROM MyShopingTable where ProdctType = ?",new String[]{prodcuttye})
See if that works in your case...

Get all rows from SQLite

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

Android SQLite get data from database to an array

i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();

Fetching sqldata into array

I have certain data in sqlite and want to fetch the data into an array of string, I am getting the first column successfully but cant able to fetch the next column data. Here is my code.
SQLiteDatabase db = contactsdbHelper.getWritableDatabase();
//db.openDatabase(path, factory, flags)
int columnIndex = 1; // Whichever column your float is in
Cursor cursor1= getData();
String[] values=new String[cursor.getCount()+1];
try{
if(cursor1.moveToFirst())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values[i]=cursor1.getString(columnIndex);
//Log.i("HI", "piyush");
Log.i("StartTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
String[] values1=new String[cursor.getCount()+1];
try{
if(cursor1.moveToNext())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values1[i]=cursor1.getString(columnIndex+1);
Log.i("EndTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
Why not fill both arrays at once?
SQLiteDatabase db = contactsdbHelper.getWritableDatabase();
//db.openDatabase(path, factory, flags)
int columnIndex = 1; // Whichever column your float is in
Cursor cursor1= getData();
String[] values=new String[cursor.getCount()+1];
String[] values1=new String[cursor.getCount()+1];
try{
if(cursor1.moveToFirst())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values[i]=cursor1.getString(columnIndex);
values1[i]=cursor1.getString(columnIndex+1);
Log.i("StartTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
But that whole thing looks kinda rubbish ... what are you trying to achieve?
You will need to call moveToFirst() on the Cursor again before you can start reading the second column.
Specifically the second if should be:
if (cursor1.moveToFirst())
Edit - usually data is in a database for a reason: you don't want to fetch it all into memory in one big array most of the time.
Could you be looking for a CursorAdapter and ListView combination to display the data in a list?
Try reading the column values by their column name.
Cursor cursor = ...
if(cursor.moveToFirst()) {
do {
values[i] = cursor.getString(cursor.getColumnIndex("columnName"));
values1[i] = cursor.getString(cursor.getColumnIndex("otherColumnName"));
} while(cursor.moveToNext());
}
where "columnName" and "otherColumnName" are the names of the columns of your table which you want to fill into the arrays.
Cursor cur = db.query(TABLENAME, null, null, null, null, null, null);
cur.moveToFirst();
int a[] = new int[100];
for (int i = 0; i < cur.getCount(); i++)
{
a[i] = cur.getInt(0);
cur.moveToNext();
}
Here is my code to return all the data in the table in list. But, it is not working.
I have called this method from CheckData class which in turn is called by main class via intent.
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
int x = 0;
if (cursor.moveToFirst())
{
do
{
String[] b1 = new String[]
{
cursor.getString(1),
cursor.getString(2)
};
list.add(b1);
x = x + 1;
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
cursor.close();
return list;
}
My database contains 3 columns - id(integer primary key), symbol(text) and company_name(text). My database name is AppDB and table name is scrip.

Categories

Resources