简体   繁体   中英

Passing ArrayList<Objects> from activity to fragment

I am trying to pass an arraylist of objects to a fragment. I tried to implement the Parcelable interface on my object class, it seems to be sending fine but when I try and use it in the fragment the arraylist is set to NULL, anyway know whats wrong?

Object Class:

public class Product implements Parcelable {
private String image;
private String userID;
private String category;
private String locationX;
private String locationY;
private String title;
private String brand;
private String colour;
private String userName;



//

public Product(String image, String userID, String category, String locationX, String locationY, String title, String brand, String colour, String userName) {
    this.image = image;
    this.userID = userID;
    this.category = category;
    this.locationX = locationX;
    this.locationY = locationY;
    this.title = title;
    this.brand = brand;
    this.colour = colour;
    this.userName = userName;

}

protected Product(Parcel in){
    image = in.readString();
    userID = in.readString();
    category = in.readString();
    locationX = in.readString();
    locationY = in.readString();
    title = in.readString();
    brand = in.readString();
    colour = in.readString();
    userName = in.readString();


}

public static final Creator<Product> CREATOR = new Creator<Product>() {
    @Override
    public Product createFromParcel(Parcel in) {
        return new Product(in);
    }

    @Override
    public Product[] newArray(int size) {
        return new Product[size];
    }
};

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(image);
    dest.writeString(userID);
    dest.writeString(category);
    dest.writeString(locationX);
    dest.writeString(locationY);
    dest.writeString(title);
    dest.writeString(brand);
    dest.writeString(colour);
    dest.writeString(userName);


}

Main activity:

public class NewHome extends AppCompatActivity {

private TextView textName, textBio;
private ImageView imageView;
Context context;
public Bundle b;

private ImageView userPic;
//    private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ArrayList<Product> arrayList;
ListView lv;
String name = " ";
String userID = " ";
String category = " ";
String locationX = " ";
String locationY = " ";
String picture= " ";


    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_home);
    FacebookSdk.sdkInitialize(getApplicationContext());
    userPic = (ImageView) findViewById(R.id.userPicture) ;
    arrayList = new ArrayList<>();
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);




    context = getApplicationContext();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            new NewHome.ReadJSON().execute("json url");

        }
    });

    viewPager = (ViewPager) findViewById(R.id.viewpagerHome);
    tabLayout = (TabLayout) findViewById(R.id.tabsHome);
    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);



}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    HomeFirstFragment firstFragment = new HomeFirstFragment();
    HomeSecondFragment secondFragment = new HomeSecondFragment();

    Bundle bundle =new Bundle();
    bundle.putString("name", name);
    bundle.putString("userID", userID);
    bundle.putString("category",category );
    bundle.putString("locationX", locationX);
    bundle.putString("locationY", locationY);
    bundle.putString("picture", picture);
    bundle.putParcelableArrayList("array", arrayList);


    firstFragment.setArguments(bundle);

    adapter.addFragment(firstFragment, "Photo");

    adapter.addFragment(secondFragment, "Likes");

    viewPager.setAdapter(adapter);
}



class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

public class ReadJSON extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }

    @Override
    protected void onPostExecute(String content) {
        try {
            JSONObject jsonObject = new JSONObject(content);
            JSONArray jsonArray =  jsonObject.getJSONArray("photos");
            JSONArray jsonArray1 = jsonObject.getJSONArray("profile");
            for(int i =0;i<jsonArray.length(); i++){
                JSONObject productObject = jsonArray.getJSONObject(i);
                arrayList.add(new Product(
                        productObject.getString("name")+".jpg",
                        productObject.getString("userID"),
                        productObject.getString("category"),
                        productObject.getString("locationX"),
                        productObject.getString("locationY"),
                        productObject.getString("title"),
                        productObject.getString("brand"),
                        productObject.getString("colour"),
                        productObject.getString("username")

                ));

            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
        CustomListAdapter adapter = new CustomListAdapter(
                getApplicationContext(), R.layout.custom_list_layout, arrayList
        );



        //lv.setAdapter(adapter);

    }
}


private static String readURL(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        // create a url object
        URL url = new URL(theUrl);
        // create a urlconnection object
        URLConnection urlConnection = url.openConnection();
        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

}

Fragment :

public class HomeFirstFragment extends Fragment  {
private Bundle b;
ListView lv;
View mView;
ArrayList<Product> arrayList;

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    FacebookSdk.sdkInitialize(getApplicationContext());

    mView = inflater.inflate(R.layout.fragment_home_first, container, false);
    b = this.getArguments();
    arrayList = new ArrayList<>();
    arrayList = b.getParcelableArrayList("array");
    CustomListAdapter adapter = new CustomListAdapter(
            getApplicationContext(), R.layout.custom_list_layout, arrayList
    );

    lv = (ListView) mView.findViewById(R.id.homeList);

    //lv.setAdapter(adapter);
    return mView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstances){
    super.onViewCreated(view, savedInstances);


}

}

There are several ways for doing this if you have application class you can store there as an object and call it wherever you want in application, Other way is via shared preferences. Intents are there to pass data between activities and fragments but I never used an intent to pass array of objects. But you can use shared preferences and object of application class.

Check these lines

   setupViewPager(viewPager);
arrayList = new ArrayList<>();

You are passing arrayList object when it is NULL.

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