Java – Send an ArrayList from an Activity to a Fragment?

Send an ArrayList from an Activity to a Fragment?… here is a solution to the problem.

Send an ArrayList from an Activity to a Fragment?

I’m new to Android and I’m trying to send some data from the database to a fragment using bundles and parcelable to display recyclerview and layouttab. Using dummy data, I can display recyclerview in 2 tabs. But when I try to use the data in the database fetched from the activity, I have some trouble sending the fragmented data.

I tried a lot of solutions with similarities in my post. But until this point I couldn’t quite find the right solution.

This is my MainActivity .java

public class MainActivity extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private static final String URL = "http://myweb.com/api/getID.php?id=1";
private String[] ar_id, ar_stat;
private int arr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
    viewPager = (ViewPager) findViewById(R.id.viewpager_id);
    adapter = new ViewPagerAdapter(getSupportFragmentManager());

Add Fragment
    adapter. AddFragment(new FragmentActive(), "Active");
    adapter. AddFragment(new FragmentHistory(), "History");

viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

getDataOrder();

}

private void getDataOrder(){
    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray list = response.getJSONArray("result");
                ArrayList<Active> arrayList = new ArrayList<Active>();
                arr = list.length();
                ar_id = new String[arr];
                ar_stat = new String[arr];
                for (int i = 0; i < arr; i++) {
                    JSONObject data = list.getJSONObject(i);
                    ar_id[i] = data.getString("id");
                    ar_stat[i] = data.getString("status");
                    arrayList.add(new Active(ar_id[i], ar_stat[i]));
                }

Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("ac_array", arrayList);
                bundle.putString("test", "123");
                FragmentActive fragmentActive = new FragmentActive();
                fragmentActive.setArguments(bundle);
            } catch (JSONException e) {

}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Fetching ERROR", "ERROR");
        }
    }
    );
    Volley.newRequestQueue(this).add(jsonObjectRequest);
}

In addition, this is the object class, Active .java

public class Active implements Parcelable {
private String status;

public Active(){

}

public Active(Parcel in){
    super();
    readFromParcel(in);
}

public Active(String id, String status) {
    this.id = id;
    this.status = status;
}

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

public Active[] newArray(int size) {

return new Active[size];
    }

};

public void readFromParcel(Parcel in){
    id = in.readString();
    status = in.readString();
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(id);
    dest.writeString(status);
}

public String getId() {
    return id;
}

public String getStatus() {
    return status;
}

public void setId(String id) {
    this.id = id;
}

public void setStatus(String status) {
    this.status = status;
}

This is the fragment class, .java FragmentActive

public class FragmentActive extends Fragment {

View v;
private RecyclerView myrecyclerview;
private ArrayList<Active> lstActive;
private ArrayList<Active> getArray;

public FragmentActive() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ArrayList<Active> activeArrayList = new ArrayList<Active>();
    if (getArguments()!=null) {
        activeArrayList = getArguments().getParcelableArrayList("ac_array");
        String test = getArguments().getString("test");
        Log.d("List", test);
    }else{
        Log.d("List", "Null?");
    }
    v = inflater.inflate(R.layout.active_fragment, container, false);
    myrecyclerview = (RecyclerView) v.findViewById(R.id.active_recyclerview);
    RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), ***activeArrayList***);
    myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
    myrecyclerview.setAdapter(recyclerAdapter);
    return v;
}

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

Dummy Data
    lstActive = new ArrayList<>();
    lstActive.add(new Active("1", "1"));
    lstActive.add(new Active("2", "0"));
    lstActive.add(new Active("3", "1"));
}

When I run the application, there is no error at all, just no recyclerview is displayed, but when I change the activeArrayList on FragmentActive.onCreateView, to the virtual ArrayList, the dummy data is displayed.

Then, I tried to print the data obtained from the database, and it shows. But when I try to print the arrayList from MainActivity, this is what I get from running debug text

D/Debug List: [com.xxx.xxx.app.Active@79e903c,
com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a]

I/System.out: [com.xxx.xxx.app.Active@79e903c,
com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a]

Are they 3 rows in the database? Because the database I selected shows 3 rows. What should I do to get, send, and display data?

Solution

D/debug list: [com.xxx.xxx.app.Active@79e903c, com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a] This is your activeArrayList.
The value inside is the object in the list.
You should probably make a custom Recycler View adapter.
You are using a list of string arrays.
So, make a recyclerviewadapter and make it in a way that you can display the data you need.

Related Problems and Solutions