Get data from sqlite database - android

I have an activity and want to get data from my sqlite database. It works, but my activity only retrieves the last row and not the whole column. What can i do to get the whole column?
This is the code in my database:
public String getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
}
c.close();
return name;
}
This is the code in my activities to contact the database:
Database getdata = new Database(this);
getdata.open();
String data = getdata.getName();
getdata.close();

use cursor.moveToFirst() method example given below
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
list.add(cursor.getString(6));
} while (cursor.moveToNext());
}

See, As I said, Without seeing code I m helpless.. And after seeing your code..
You are returning only single String from that function getName() instead it return String[].
Note: this is only pseudo code.. Actual may be different..
public String[] getName() {
int i=0;
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
String name[] = new String[c.getCount()];
c.moveToFirst();
while(!c.isAfterLast()) {
name[i] = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
i++;
}
c.close();
return name;
}
And this one,
Database getdata = new Database(this);
getdata.open();
String data[] = getdata.getName();
getdata.close();

Update your code...
public String[] getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
int i=0;
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
String[] names = new String[c.getCount()];
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
names[i]=name;
c.moveToNext();
i++;
}
c.close();
return names;
}
Database getdata = new Database(this);
getdata.open();
String[] data = getdata.getName();
getdata.close();

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

Getting multiple entries for SELECT DISTINCT sqlite android?

I am trying to get the unique column name and show it as a list adapter.
public String[] getAllUsers() {
String[] contactList = new String[100];
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
int i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList[i] = cursor.getString(1);
i++;
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
The above is method in my database class.
And from mainActivity I call this method
private void updateUserList() {
// TODO Auto-generated method stub
String[] contactList = new String[100];
contactList = db.getAllUsers();
Log.d("User List",contactList[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
The list is getting updated ,but list is getting repeated as a whole
I don't know if I fully understood your question.
If you want to get columns KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE from all rows in database without KEY_NAME repetitions use this query:
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
In your methods do not use Array instead use ArrayList<String>
public ArrayList<String> getAllUsers() {
ArrayList<String> contactList = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList.add(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
And updateUserList():
private void updateUserList() {
// TODO Auto-generated method stub
ArrayList<String> contactList;
contactList = db.getAllUsers();
Log.d("User List", contactList.get(0));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
As you only use the column KEY_NAME from cursor the query can be simplified to return only that column.
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] {KEY_NAME}, null, null, null, null, null, null);
The problem was with initializing the String array as 100. I wrote a method to get the total number of counts and it works fine.
public int getUsersCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
//cursor.close();
// return count
return cursor.getCount();}

Sqlite query for multiple result

i want to query for data in sqlite, but in the case where 2item have the same name.. still it return only result... what should i add in this code?
public String getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
Log.v(name,name + ("zz"));
return name;
}
return null;
}
Try sending List<String>
public List<String> getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
List<String> lst = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
String name = c.getString(1);
lst.add(name);
Log.v(name,name + ("zz"));
} while (cursor.moveToNext());
}
return lst;
}

How to import a specific data from all the columns into a single array

I need to import a list of names from the SQLite Database (where it is stored ) in form of an array . Is this the right way to do it
Code for Database
public String queryAll() {
// TODO Auto-generated method stub
String [] columns = new String [] {KEY_NAME};
Cursor point = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iName = point.getColumnIndex(KEY_NAME);
for(point.moveToFirst();!point.isAfterLast();point.moveToNext()){
result = result + point.getString(iName);
}
return result;
Code to where I should import the data to
DBContact info = new DBContact (this);
info.open();
String data[] = info.queryAll();
info.close();
NewContact = (Button) findViewById(R.id.bAddContact);
I am a beginner , anything would help a lot.
Thank you
public String[] queryAll() {
String [] columns = new String [] {KEY_NAME};
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (cursor != null) {
try {
final int nameColumnIndex = cursor.getColumnIndex(KEY_NAME);
List<String> names = new ArrayList<String>();
while (cursor.moveToNext()) {
names.add(cursor.getString(nameColumnIndex));
}
return names.toArray(new String[names.size()]);
} finally {
cursor.close();
}
}
return null;
}

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

Categories

Resources