Android: sqlite querying based on username - android

public ArrayList < PatientInfo > getAllPatients(String username) {
ArrayList < PatientInfo > patients = new ArrayList < PatientInfo > ();
open();
Cursor cursor = db.query(UserTable, null, null, null, null, null, AccessedDate);
while (cursor != null && cursor.moveToNext()) {
try {
} catch (Exception ex) {
//Log.e("XXX", ex.getMessage());
}
}
if (cursor != null)
cursor.close();
close();
Collections.reverse(patients);
return patients;
}
I am getting username as argument in my method, how can i query out my table based on username and get the user specific result.

As you can see from the documentation, the third and fourth parameters to query() are the selection and selection args.
So you want something like this:
Cursor cursor = db.query(UserTable, null,
"username=?", new String[] {username},
null, null, AccessedDate);
Edit the third parameter as needed to match the actual name of the relevant column in your table.

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...

I can't get data from Cursor Object

I've following table structure in my SQLite Database.
In my SqliteOpenHelper class, I wrote following method.
public Form getAllForms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
int count = cursor.getCount();
String formID = cursor.getString(0);
Form form = new Form();
form.setId(formID);
cursor.close();
db.close();
return form;
}
I'm sure there's some data in it because I already watched count in debugging mode and I saw the quantity of row that actually existing in database. But CursorIndexOutOfBoundException shows up at cursor.getString(0). plus cursor.getInt(0) and cursor.getString(1) didn't work also. What's the problem might be?
You need to move the cursor to a valid row.
Valid rows are indexed from 0 to count-1. At first the cursor will point to row index -1 i.e. the one just before the first row.
The canonical way of looping through all rows is
if (cursor.moveToFirst()) {
do {
// now access cursor columns
} while (cursor.moveToNext());
}
Try this
try {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
Form form = new Form();
form.setId(formID);
cursor.moveToNext();
}
} finally {
// database.close();
cursor.close();
dbHelper.close();
}
You need to call moveToFirst() to get to the first row before asking for values:
if ((cursor!= null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
}
So Simply use your code as
public Form getAllForms(){
Form form = new Form();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
if ((cursor != null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
String formID = cursor.getString(0);
form.setId(formID);
cursor.moveToNext();
}
cursor.close();
}
db.close();
return form;
}

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

using the contacts manager in android

i have an app which shows the received messages as a Toast through a BroadcastReceiver. I am presently using the SmsMessage.getOriginatingAddress() method which gives me the number of the sender, how can modify it to get the corresponding name of the sender if stored in the contacts?
You will need to query the contacts for the rest of the data.
First query for the contacts id using the phone number.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address),
new String[] { Contacts.Phones.PERSON_ID }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long id = Long.valueOf(cursor.getLong(0));
if (Log.DEBUG) Log.v("Found person: " + id);
return (String.valueOf(id));
}
} finally {
cursor.close();
}
}
Then query for the Contacts name with the id from the first query.
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id),
new String[] { PeopleColumns.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String name = cursor.getString(0);
if (Log.DEBUG) Log.v("Contact Display Name: " + name);
return name;
}
} finally {
cursor.close();
}
}
You may be able to combine these two queries somehow.

Categories

Resources