0

The object that I want to send from a fragment to another fragment is "post". The DemandFragment consist of a listview which consist of items which are post objects.

I need to send the selected item from the listview, in this case postArrayList.get(position), to SelectedPostFragment.

I've tried with bundle but this is not working...

Does someone know how to fix this?

DemandFragment:

public class DemandFragment extends Fragment {

ListView lv;
ArrayAdapter adapter;
ArrayList<Post> postArrayList;
private EditText editSearch;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_demand, container, false);

    if(rootView != null){
        lv = (ListView) rootView.findViewById(R.id.listDemand);

        editSearch = (EditText) rootView.findViewById(R.id.search_post);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // clicked on item show post
                Post selectedPost = postArrayList.get(position);
                Bundle bundle = new Bundle();
                bundle.putParcelable("data", (Parcelable) selectedPost);
                FragmentManager fm = getActivity().getFragmentManager();
                Fragment fragment = new rang.afterflight.fragments.SelectedPostFragment();
                fragment.setArguments(bundle);
                fm.beginTransaction().replace(R.id.content_main, fragment).commit();
            }
        });
    }
    searchPost();
    return rootView;
}

public void searchPost(){
    editSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");

    postArrayList = new ArrayList<Post>();

    query.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> postList, ParseException e) {
            if (e == null) {
                for (ParseObject object : postList) {
                    Post newPost = new Post();

                    newPost.setAirportParse((String) object.get("airport"));
                    newPost.setDateParse((String) object.get("date"));
                    newPost.setTimeParse((String) object.get("time"));
                    newPost.setPersonsParse((String) object.get("persons"));
                    newPost.setAddressParse((String) object.get("address"));
                    newPost.setFlightnrParse((String) object.get("address"));
                    newPost.setUsername((String) object.get("username"));
                    newPost.setImageFile((ParseFile) object.get("profilepic"));

                    postArrayList.add(newPost);
                }
                adapter = new ListViewAdapter(getActivity(), R.layout.item_cardview, postArrayList);
                lv.setAdapter(adapter);
            }
        }
    });
}

}

SelectedPostFragment:

public class SelectedPostFragment extends Fragment {
TextView airportPost, datePost, timePost, personsPost, addressPost,
        flightnrPost, postedbyPost, contactPost;


ImageView iv;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_selectedpost, container, false);

    airportPost = (TextView) rootView.findViewById(R.id.airport_post);
    datePost = (TextView) rootView.findViewById(R.id.date_post);
    timePost = (TextView) rootView.findViewById(R.id.time_post);
    personsPost = (TextView) rootView.findViewById(R.id.persons_post);
    addressPost = (TextView) rootView.findViewById(R.id.address_post);
    flightnrPost = (TextView) rootView.findViewById(R.id.flightnr_post);
    postedbyPost = (TextView) rootView.findViewById(R.id.postedby_post);
    contactPost = (TextView) rootView.findViewById(R.id.contact_post);

    Post selectedPost = getArguments().getParcelable("object");
    String s = (String) selectedPost.get("airport");
    Log.d("AIRPORT NAME", s);

    return rootView;
}

}

Post:

@ParseClassName("Post")
public class Post extends ParseObject implements Serializable {

    public Post(){
        super();
    }

    public String getId(){
        return getString("objectId");
    }

    public void setId(String id){
        put("objectId", id);
    }

    //////////

    public String getUsername(){
        return getString("username");
    }

    public void setUsername(String username){
        put("username", username);
    }



    public String getAirportParse(){
        return getString("airport");
    }

    public void setAirportParse(String airport){
        put("airport", airport);
    }

    //////////


    public String getDateParse(){
        return getString("date");
    }

    public void setDateParse(String date){
        put("date", date);
    }


    //////////


    public String getTimeParse(){
        return getString("time");
    }

    public void setTimeParse(String time){
        put("time", time);
    }


    //////////


    public String getPersonsParse(){
        return getString("persons");
    }

    public void setPersonsParse(String persons){
        put("persons", persons);
    }


    //////////


    public String getAddressParse(){
        return getString("address");
    }

    public void setAddressParse(String address){
        put("address", address);
    }

    public String getFlightnrParse(){
        return getString("flightnr");
    }

    public void setFlightnrParse(String flightnr){
        put("flightnr", flightnr);
    }


    public Bitmap getImageFile(){
        Bitmap bmp = null;
        ParseFile image = getParseFile("profilepic");
        if(image != null){
            try {
                byte[] data = image.getData();
                bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
            } catch (ParseException e) {
                e.printStackTrace();
                }
        }
        return bmp;
    }

    public void setImageFile(ParseFile file) {
        if (file != null) {
            put("profilepic", file);
        }
    }
}
Andrew Senner
  • 2,479
  • 1
  • 18
  • 24
Rang92
  • 67
  • 9
  • What do you mean by "not working?" Are there any exceptions being thrown? What isn't happening that you feel should be happening, specifically? Can you post your `Post` class? – Andrew Senner Jan 27 '16 at 22:05
  • I posted my Post class.... – Rang92 Jan 27 '16 at 22:12
  • 1
    Possible duplicate of [Passing objects in to Fragments](http://stackoverflow.com/questions/10836525/passing-objects-in-to-fragments) – Amir Jan 27 '16 at 22:57

2 Answers2

1

I believe your Post class needs to implement Parcelable as well to pass it in a bundle between fragments with putParcelable().

Check out: Parcelable.

This is also a great example.

Basic implementation:

public class Post extends ParseObject implements Serializable, Parcelable {
    ...

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(getId());
        out.writeSring(getUsername());
        ...
    }

    public static final Parcelable.Creator<Post> CREATOR
        = new Parcelable.Creator<Post>() {
            public Post createFromParcel(Parcel in) {
                return new Post(in);
            }

            public Post[] newArray(int size) {
                return new Post[size];
            }
    };

    private Post(Parcel in) {
        // Items must be read in the order they were written.
        setId(in.readString());
        setUsername(in.readString());
        ...
    }
}

Try that on for size, hope it helps.

Andrew Senner
  • 2,479
  • 1
  • 18
  • 24
  • Hmm, well, I've passed bundles to fragments successfully using this code. Basically, your object gets broken down into primitive types and saved into a `Parcel`, which acts as a container for the data you need to pass to the next activity/fragment/etc. Afterwards, you can read from that same parcel and rebuild the object you passed in. Parcelable objects require the methods and `CREATOR` class I posted above. Also, please, stop posting "It's not working." That could mean a million different things. Post details and errors/code you think might be the problem. – Andrew Senner Jan 27 '16 at 22:35
  • 1
    There is an Android studio plugin that does this for you. Open up plugins in Android studio and search for Parcelable. – TheSunny Jan 27 '16 at 22:56
  • Thanks @AndrewSenner it works.... but i did not use out.putString but out.writeString , and also not (in.getString()) but (in.readString) Thank you too TheSunny! – Rang92 Jan 28 '16 at 00:18
  • You're correct, I edited my answer. If you feel this has helped you, please mark as correct. Thanks! :-) – Andrew Senner Jan 28 '16 at 00:39
0

Use the activity as a transporting mechanism.

Create an interface for the activity to implement, which the activity passes to the fragment upon instantiation. Whenever you want to transfer data, call the callback for the interface. Co-ordinate with the activity which fragment it needs to interact with and then post your data in another callback that will be linked to the fragment.

If all of this is too complex, then just use Otto and enjoy sending events everywhere without having to worry about detaching/attaching interfaces/listeners upon configuration change.

TheSunny
  • 371
  • 4
  • 14