Display multiple rows in a textview Android - android

Hello guys I want to display records. However, I don't want to display them in listview but in textview. I have in my to do the new line feed \n to do the trick, but in my program, it just shows the first record.
This is what I've tried so far:
MainActivity.class
Bundle extras = getIntent().getExtras();
if (extras != null) {
dog_name = extras.getString("dog_name");
cursor = dbHelper.fetchbBreedByName(dog_name);
strID = cursor.getString(0);
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
strDiet = cursor.getString(cursor.getColumnIndexOrThrow("diet"));
strShelter = cursor.getString(cursor.getColumnIndexOrThrow("shelter"));
strHygiene = cursor.getString(cursor.getColumnIndexOrThrow("hygiene"));
strMedication = cursor.getString(cursor.getColumnIndexOrThrow("medication"));
strBreed = cursor.getString(cursor.getColumnIndexOrThrow("breed"));
Log.d("Animal ID", "Animal ID is " + strID + " and breed is " + strBreed);
Log.d("Desc", "Desc " + strDesc);
Description.setText(strDesc);
Diet.setText(strDiet);
Shelter.setText(strShelter);
Hygene.setText(strHygiene);
Medication.setText(strMedication); }
DBHelper.class
public Cursor fetchbBreedByName(CharSequence inputText) throws SQLException {
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_DESCRIPTION,
KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
null, null, null, null, null);
}
else {
String qry = "SELECT _id, description, diet, shelter, hygiene, medication, " +
"breed FROM tblAnimalInfo WHERE breed LIKE '%" + inputText + "%';";
mCursor = myDataBase.rawQuery(qry, null);
//mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_DESCRIPTION,
// KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
// KEY_BREED + " like '%" + inputText + "%'", null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I don't know what's wrong. Please help me figure out what's missing in my code. Thanks in advance.

It seems that you are only loading the first row given by your Cursor. You have to use cursor.moveToNext(); to be able to get the rest of your data. Take a look to the example below:
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}

You are missing cursor.moveToNext() function to move to the next record, as mentioned earlier. Besides I would like to mention a few other issues in the coding style. You should not call moveToFirst() in the query function itself, use it where you are actually traversing through the records. Also make sure you close the cursor appropriately. So your code should look like:
cursor = dbHelper.fetchbBreedByName(dog_name);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
....
< access the record >
...
} while (cursor.moveToNext());
}
cursor.close(); // very important
}
And remove these lines from fetchbBreedByName()
if (mCursor != null) {
mCursor.moveToFirst();
}

Related

search sqlite with multiple columns

Hi every one I'm trying to search my sqlite data base which has 4 columns but the app crashes and the log error is :-
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I'm wondering if there is a method to search sqlite data base with multiple columns and with single columns.
The code for the cursor is :-
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
DataBase Code is :
public Cursor search(String searchString) {
String[] columns = new String[]{KEY_WORD};
String where = KEY_WORD + " LIKE ?";
searchString = "%" + searchString + "%";
String[] whereArgs = new String[]{searchString};
Cursor cursor = null;
if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
return cursor;
}
and the search class is :
public void showResult(View view) {
String word = editText_search.getText().toString();
textView.setText("Result for " + word + ":\n\n");
Cursor cursor = mDataBase.search(word);
cursor.moveToFirst();
if (cursor != null & cursor.getCount() > 0) {
int index;
String result;
do {
index = cursor.getColumnIndex(mDataBase.KEY_WORD);
result = cursor.getString(index);
textView.append(result + "\n");
} while (cursor.moveToNext());
cursor.close();
} else {
textView.append("no result");
}
}
Your cursor does not return anything. this is how I usually use database in android: by using .rawQuery(); and SQLite.
e.g.
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tasks WHERE id = " + id, null);
And you can also check if the cursor is empty or not by calling cursor.moveToFirst();.
If cursor was empty, the method returns false. else it returns true.
After checking that, you can go to the row that you want by using cursor.move(rowNumber); and get the value of the column you want with get methods e.g. cursor.getString(1);

retrieve specific values from SQLite database

I am a beginner in Android. I created a database with unique id, name, email etc. I want to retrieve the specific data from the database using the unique id. I don't know what to do. I read the previous answers but didn't get any idea from that.
At first you should read SQL Database
Below code is DEMO
public String getSpecificResult(int getID) // you should pass getID from your Class
{
SQLiteDatabase db = this.getWritableDatabase();
String get_Status = "0";
String selectQuery = "SELECT your_coloum_ FROM "+ TABLE_NAME + " WHERE " + YOUR_UNIQUE_KEY + " = '"+ getID +"'";
Cursor c = db.rawQuery(selectQuery, null);
if (c != null && c.moveToFirst()) {
get_Status = c.getString(0); // Return 1 selected result
}
db.close();
return get_Status;
}
Try this..
pass ur unique_id to get the contents.. alter names according to your table.
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_NUMBER}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

how to use where clause in cursor query in sqlite

I want only particular rows that has "E" inside the column "TX_IDT". I used the following code but apps stops. In logcat the error says it is at db.query line.
public Cursor getAllRows( ) {
String where = null;
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { VivzHelper.UID, helper.UID,helper.NAME,helper.TX_IDT};
String whereClause = "TX_IDT = ? ";
String[] whereArgs = new String[] { "E" };
Cursor c = db.query( VivzHelper.TABLE_NAME, columns,whereClause,whereArgs, null, null, NAME + " ASC"); // for out btn
if (c != null) {
c.moveToFirst();
}
return c;
}
`
Seems like you want record's containing "E" ,
Try this
Cursor c = db.query(VivzHelper.TABLE_NAME, columns, helper.TX_IDT +" LIKE '%E%' ", null, null, null, null);

cant access data in sqlite database

I wrote this function which takes in a post id and finds the last name for that post id.When I run this I get error :
database.cursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
What is wrong?
public Person_Obj GetPerson_Obj(int post_id)
{
Person_Obj obj = new Person_Obj();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_Persons + " WHERE "
+ Post_Id + " = " + post_id;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
obj.set_last_name(cursor.getString(cursor.getColumnIndex("LastName")));
return obj;
}
Try this,
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.rawQuery("query", null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
// write your code
} while (cursor.moveToNext());
}
database.close();

Using the ContactsContract cursor to get the contacts by group

How would I filter the returned contacts by the groupName?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
String groupName = parent.getItemAtPosition(pos).toString();
Log.i(this.toString(), String.format("Show Group: %s", groupName));
Cursor cur = this.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (name != null) {
Log.i(this.toString(), String.format("Show: %s", name));
}
}
cur.close();
}
}
I was able to filter contacts by group by using the following query:
Cursor c = this.managedQuery(Data.CONTENT_URI, new String[] {
Contacts.DISPLAY_NAME, Contacts._ID },
GroupMembership.GROUP_ROW_ID + " = ?",
new String[] { groupId }, Phone.TIMES_CONTACTED + " DESC");
Obviously you need to know the Group Id in order to complete this, how I did this was used a SimpleCursorAdapter to a Spinner w/the following Cursor:
Cursor c = managedQuery(Groups.CONTENT_URI,
new String[] { Groups.SYSTEM_ID, Groups._ID,},
Groups.SYSTEM_ID + " NOT NULL",
null, null);
This works for me for getting all group IDs rather than just system IDs:
public HashMap<String, Long> fillGroupsHashMap(HashMap<String, Long> groups) //
{
Cursor tempCur = activity.managedQuery(Groups.CONTENT_URI,
new String[] { Groups._ID, Groups.TITLE }, null, null, null);
tempCur.moveToFirst();
while (tempCur.moveToNext()) //
{
groups.put(tempCur.getString(1), tempCur.getLong(0));
}
return groups;
}
Unfortunately only System Groups ("groups that have a special meaning to the sync adapter") have SYSTEM_IDs. So this method is not bullet proof.
I had a heachache with this, but finally i get this working with whis code, and now i can filter by only phone numbers and avoid repeated and unused groups:
String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID, ContactsContract.Groups.TITLE,ContactsContract.Groups.SUMMARY_COUNT ,ContactsContract.Groups.SUMMARY_WITH_PHONES };
Cursor c = context.getApplicationContext().getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.SUMMARY_WITH_PHONES +"> 0"
, null, ContactsContract.Groups.TITLE + " ASC");

Categories

Resources