Check ArrayList包含任何数据

时间:2013-07-05 06:57:31

标签: java android android-fragments

我已经3 ScreenSlidePageFragment objects。我通过解析json文件来显示我的数据。这是我的主要活动代码:

public class ScheduleMainActivity extends FragmentActivity {
    /*
     * Parsing JSON to get the array length
     */
    private void getLength() {
        try {
            BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
                    .getResources().openRawResource(R.raw.program)));
            StringBuilder jsonBuilder = new StringBuilder();
            for (String line = null; (line = jsonReader.readLine()) != null;) {
                jsonBuilder.append(line).append("\n");
            }
            JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
            JSONArray jsonArray = new JSONArray(tokener);
            totalPages = jsonArray.length();
            for(int counter = 0 ; counter < NUM_PAGES ; counter ++){
               JSONObject jsonObject = jsonArray.getJSONObject(counter);
                   String getDate = jsonObject.getString("date");
                   ScheduleItem.dateWay.add(getDate);
    }



        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static int totalPages; //value = 3

    /**/

    /**
     * The pager widget, which handles animation and allows swiping horizontally
     * to access previous and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            super.onBackPressed();
        } else {
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_slide);
        getLength();
        mPager = (ViewPager)findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                supportInvalidateOptionsMenu();
            }
        });
    }

    /**
     * A simple pager adapter that represents ScreenSlidePageFragment objects,
     * in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            //Log.e("#MA", position + "");
            return ScheduleSlideFragment.create(position, mPager);
        }

        @Override
        public int getCount() {
            return totalPages;
        }
    }

}

现在,我想检查数据date中是否包含先前的ArrayList。所以,我试过这个

 if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){

            jsonParseData(getPageNumber);
        }

它抛出IndexOutOfBoundsException: Invalid index 0, size is 0

这是我的ScheduleSlideFragment代码

public class ScheduleSlideFragment extends Fragment {

    final static String ARG_PAGE = "page";

    private static ViewPager pager;

    private static int pageNumber;

    final static int totalPages = ScheduleMainActivity.totalPages;

    //@SuppressWarnings("unchecked")
    //public List<ScheduleItem>[] data = (ArrayList<ScheduleItem>[])new ArrayList[totalPages];

    public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();

    public int getPageNumber;

    private void jsonParseData(int _getPageNumber) {
        try {
            BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
                    .getResources().openRawResource(R.raw.program)));
            StringBuilder jsonBuilder = new StringBuilder();
            for (String line = null; (line = jsonReader.readLine()) != null;) {
                jsonBuilder.append(line).append("\n");
            }

            // Parse Json
            JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
            JSONArray jsonArray = new JSONArray(tokener);
            _getPageNumber = getPageNumber;
            JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
            String getDate = jsonObject.getString("date");
            JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));

            for (int i = 0; i < getFirstArray.length(); i++) {

                JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
                String time = getJSonObj.getString("time");
                //Log.e("Time Log",time);
                String type = getJSonObj.getString("type");
                String title = getJSonObj.getString("title");
                int typeId = getJSonObj.getInt("type_id");

                data.add(new ScheduleItem(time, title, typeId, getDate));

                /*
                 * Get Events
                 */
                if (typeId == 0) {

                    JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));

                    for (int j = 0; j < getEventsArray.length(); j++) {

                        JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
                        int typeEventId = getJSonEventobj.getInt("type_id");

                        if (typeEventId == 1) {

                            String EventInfo = getJSonEventobj.getString("info");
                            String EventType = getJSonEventobj.getString("type");
                            String EventTitle = getJSonEventobj.getString("title");
                            String Eventtime = getJSonEventobj.getString("time");
                            data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
                                    typeEventId, getDate));
                        } else {

                            String EventType = getJSonEventobj.getString("type");
                            String EventTitle = getJSonEventobj.getString("title");
                            String Eventtime = getJSonEventobj.getString("time");
                            data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
                                    getDate));
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.getStackTraceString(e);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
        getPageNumber = pageNumber;
        /** 
         * JSON Parsing 
         */
        if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){

            jsonParseData(getPageNumber);
        }
        /**
         * Set header date 
         */
        ((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
        final ListView list = (ListView)rootView.findViewById(R.id.list);
        BinderData bindingData = new BinderData(this.getActivity(), data);
        list.setAdapter(bindingData);

        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                if (data.get(position).getItemType() == 0
                        || data.get(position).getItemType() == 3
                        || data.get(position).getItemType() == 2)
                    return;
                Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
                        ContentExtended.class);
                intent.putExtra("title", data.get(position).getTitle());
                intent.putExtra("content", data.get(position).getContent());
                startActivity(intent);
            }
        });

        ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
        if (pageNumber == 0)
            ibLeft.setVisibility(View.INVISIBLE);

        else
            ibLeft.setVisibility(View.VISIBLE);

        ibLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pager.getCurrentItem() > 0)
                    pager.setCurrentItem(pager.getCurrentItem() - 1, true);
            }
        });

        ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
        if (pageNumber + 1 == totalPages)
            ibRight.setVisibility(View.INVISIBLE);
        else
            ibRight.setVisibility(View.VISIBLE);

        ibRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pager.getCurrentItem() < totalPages)
                    pager.setCurrentItem(pager.getCurrentItem() + 1, true);
            }
        });

        return rootView;
    }

    public static Fragment create(int position) {
        Fragment fragment = new ScheduleSlideFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, position);
        fragment.setArguments(args);
        return fragment;
    }

    public static Fragment create(int position, ViewPager _pager) {
        pageNumber = position;
        pager = _pager;
        Fragment fragment = new ScheduleSlideFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageNumber = getArguments().getInt(ARG_PAGE);
    }

}

我的主要问题是:

数据数组包含每个位置一天/页的所有数据。在当前的实现中(没有If条件),每当有人打开说第3页时,第3页的所有数据都被加载,转换并存储在位置2的数据中。如果我们使用这样的数据数组,则不应重新创建所有的数据。时间。所以,我想使用if condition检查数据是否可用。

我的问题是:

1)有什么方法可以检查data ArrayList是否包含任何数据?

2)如何解决IndexOutOfBoundsException问题?

3 个答案:

答案 0 :(得分:2)

  

1)检查数据ArrayList的方法有哪些替代方法   包含任何数据??

要检查ArrayList是否包含任何数据,请使用isEmpty()方法,如下所示:

ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
if (!data.isEmpty()) { //data is not empty, meaning there is data....
  

2)如何解决IndexOutOfBoundsException问题?

当您尝试使索引位置超出范围时,会抛出

IndexOutOfBoundsException

超出范围的时间是[0, size() - 1],其中size()ArrayList()的大小。

要简单地检查一下你是否超出界限,做一些这样的事情......

if ( i < 0 || i >= size()) { // Don't get item from an ArrayList, it's out of bounds

在你的情况下:

if ( _getPageNumber >=0 &&  _getPageNumber < data.size()) { //Get item from jsonArray...

我希望这会有所帮助。

答案 1 :(得分:0)

回答你的问题

1)您可以检查数据是否包含if (data != null && data.size() > 0)

的数据

2)您可以通过验证IndexOutOfBoundsException

来避免if (getPageNumber > 0 && getPageNumber < data.size())

答案 2 :(得分:0)

我认为寻找通用Java API的第一个地方是Apache Commons。对于您的特定情况(检查集合是否为空) - 请参阅http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/CollectionUtils.html#isEmpty%28java.util.Collection%29