gpt4 book ai didi

java - 检查 ArrayList 是否包含任何数据

转载 作者:行者123 更新时间:2023-12-02 06:55:10 25 4
gpt4 key购买 nike

我有 3 个 ScreenSlidePageFragment 对象。我通过解析 json 文件来显示我的数据。这是我的主要 Activity 代码:

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

}

现在,我想检查数据ArrayList中是否包含任何先前的日期。所以,我尝试了这个

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

jsonParseData(getPageNumber);
}

并且它抛出IndexOutOfBoundsException:无效索引0,大小为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 条件),每当有人打开第三页时,第三页的所有数据都会被加载、转换并存储在位置 2 的数据中。如果我们使用这样的数据数组,则不应重新创建各个条目。时间。因此,我想使用 if 条件 来检查数据是否可用。

我的问题是:

1) 检查 data ArrayList 是否包含任何数据的替代方法是什么?

2)如何解决IndexOutOfBoundsException问题?

最佳答案

1) What are the alternatives way to way to check if data ArrayList contains any data??

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

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

2)How can I solve the the IndexOutOfBoundsException problem?

当您尝试获取超出范围的索引位置中的项目时,会引发

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...

我希望这会有所帮助。

关于java - 检查 ArrayList 是否包含任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17482858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com