Passing a cursor to an activity?

2019-02-15 16:24发布

Is this possible? I am trying to open a SQLite database cursor in one activity, and pass it to another activity.

3条回答
劳资没心,怎么记你
2楼-- · 2019-02-15 16:59

You should write your own Cursor which will implement Parcelable interface. In this case you can put your cursor to parcel and send it to another Activity through putExtra(). In target Activity you can explode (in fact just find it through handler) Cursor through one of Parcel methods (related to Binder).

查看更多
我只想做你的唯一
3楼-- · 2019-02-15 17:17

Another way to do this which might be easier is to create an Application class for your app. This is guaranteed to be created only once, and exists for the lifetime of your app. Among other things, it can provide a "data hub" capability for your app so different Activities can share data easily. So, for your cursor, you'd simply use a member variable of the Application class like so (warning, I copied this code from my app and edited it here, so no guarantee of compilation. Just something to show the idea.):

    package com.jcascio.k03;

    import android.app.Application;
    import android.database.Cursor;

// use your application's name instead of "K03Application"

        public class K03Application extends Application { 

        public final String TAG = "K03";

        Cursor sharedCursor; // this cursor can be shared between different Activities

        @Override
        public void onCreate() {
            super.onCreate();
        }

        @Override
        public void onTerminate() {
            super.onTerminate();
        }


        public Cursor getSharedCursor() 
        {
            return this.sharedCursor;
        }

        public void setSharedCursor(Cursor c)
        {
            this.sharedCursor = c;
        }

    }

The application object can be fetched from any Activity using

    this.getApplication()

// You cast it to your Application sub-class and call the Cursor accessor function

Cursor c = ((K03Application)this.getApplication()).getSharedCursor();

So, your first Activity would fetch some goo from the database, which is returned to it as a Cursor. This activity would call setSharedCursor in the application. Then it would launch the second Activity, which would call getSharedCursor in its onCreate function (or any other function for that matter) to retrieve the cursor.

查看更多
Evening l夕情丶
4楼-- · 2019-02-15 17:23

I personally don't know of any simple ways to do this. It might be easier just to make the query again in the destination activity.

查看更多
登录 后发表回答