简体   繁体   English

传递ArrayList <Objects> 从活动到碎片

[英]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? 我试图在我的对象类上实现Parcelable接口,它似乎发送得很好,但是当我尝试在片段中使用它时,arraylist设置为NULL,无论如何都知道怎么回事?

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. 当它为NULL时,您正在传递arrayList对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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