简体   繁体   中英

Is it possible to send an object from a fragment to another fragment?

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);
        }
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM