Check ArrayList contains any data - java

I've 3 ScreenSlidePageFragment objects. I'm showing my data by parsing a json file. Here is my main activity code :
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;
}
}
}
Now, I want to check if any previous date contains in data ArrayList. So, I tried this
if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){
jsonParseData(getPageNumber);
}
And It throws IndexOutOfBoundsException: Invalid index 0, size is 0.
Here is my ScheduleSlideFragment code
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);
}
}
My main problem is :
The data array contains all the data for one day/page at each position. In the current implementation(Without If condition), whenever someone opens say page three all data for page three is loaded, converted and stored in data at position 2.If we use such a data array the individual entries should not be recreated all of the time. So, I want to use a if condition to check data is available.
My Question is :
1) What are the alternatives way to way to check if data ArrayList contains any data??
2)How can I solve the the IndexOutOfBoundsException problem?

1) What are the alternatives way to way to check if data ArrayList
contains any data??
To check if an ArrayList contains any data, use the isEmpty() method, like so:
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 is thrown when you try to get an item in an indexed position that is out of range.
Out of range is when between [0, size() - 1] where size() is the size of the ArrayList().
To simply check if you're out of bounds, do something of this effect...
if ( i < 0 || i >= size()) { // Don't get item from an ArrayList, it's out of bounds
In your case:
if ( _getPageNumber >=0 && _getPageNumber < data.size()) { //Get item from jsonArray...
I hope this helps.

Answering your questions
1) You can check if data has any data with if (data != null && data.size() > 0)
2) You can avoid IndexOutOfBoundsException by validating that if (getPageNumber > 0 && getPageNumber < data.size())

I think first place to look for general purpose java APIs is Apache Commons. For your particular case (check if a collection is not empty) - see http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/CollectionUtils.html#isEmpty%28java.util.Collection%29.

Related

How to Delete Item Without Deleting Position in Recycler View?

I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}

Cannot set value to textview in runonuithread

public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.

How to make dynamic API calls depending on user preferences?

