Android MediaStore get cursor position by comparing with TITLE_KEY - android

I am using MediaStore's media content and have a SearchView to filter the content displayed in a listfragment.
I keep a reference to the cursor(mainCursor) when the query string is null (which means all rows)
When user searches, i get new cursor based on the query
As per my understanding(I am very new to Cursor,DB & Contentprovider), the cursor will contain all the rows matching the query and the column to query is MediaStore.Audio.Media.TITLE, so i can see matching titles in list.
public void doQuery(String query) {
// TODO Auto-generated method stub
Log.e(TAG,"inside doQuery: "+query);
String search = MediaStore.Audio.Media.TITLE + " LIKE '%" + query + "%'";
Cursor cursorNew = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns, search , null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
sendBroadcast(new Intent(MainActivity.SWAP_CURSOR));
}
Now when user presses list element, i getPosition() of the cursor and retrieve the TRACK_ID of selected item.
My question is: How to search the initial cursor, i.e., mainCursor with TRACK_ID got from cursorNew and to get the position of the matching TRACK_ID in mainCursor?
I don't want to SELECT from the mainCursor, because i want to get the position of a specific TRACK from the un-filtered cursor
Thanks in advance

If you are just interested in the position, why dont you put the audio_ids in an array
ArrayList<String> audio_ids = new ArrayList<String>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
String audio_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID));
audio_ids.add(audio_id);
}
and then use
String audio_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID));
position = audio_ids.lastIndexOf(audio_id);
This example queries playlists. The above example would give you the last position if you had duplicates. (something you perhaps had not thought about?)
I hope this gives you some ideas

Related

Why Sqlite return only last row not all rows data?

I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)

Disabling button and storing in database

I am calling same activity for 5, 6 different movies to book ticket. I have used button for seats. I set button disable after clicking and store its id in sql database. Now when I come again to book another ticket for same movie, same show
String[] projection= new String[]{
movieEntry.COLUMN_NAME_SEAT
};
//where clause
String selection=movieEntry.COLUMN_NAME_MN + " =?"+" AND "+movieEntry.COLUMN_NAME_MD +" =?" +" AND "+movieEntry.COLUMN_NAME_MT +" =?" ;
// int i=0;
String colindex=null;
// this query is select seatno from tablename
// where movie_name='movie that user selected' and movie_time='user seklected currently'
//and movie_date='';
//it is working correctly its fetching all records
// i am trying to add all this fetched seatno to the seatsArraylist so that
//we can get it from this arrayList and disable that seats for the user for that particular movie and date and time
// but problem is that it is adding only one records to arraylist
//can you plz go through this code
String[] selectionArgs ={ Movietitle, Datem, Mtiming} ;
try{
Cursor cursor = rdb.query(
movieEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
null
);
if(cursor!= null ) {
int i=0;
while(cursor.moveToFirst())
{
colindex= cursor.getString(i);
seatsArrayList.add(colindex);
i++;
tv1.setText(seatsArrayList.get(2));
}
tv.setText(colindex);
}
/* for(int j=0;j<=seatsArrayList.size();j++)
{
if(seatsArrayList.get(j)=="Seat4")
{
theBtn[3].setEnabled(false);
}
}*/
You are not supposed to iterate in your cursor like that you have just made your cursor to move to the first part (0th). To iterate in a cursor its easy with a for loop like this:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// all operations should be here
}
And again even inside the loop the method cursor.getString(int) the int passed is not the index of a cursor but it is a column index. In your table there may be multiple columns the first one is (0th) the second column is (1st). So you should pass column indexes.

Android - populate ListView SQLite, cursor null pointer

