Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Parcelable in fragment for getting data?

I can use Parcelable in Activity but I don't know how to use it in Fragment.

I have a ListFragment in FragmentGet to display all rows database in ListView, I want to get details of ListView in another Fragment when it's clicked, I use Parcelable to passing data between Fragments.

This is my Test.java:

import android.os.Parcel;
import android.os.Parcelable;

public class Test implements Parcelable {

    private int studentNumber;
    private String studentName;
    private String studentFamily;

    public int getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(int studentNumber) {
        this.studentNumber = studentNumber;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentFamily() {
        return studentFamily;
    }

    public void setStudentFamily(String studentFamily) {
        this.studentFamily = studentFamily;
    }

    public Test() {
    }

    public Test(Parcel read) {
        studentNumber = read.readInt();
        studentName = read.readString();
        studentFamily = read.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel write, int flags) {
        write.writeInt(studentNumber);
        write.writeString(studentName);
        write.writeString(studentFamily);
    }

    public static final Parcelable.Creator<Test> CREATOR =
            new Parcelable.Creator<Test>() {
                @Override
                public Test createFromParcel(Parcel source) {
                    return new TestP(source);
                }
                @Override
                public Test[] newArray(int size) {
                    return new TestP[size];
                }
            };
}

In FragmentSend.java I want to send data to FragmentGet.java, this is the code:

public class FragmentSend extends ListFragment {

    //    Classes
    TestReadData readData;
    TestDataSource dataSource;

    private List<Test> listTest;       

    public FragmentSend() {
        // Required empty public constructor
    }


    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_send, container, false);

        readData = new TestReadData(getContext());
        dataSource = new TestDataSource(getContext());  

       refreshStudentList(inflater);

    return layout;
}

public void refreshStudentList(LayoutInflater inflater) {

    listTest = readData.getAllStudentRows();
    ArrayAdapter<Test> testAdapter = new TestFragmentListAdapter(inflater.getContext(), listTest);
    setListAdapter(testAdapter);

}

    @Override
    public void onResume() {
        super.onResume();
        dataSource.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        dataSource.close();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Test model = listTest.get(position);

        // this three line code is for Activity not Fragment!
        Intent intent = new Intent(getContext(), FragmentGet.class);
        intent.putExtra("Student", model);
       // startActivity(intent);

        // I use this code for fragment
        Fragment fragmentGet = new FragmentGet();
    fragmentGet.setArguments(intent.getExtras());
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_container, fragmentGet);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

    }

In the FragmentGet.java I get data like this:

public class FragmentGet extends Fragment {

    //    Classes
    Test model;    

    //    Variables
    private List<Test> listTest;

    public FragmentGet () {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View layout = inflater.inflate(R.layout.fragment_get, container, false);

        //        Classes Associated
        model = new Test(Parcel.obtain());

        Bundle bundle = getActivity().getIntent().getExtras();
        model = bundle.getParcelable("Student");

        return layout;    
    }

When I run the app, I will get this error:

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

how can I fix this error?

like image 461
Salar Rastari Avatar asked Nov 11 '15 07:11

Salar Rastari


People also ask

How do you use Parcelable?

Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

How do I use Parcelable intent?

Suppose you have a class Foo implements Parcelable properly, to put it into Intent in an Activity: Intent intent = new Intent(getBaseContext(), NextActivity. class); Foo foo = new Foo(); intent. putExtra("foo ", foo); startActivity(intent);

How do we pass values between fragments?

To actually pass the data between fragments, we need to create a ViewModel object with an activity scope of both the fragments, initialize the ViewModel , and set the value of the LiveData object.

What is Parcelable data?

Parcelable is a serialization mechanism provided by Android to pass complex data from one activity to another activity.In order to write an object to a Parcel, that object should implement the interface “Parcelable“.


1 Answers

Passing data to Fragments is carried by using Bundles but not Intents.

In FragmentSend change

Intent intent = new Intent(getContext(), FragmentGet.class);
intent.putExtra("Student", model);

Fragment fragmentGet = new FragmentGet();
fragmentGet.setArguments(intent.getExtras());

to this

Fragment fragmentGet = new FragmentGet();
Bundle bundle = new Bundle();
bundle.putParcelable("Student", model);
fragmentGet.setArguments(bundle);

And to receive the data in FragmentGet change

Bundle bundle = getActivity().getIntent().getExtras();
model = bundle.getParcelable("Student");

to

Bundle bundle = this.getArguments();
if (bundle != null) {
    model = bundle.getParcelable("Student");
}
like image 196
DmitryArc Avatar answered Oct 25 '22 12:10

DmitryArc