0

The core of this question is how to send a MatrixCursor of data from an activity to a fragment.

I am doing my search functionality in my activity and am returning a fragment which contains a list that will be filled with data from the query response that is a Matrix Cursor.

Bundle and parcelable thus far are not working out for me. Any tips or guidance?

NVA
  • 1,662
  • 5
  • 17
  • 24

2 Answers2

0

I see three potential options.

  1. Try Gson. You may be able to convert the instance to a String to pass it and then reinstantiate it from the String data. However, this doesn't work for everything.

  2. Create a new method in your Fragment. You're not meant to pass custom arguments in the constructor, but you could pass it later:

    private MatrixCursor cursor;
    
    public void setCursor(MatrixCursor cursor) {
        this.cursor = cursor;
    }
    

    Since it's the same instance, changes made to the one in your Fragment will be reflected in your Activity. However, this will cause issues if you rotate your device or cause another configuration change. To fix that, add the following to your <activity> attribute in your Manifest:

    android:configChanges="orientation|keyboardHidden"
    
  3. Fragments retain a reference to their parent Activity. You could add helper methods to your Activity that essentially proxy the ones you need from your MatrixCursor instance:

    public void addRow(Object[] columnValues) {
        cursor.addrow(columnValues);
    }
    
    //etc
    

    Then, in your Fragment, you can do:

    ((MyActivityClass) getActivity()).addRow(columnValues);
    

Option 3 would probably be the best option, since it doesn't rely on something that might not work or what's basically a hack.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63
0

Make a interface Searchable

public interface Searchable {
     MatrixCursor getSearchResult() 
}

make sure you implement this interface to your activity.

public MainActivity extends AppCompatActivity implements Searchable {

    private MatrixCursor mSearchResultMatrixCursor;
    ...
    @Override public MatrixCursor getSearchResult() {
         return mSearchResultMatrixCursor;
    }    
}

In you Fragment's onCreate or wherever you want to use MatrixCursor,

you can call,

if(getActivity != null && getActivity instanceOf Searchable) {
         MatrixCursor matrixCursor = ((Searchable)getActivity).getSearchResult()
}

This will persist as long as activity is not recreated.

Rahul
  • 4,699
  • 5
  • 26
  • 38