I have two tables atm, users and notes. I am trying to retrieve data that belongs to the user. So all data to list must be owned by the original user and shown only to him. I have made my table in Databasehelper.
I have made a new class that controls the notes table. In listNotes() I want to loop through the cursor row and get all data owned by the user. Am I quering it correctly?
// Listing all notes
public Cursor listNotes() {
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
db.close();
return c;
}
I then want to display the cursor data collected in a listview
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
You aren't creating the NOTE_TABLE right.
You miss a space and a comma here
+ COLUMN_DATE + "DATETIME DEFAULT CURRENT_TIMESTAMP"
It has to be
+ COLUMN_DATE + " DATETIME DEFAULT CURRENT_TIMESTAMP,"
There are two issues here:
One is you have missed a comma (after the Timestamp as specified in an earlier answer).
The other error you have is when using a SimpleCursorAdapter, you need to ensure that the Projection string array includes something to index the rows uniquely and this must be an integer column named as "_id". SQLite already has a feature built in for this and provides a column named "_id" for this purpose (however you can have your own integer column which you can rename to _id). To solve this, change your projection string array to something like:
new String[] {"ROW_ID AS _id", help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}
I guess the NullPointerException stems from this (but without the stacktrace I don't know for sure).

How to return all data from one column Android SQL

I have an SQLite Database in my application. It has three columns. being _id, TEXT, and Location. If I want to return all the data from, say, the TEXT column should I use cursor.getColumnIndex(2)? I am obviously new to SQLite. And and all help is appreciated. Thanks everyone!
Yes, friend, you are new.
First off, your database doesn't have three columns, but rather, your table does. Databases have tables, tables of columns (fields) and rows (records).
Secondly, TEXT is not a valid name for a column, as it's a datatype. Let's say you called the three columns id, theText, and location -- then if you selected all three columns to be returned, the second one would be accessible through:
cursor.getString(1); // that's the second column returned
or
cursor.getString(cursor.getColumnIndex( "theText" ) );
However, you can have sqlite do most of the work for you by selecting only the column you're interested in, so then you'd cursor.getString(0) as it's the only column returned.
For more pertinent explanations, please post your code in the question.
simply apply the query of getting all contacts and take an array of string type and then add the required record in that array as shown below
I hope this code help u
in DBHelper getting record of particular column :
public ArrayList<String> getAllCotactsEmail() {
ArrayList<String> arrayList=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
if (res != null)
{
while(res.isAfterLast() == false){
arrayList.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
Log.d("emailssinlisttt",arrayList.toString());
res.moveToNext();
}}
return arrayList;
}
retrieve :
email=mydb.getAllCotactsEmail();
Log.d("emaillllll",email.toString());
You need to query your Database to get your data. This query will return a Cursor with the column you specified in the query.
To make query, you need to call query() method from ContentResolver. To get your ContentResolver, you can use getContentResolver() from a Context like Activity :
getContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
To understand all parameters, see : ContentResolver
In your case, you want only TEXT column so pass a String array with your TEXT column name for projection parameters.
You want all rows so your selection and selectionArgs parameters must be null.
If you don't care about order, pass null for sortOrder (rows will be sort by ID) :
Cursor c = getContentResolver.query(yourUri, new String[]{"TEXT"}, null, null, null)
This query will return a cursor, to extract your values from the cursor, make a loop like :
if(c.moveToFirst()) {
do {
final String text = c.getString(c.getColumnIndex("TEXT"));
} while (c.moveToNext());
}
Hope this will help you :)

Android: Get CallLog History from a certain contact

I query the CallLog.Calls provider in order to retrieve a list of calls from a certain contact, based on the contact's display name. In particular, I use this query:
String selection = CallLog.Calls.CACHED_NAME + "= ?";
String dispName = dataCollector.getDisplayName();
Cursor callCursor =
cr.query(callLogUri, callLogProjection, selection,
new String[] {dispName},CallLog.Calls.DATE + " DESC");
The dataCollector object is used to hold information from queries based on a given contact id.
The problem is that this code only returns one call for the given contact. I can't understand why. Any clues?
int i=0;
while(cursor.moveToNext())
{
Sring id = cursor.getString(cursor.getColumnIndex(CallLog.Calls._ID));
numbersTemp[i]=cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
valuesTemp[i]=cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
i++;
}

Categories

Resources