Send A Cursor To An Activity From A Service
Solution 1:
You don't actually need to use a Bundle
to send anything from the Service
to the Activity
. You can do it like this in the Service
. I am talking strictly about a Service
here and not an IntentService
, as I've not used them before. Using a bound Service
is the same, but just call unbindService()
in your Activity when you're done with it:
private Cursor cursor;
publicvoidinitializeCursor() {
cursor = Cursor();
//Now the cursor is created. Send a broadcast to the activity that it's done.
broadcastManager.sendBroadcast("your.package.CURSOR_FINISHED");
}
and have a getCursor()
method for the Activity
:
public Cursor getCursor() {
returnthis.cursor;
}
And in the BroadcastReceiver
of your Activity
, catch this event:
@OverridepublicvoidonReceive(Context context, Intent intent) {
if(intent.getAction().equals("your.package.CURSOR_FINISHED") {
Cursor cursor = myService.getCursor();
unbindService(myServiceConnection);
}
}
As your activity is bound to your service, you will have a service object avaiable in your activity. Once you get the broadcast that the cursor is done, just kill the service.
Solution 2:
I opt for made my own custom class which implements a Parcelable Interface. since the parcelable cursors like CrossProcessCursor is quite unknown for me.
Inside of my own ParcelableRow i just implement HashMap object. To don't worry anymore about amount of rows or columns, I just map the cursor to my own ParcelableRow object. here is mi code:
publicclassParcelableRowimplementsParcelable {
privateHashMap<String, String> colsMap;
publicstatic final Parcelable.Creator<ParcelableRow> CREATOR
= newParcelable.Creator<ParcelableRow>() {
@OverridepublicParcelableRowcreateFromParcel(Parcel source) {
returnnewParcelableRow(source);
}
@OverridepublicParcelableRow[] newArray(int size) {
returnnewParcelableRow[size];
}
};
publicParcelableRow(Parcelin) {
colsMap = newHashMap<String, String>();
readFromParcel(in);
}
publicParcelableRow() {
colsMap = newHashMap<String, String>();
}
@Overridepublic int describeContents() {
return0;
}
@OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
for(Stringkey: colsMap.keySet()){
dest.writeString(key);
dest.writeString(colsMap.get(key));
}
}
publicvoidreadFromParcel(Parcel parcel) {
int limit = parcel.dataSize();
parcel.setDataPosition(0);
for(int i = 0; i < limit; i++){
colsMap.put(parcel.readString(), parcel.readString());
}
}
publicvoidaddNewCol(String colName, String colValue){
colsMap.put(colName, colValue);
}
publicStringgetColumnValue(String colName){
return colsMap.get(colName);
}
} Thanks to @CommonsWare to gave me a clue. thumbs up!.
I hope this can be useful to someone, i've just spend some days trying to find something that could satisfy my needs. here are some code examples which i've used. advises are welcome.
Warning It only satisfy me because i'm against the time.
keep coding!
Post a Comment for "Send A Cursor To An Activity From A Service"