I am using theMovieDb.com API to fetch data.On launching the app it shows grid view of popular movies. In setting menu, it has option to sort the grid view on the basis of more popular and highest rated. I am using shared preferences to store user preferences and a listener on preference change.But unable to sort the grid view.
MainActivityFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view_movies);
final ImageAdapter mAdapter= new ImageAdapter(getActivity(),listMovie);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie movieSelected= listMovie.get(position);
String movieTitle=movieSelected.getTitle();
String movieThumbnail=movieSelected.getUrlThumbnail();
String movieReleaseDate=movieSelected.getReleaseDate();
String movieOverview=movieSelected.getOverview();
String movieRating = movieSelected.getRating();
Intent i = new Intent( getActivity() ,DetailsMovies.class);
i.putExtra(EXTRA_MESSAGE_1, movieThumbnail);
i.putExtra(EXTRA_MESSAGE_2, movieTitle);
i.putExtra(EXTRA_MESSAGE_3, movieReleaseDate);
i.putExtra(EXTRA_MESSAGE_4, movieRating);
i.putExtra(EXTRA_MESSAGE_5, movieOverview);
startActivity(i);
}
});
return rootView;
}
private void sendJsonRequest() {
//In the case of theMovieDB it is JSON Object Request
//Specify several argument in JSON Object Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJsonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private void parseJsonResponse(JSONObject response) {
if (response == null || response.length() == 0) {
return;
}
long id = -1;
String title = Constants.NA;
String releaseDate = Constants.NA;
String synopsis = Constants.NA;
String urlThumbnail = Constants.NA;
String rating = Constants.NA;
try {
if (response.has(KEY_RESULTS)) {
JSONArray jsonArray = response.getJSONArray(KEY_RESULTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentMovies = jsonArray.getJSONObject(i);
//Get the id of the current movie
//If statement is used to check whether id is null or not.
if (currentMovies.has(KEY_ID) && !currentMovies.isNull(KEY_ID)) {
id = currentMovies.getLong(KEY_ID);
}
//Get the synopsis of the current movie
if (currentMovies.has(KEY_OVERVIEW) && !currentMovies.isNull(KEY_OVERVIEW)) {
synopsis = currentMovies.getString(KEY_OVERVIEW);
}
//Get the title of the current movie
if (currentMovies.has(KEY_TITLE) && !currentMovies.isNull(KEY_TITLE)) {
title = currentMovies.getString(KEY_TITLE);
}
//Get the urlThumbnail of the current movie
if (currentMovies.has(KEY_POSTER_PATH) && !currentMovies.isNull(KEY_POSTER_PATH)) {
urlThumbnail = currentMovies.getString(KEY_POSTER_PATH);
}
//Get the release date of the current movie
if (currentMovies.has(KEY_RELEASE_DATE) && !currentMovies.isNull(KEY_RELEASE_DATE)) {
releaseDate = currentMovies.getString(KEY_RELEASE_DATE);
}
//Get the rating of current movie
if (currentMovies.has(KEY_VOTE_AVERAGE) && !currentMovies.isNull(KEY_VOTE_AVERAGE)) {
rating = currentMovies.getString(KEY_VOTE_AVERAGE);
}
//Create movie object
movie=new Movie();
movie.setId(id);
movie.setTitle(title);
movie.setUrlThumbnail("http://image.tmdb.org/t/p/w185/" + urlThumbnail);
movie.setReleaseDate(releaseDate);
movie.setOverview(synopsis);
movie.setRating(rating);
//This decides when to add movies to the ArrayList
if (id != -1 && !title.equals(Constants.NA)) {
listMovie.add(movie);
}
}
}
} catch (JSONException e) {
Log.e("error", e.getMessage());
}
}
public String getRequestUrl() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String order = pref.getString(getString(R.string.pref_order_key), getString(R.string.pref_popularity));
if(order.equals(getString(R.string.pref_rating)))
return URL + "vote_average" + UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
else
return URL+ "popularity"+UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
}
//Base Adapter which is used to put poster in grid view
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Movie> movieItems;
public ImageAdapter(Context c, ArrayList<Movie> movieList) {
this.mContext = c;
this.movieItems = movieList;
}
public int getCount() {
return movieItems.size();
}
public Object getItem(int position) {
return movieItems.get(position);
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item_movies, null);
}
mNetworkImageView = (NetworkImageView) convertView.findViewById
(R.id.networkImageView);
//Getting movie data for the row
Movie m = movieItems.get(position);
//Thumbnail Image
//ImageLoader is used to load the images from json object retrieved.
imageLoader=VolleySingleton.getInstance().getImageLoader();
mNetworkImageView.setImageUrl(m.getUrlThumbnail(), imageLoader);
return convertView;
}
}
}
SettingsActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// Added preferences from XML
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
// Added preferences
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}

