【问题标题】:Passing ArrayList<Objects> from activity to fragment将 ArrayList<Objects> 从活动传递到片段
【发布时间】:2017-03-21 00:32:52
【问题描述】:

我正在尝试将对象数组列表传递给片段。我尝试在我的对象类上实现 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);


}

}

【问题讨论】:

  • 您在 setupViewPager() 调用后初始化数组列表,这就是它为空的原因。
  • 顺便说一句,你不需要context = getApplicationContext()...一个Activity已经是一个上下文。而且你不需要runOnUiThread,因为那时你已经在 UI 线程上
  • 我已经编辑了 on create 方法,在 setupViewPager() 之前初始化了数组,但问题仍然存在。我认为由于某种原因它没有加载 JSON 部分,所以数组没有被填充

标签: java android nullpointerexception


【解决方案1】:

如果您有应用程序类,您可以将其存储为一个对象并在应用程序中的任何位置调用它,有几种方法可以做到这一点,其他方法是通过共享首选项。意图是在活动和片段之间传递数据,但我从未使用意图传递对象数组。但是您可以使用共享首选项和应用程序类的对象。

【讨论】:

  • 您可以传递 Parcelables 的 Arraylist... 不需要 SharedPrefences
  • 使用putParcelableArrayList 并不难。与任何其他 putExtra 方法没有什么不同
【解决方案2】:

检查这些行

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

当它为 NULL 时,您正在传递 arrayList 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多