将ArrayList <objects>从activity传递给fragment

时间:2017-03-20 12:49:08

标签: java android nullpointerexception

我正在尝试将对象的arraylist传递给片段。我试图在我的对象类上实现Parcelable接口,它似乎发送正常但是当我尝试在片段中使用它时,arraylist被设置为NULL,无论如何知道什么是错的?

对象类:

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


}

主要活动:

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

}

片段:

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


}

}

2 个答案:

答案 0 :(得分:0)

如果您有应用程序类可以存储在那里作为对象并在应用程序中的任何位置调用它,有几种方法可以执行此操作。其他方式是通过共享首选项。意图是在活动和片段之间传递数据但我从未使用过意图来传递对象数组。但是您可以使用共享首选项和应用程序类的对象。

答案 1 :(得分:0)

检查这些行

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

当它为NULL时传递arrayList对象。