Search Bar filter listview items [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm wanting to put a search bar to act as a filter for the data displayed in the listview.I could not find any examples that do something like that.
If someone can show me how I can do this or demonstrate an example I am very grateful.
public class ListFragment extends Fragment {
//the GridView
GridView lv;
Bitmap bitmap;
//The list that contains the menuitems (sort)
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
View btnLoadMore;
Spinner spinner;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
//The list that contains the wallappers
ArrayList<Wallpaper> productsList;
//The adapter of the WallPaperList
WallPaperAdapter adapter;
private final String baseurl = AppConstant.BASE_URL;
String list_url;
// url to get all products list
private String url_all_products = baseurl + "get_all_products.php";
private String get_tag_products = baseurl + "get_tag_products.php";
// Flag for current page
int current_page = 0;
int max_pages;
// Prevent loading more items to the GridView twice
boolean isLoading;
//
String sort_order;
String tag;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PAGE = "page";
private static final String TAG_ORDER = "order";
private static final String TAG_TAG = "tag";
private static final String TAG_THUMBURL = "url";
private static final String TAG_TOTAL_PAGE = "total_page";
// products JSONArray
JSONArray products = null;
// listener for sort order
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Log.v("Selected: ", Integer.toString(position));
if (position == 0){
sort_order = "latest";
} else if (position == 1){
sort_order = "popular";
} else if (position == 2){
sort_order = "oldest";
} else if (position == 3){
sort_order = "alphabet";
}
//"resetting the GridView"
productsList.clear();
if (adapter != null){
adapter.clear();
}
current_page = 0;
isLoading = false;
//TODO footerview is not visible
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
new InitialLoadGridView().execute();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), ImageGridActivity.class);
startActivity(intent);
}
//}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_listfragment, null);
lv = (GridView)view.findViewById(R.id.listView);
setRetainInstance(true);
setHasOptionsMenu(true);
return view;
}
*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.pesquisa, menu);
super.onCreateOptionsMenu(menu,inflater);
//Pega o Componente.
SearchView mSearchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
//Define um texto de ajuda:
mSearchView.setQueryHint("teste");
// exemplos de utilização:
return;
}*
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actions = getActivity().getActionBar();
actions.setDisplayShowTitleEnabled(false);
// Adapter
SpinnerAdapter spinadapter =
ArrayAdapter.createFromResource(getActivity(), R.array.actions,
//android.R.layout.simple_spinner_dropdown_item);
R.layout.actionbar_spinner_item);
Spinner navigationSpinner = new Spinner(getActivity());
navigationSpinner.setAdapter(spinadapter);
// Here you set navigation listener
navigationSpinner.setOnItemSelectedListener(itemSelectedListener);
actions.setCustomView(navigationSpinner);
if (getActivity().getActionBar().getCustomView().getVisibility() == View.INVISIBLE){
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
}
actions.setDisplayShowCustomEnabled(true);
//ListFragment is created, so let's clear the imageloader cache
ImageLoader.getInstance().clearMemoryCache();
// Arraylist for GridView
productsList = new ArrayList<Wallpaper>();
//initialize the footer so it can be used
btnLoadMore = View.inflate(getActivity(), R.layout.footerview, null);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) getActivity().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
//TODO Implement and replace old
lv.setOnScrollListener(new OnScrollListener(){
int currentVisibleItemCount;
int currentScrollState;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentVisibleItemCount = visibleItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
} else {
Log.v("INFO", "Not loading more items because everything is already showing");
}
}
}
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
String pid = productsList.get(position).getPid();
boolean singlepane = MainActivity.getPane();
if(singlepane== true){
/*
* The second fragment not yet loaded.
* Load DetailFragment by FragmentTransaction, and pass
* data from current fragment to second fragment via bundle.
*/
DetailFragment detailFragment = new DetailFragment();
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
Bundle bundle = new Bundle();
bundle.putString("TAG_PID",pid);
detailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(
R.anim.fadein, R.anim.fadeout, R.anim.fadein, R.anim.fadeout);
//This could use some improvement, but it works, hide current fragment, show new one
fragmentTransaction.hide(myListFragment);
fragmentTransaction.add(R.id.phone_container, detailFragment);
//fragmentTransaction.show(myDetailFragment);
/*
* Add this transaction to the back stack.
* This means that the transaction will be remembered after it is
* committed, and will reverse its operation when later popped off
* the stack.
*/
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class loadMoreGridView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
protected Void doInBackground(Void... unused) {
// increment current page
current_page += +1;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PAGE, Integer.toString(current_page)));
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
if (tag != null){
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
//OUTDATED - Listview seems to automatically keep up with the position
//get GridView current position - used to maintain scroll position
//int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter.notifyDataSetChanged();
//OUTDATED - Setting new scroll position
//lv.setSelectionFromTop(currentPosition + 1, 0);
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
isLoading = false;
}
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class InitialLoadGridView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
getActivity());
pDialog.setMessage(getResources().getString(R.string.wait));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
try { tag = getActivity().getIntent().getExtras().getString("TAG"); } catch (Exception e){}
if (tag != null){
list_url = get_tag_products;
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
max_pages = json.getInt(TAG_TOTAL_PAGE);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
// Getting adapter
adapter = new WallPaperAdapter(
getActivity(), productsList);
lv.setAdapter(adapter);
current_page = 0;
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
lv.post(new Runnable() {
public void run() {
//check if last item is visible, in that case, load some more items
if (lv.getLastVisiblePosition() == lv.getAdapter().getCount() -1 &&
lv.getChildAt(lv.getChildCount() - 1).getBottom() <= lv.getHeight() )
{
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
Log.v("INFO", "Last Item Visible and more available so loading more");
} else {
Log.v("INFO", "Already showing max pages");
}
}
} else {
Log.v("INFO", "Last Item Not Visible, not loading more");
}
}
});
}
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
if (myListFragment != null && myListFragment.isVisible()) {
//VISIBLE! =)
Log.d("STATE", "Just became visible!");
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
getActivity().getActionBar().setDisplayShowTitleEnabled(false);
}
}
public static int convertDpToPixels(float dp, Context context){
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
resources.getDisplayMetrics()
);
}
public interface MyFragInterface {
public void needsHide();
}
public static boolean isInVisible(GridView scrollView, View view, Rect region, boolean relative)
{
int top = scrollView.getScrollY() + region.top;
int bottom = scrollView.getScrollY() + region.bottom;
if(!relative)
{
// If given region is not relative to scrollView
// i.e 0,0 does not point to first child left and top
top -= scrollView.getTop();
bottom -= scrollView.getTop();
}
Rect rect = new Rect(region);
rect.top = top;
rect.bottom = bottom;
Rect childRegion = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
return Rect.intersects(childRegion, region);
}
}
Using AutoCompleteTextView for search bar is the simplest way for me, following is a sample code,hope that will help.
Layout Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<AutoCompleteTextView
android:id="#+id/search_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:lines="1"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/search_text"
android:background="#color/white"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<ListView
android:id="#+id/countries_list"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
Fragment:
public static class PlaceholderFragment extends Fragment implements AdapterView.OnItemClickListener {
AutoCompleteTextView searchTextview;
ListView capitalList;
ArrayAdapter searchTextviewAdapter;
private View rootView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
getActivity().setTitle(" Letsgomo");
searchTextview= (AutoCompleteTextView) rootView.findViewById(R.id.search_text);
capitalList= (ListView) rootView.findViewById(R.id.countries_list);
searchTextviewAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,Constants.capitals);
searchTextview.setAdapter(searchTextviewAdapter);
ArrayAdapter capitalAdapter= (ArrayAdapter) searchTextview.getAdapter();
capitalList.setAdapter(capitalAdapter);
capitalList.setOnItemClickListener(this);
return rootView;
}
}

Java : Recommended way to check a certain data already exists in the ArrayList

I have jsonParse method inside a onCreateView. I have 3 pages in my application. Every time, when I
open a page data created all of the time and I want to check therefore whether there is already something at the current position. Now, my question is what are recommended way to check a certain data already exists in the ArrayList.
Here is my code :
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
public static int pageNumber;
public static int PAGE_NUM = ScheduleMainActivity.NUM_PAGES ;
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");
// data.add(new ScheduleItem(getDate));
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));
Log.e("Check Size", String.valueOf(data.size()));
/*
* 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));
}
}
}
}
//Log.e("Check Date", String.valueOf(data.get(_getPageNumber).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
*/
checker = getPageNumber + 1;
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 == PAGE_NUM)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < PAGE_NUM)
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 the objects inside the ArrayList has the equal methods properly overridden and defined you can use the contains method.
Whenever you need to check if your List contains something, you should use Set instead of List. HashSet for example.

Categories

Resources