Android SQLite get data from database to an array - android

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

Related

showing record in text view using sqlite table

i have created this method in dbHelper class.
I am calling this method from mainActivity using onClickListener to show column 1 of each row one by one by changing cursor position.
i need to move the cursor to next row each time the button is clicked to show the string in Column1 in a textView.
i am new to android and programming too, so please bear with me.
public String nextData() {
String nQuote = "";
int i=0;
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_IQ };
Cursor resultSet = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
resultSet.movetoPostion(i);
if (i==0||i!=resultSet.getcount()){
resultSet.moveToNext();
nQuote = resultSet.getString(1);
i++;
}
return nQuote;
}
use this,
public String nextData(int position) {
String nQuote = "";
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_IQ};
Cursor resultSet = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (position >= 0 && position < resultSet.getCount()) {
resultSet.moveToPosition(position);
nQuote = resultSet.getString(1);
}
resultSet.close();
return nQuote;
}

updating sqlite database to sort integers from highest value down

How would i go about this, i have COLUMN_ID, COLUMN_NAME and COLUMN_INTE
COLUMN_INTE holds long integers and I want it to be displayed on a List view, which it currently does just not descending from highest to lowest
You need to write your query against your table with an ORDER BY clause that dictates a descending order with the DESC keyword. Something like this should work:
string query = "SELECT COLUMN_ID, COLUMN_NAME, COLUMN_INTE FROM MY_TABLE ORDER BY COLUMN_INTE DESC";
Cursor c = db.rawQuery(query, null);
String[] columns = new String[] { "COLUMN_ID", "COLUMN_NAME"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
try {
dataAdapter = new SimpleCursorAdapter(
this, android.R.layout.simple_list_item_2, c, columns, to, 0
);
ListView lv = (ListView) findViewById(R.id.MY_LISTVIEW);
lv.setAdapter(dataAdapter);
} catch (Exception ex) {
ex.printStackTrace();
}
You can also use comparator to do sorting . Like an example -
class MySalaryComp implements Comparator{
#Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
You have two options: Use an SQL command that sorts for you or you can get the entire list and sort it yourself.
SQL command sorting:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS order by COLUMN_INTE";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
Sort yourself:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
// Sort the object

how to get all IDs from a sqlite database

I have a database manager class where i build a table that has two columns. the first column being an integer, and i am trying to write a method that will return all values in that column as a list:
public List<Integer> getAllStyleIDs(){
List<Integer> results = null;
SQLiteDatabase db = this.getReadableDatabase();
// Select All Query
String selectQuery = "select * from " + DBConstants.allStyles;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
results.add(cursor.getInt(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return results;
}
but i am getting a null point exception
any ideas?
Your list results is null, then you attempt to add to it. Try this:
List<Integer> results = new ArrayList<Integer>();
First thing: the list hasn't been initialized.
Second thing: using raw queries is not recommended:
Try something like this:
List<Integer> results = new ArrayList<Integer>();
this.database = this.getReadableDatabase();
String [] columns = {_ID}; // name of the column
Cursor cursor = this.database.query(COURSES_TABLE, columns, null, null, null, null, null);
int iId = cursor.getColumnIndex(_ID);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
Integer rowId = cursor.getInt(iName);
results.add(rowId);
}
cursor.close();
this.database.close();
return results;

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

Iterate through rows from Sqlite-query

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

Categories

Resources