ListView Pagination with NEXT and PREVIOUS buttons - android

I have a listview which loads 200 items using webservice. Where all 200 items are displaying in single listview.
I want to load first 1-20 items first and when i click NEXT button i need to load 21-40 items and so on. And vice-verse, when i click PREVIOUS button i need to load 1-20 items.
How to implement Pagination for this?
I tried :
static ArrayList<String> Code = new ArrayList<String>();
//Code is ArrayList where i get 200 items from Service
int rowSize = 20;
// rowSize is number of items i want per page
static ArrayList<String> TempCode = new ArrayList<String>();
//TempCode is temporary ArrayList where iam trying to store items per page
Button NextButton;
NextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int size = Code.size() / rowSize;
for (int j = 0; j < size; j++) {
final int k;
k = j;
addItem(k);
}
}
});
public void addItem(int count) {
TempCode.clear();
count = count * rowSize;
/**
* fill temp array list to set on page change
*/
for (int j = 0; j < rowSize; j++) {
TempCode.add(j, Code.get(count));
count = count + 1;
}
Adapter adapter=new Adapter(getApplicationContext(),TempCode);
listView.setAdapter(adapter);
}
Please help.
Thanks in advance.

int _currentPage = 1;
public int FeedCountPerPage = 20;
//Call the below code in one function on click of your next button
//And do the reverse on click of previous button
_currentPage += 1;
try {
int _feedCount = _currentPage * FeedCountPerPage;
if (_feedCount <= arrPhotoData.size()) {
tmpList = arrPhotoData.subList(_feedCount - FeedCountPerPage, _feedCount);
adderList.addAll(arrPhotoData.subList(0, FeedCountPerPage));
adderList.addAll(tmpList);
}
} catch (Exception e) {
e.printStackTrace();
}
if (adderList == null || adderList.size() == 0)
adapter = new InstagramListAdapter(_myActivity, arrPhotoData);
else
adapter = new InstagramListAdapter(_myActivity, adderList);
I have posted this answer as a context of my project. I hope you'll have some understanding from this.

Related

Recycler view with multiple layout items duplicate radio buttons on scroll

RecyclerView containing multiple layouts such as one row containing Edittext, radioButtons another row containing checkbox etc
Now when I input in first edit text and scroll the list then same inputed value gets copied in the last edit text visible on the screen.
Also if there are two radio buttons visible say radio1 and radio 2 then on scroll this becomes
radio1
radio2
radio1
radio2
i.e. radio1 and radio 2 are duplicated on scroll.
Can any one suggest some solution for the same?
Code for dynamic Edit Text
private void configureViewHolderText(final ViewHolderText holderText, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
String hint = questionsArrayList.get(position).getHelperText();
int characterLength = questionsArrayList.get(position).getCharLimit();
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderText.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
holderText.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
if (characterLength > 0) {
holderText.getEt_dynamic_edit_text().setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterLength)});
}
if (hint != null && hint.equals("null") == false && hint.equals("") == false) {
holderText.getEt_dynamic_edit_text().setHint(hint);
} else {
holderText.getEt_dynamic_edit_text().setHint("Enter Answer");
}
holderText.getEt_dynamic_edit_text().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editTextInput = holderText.getEt_dynamic_edit_text().getText().toString();
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// hashAnswerInput.put(questionsArrayList.get(position).get_id(), editTextInput);
/*hashQuestionText.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getQuestionText()) ;
hashQuestionId.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).get_id()) ;
hashAnswerType.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getAnswerType());*/
/* for(Map.Entry map : hashAnswerInput.entrySet() )
{
dynamicEditTextAnswer = String.valueOf(map.getValue());
//answers.setAnswerText(inputAnswer);
}*/
/*if(dynamicEditTextAnswer!= null)
{*/
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(editTextInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
/* }*/
/*for(Map.Entry map : hashQuestionText.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionText(inputAnswer);
}
for(Map.Entry map : hashQuestionId.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionId(inputAnswer);
}
for(Map.Entry map : hashAnswerType.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setAnswerType(inputAnswer);
}*/
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
// answers.setQuestionId(questionsArrayList.get(position).get_id());
// answers.setAnswerText(editTextInput);
// answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Code for dynamic radio button
private void configureViewHolderRadioGroup(final ViewHolderRadioGroup holderRadioGroup, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
ArrayList<String> radioOptionsList = new ArrayList<String>();
for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {
String radioItemName = questionsArrayList.get(position).getOptions().get(j).getOptionText();
radioOptionsList.add(radioItemName);
}
holderRadioGroup.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderRadioGroup.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
int totalCount = questionsArrayList.get(position).getOptions().size();
final RadioButton[] rb = new RadioButton[totalCount];
for (int i = 0; i < totalCount; i++) {
rb[i] = new RadioButton(context);
rb[i].setText(radioOptionsList.get(i));
rb[i].setId(i);
holderRadioGroup.getRg_dynamic_radio_group().addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
holderRadioGroup.getRg_dynamic_radio_group().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton rg = (RadioButton) group.getChildAt(i);
if (rg.getId() == checkedId) {
radioInput = rg.getText().toString();
Toast.makeText(context, radioInput, Toast.LENGTH_SHORT).show();
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(radioInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
getRadioChildQuestions(relatedQuestionsId, holderRadioGroup, k);
}
}
return;
}
else if(rg.getId() != checkedId) {
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
/*for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {*/
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
}
}
}
}
}
});
}
}
}
The recycler view reuses your view holders instances.
So if you are scrolling and a layout is leaving the screen at the top, it gets reused, when the same layout should be used for a new item at the bottom.
You need to reset all dynamic attribues in the onBindViewHolder-method.
For a better understanding set two debug points inside your recycler view adapter:
One inside the onCreateViewHolder-method and one inside the onBindViewHolder-method.
EDIT:
A sample for a working Recycler View Adapter can be found here: https://github.com/olLenz/Movies-with-Kotlin/blob/master/base/src/main/java/com/lenz/oliver/movieswithkotlin/ui/home/HomeAdapter.kt
The onCreateViewHolder-method creates a new instance of the ViewHolder.
The onBindViewHolder-method just calls the bind-method on a created ViewHolder instance. This bind-method sets all dynamic information to the given layout on every call.

Navigation Draw Submenu Array Error

I'm trying to add an item from array to navigation draw submenu. But i could not it. My code ise here
> private void addItemsRunTime(NavigationView navigationView) {
//adding items run time
final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 3; i++) {
menu.add("Runtime item "+ i);
}
//stringArray[0]="Selam";
//stringArray[1]="Merhaba";
//stringArray[2]="Merhaba";
//stringArray[3]="Merhaba";
// adding a section and items into it
final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
for (int i = 0; i <= sayaca; i++) {
subMenu.add("SubMenu Item " + i);
}
// refreshing navigation drawer adapter
for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
final View child = mNavigationView.getChildAt(i);
if (child != null && child instanceof ListView) {
final ListView menuView = (ListView) child;
final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
wrapped.notifyDataSetChanged();
}
}
}
when i change my code like this "for (int i = 0; i <= myArray.length; i++)" it gives me and error.and my application is closed. Message is here.
Array is working other function. But in this now working.
thanks for your help.
it throws exception to your myarray.length try to saving it in a variable then use the variable.
You are doing wrong thing , you must loopthrough from 0 to n-1 values and then your error will be solved because last element of array is always at (n-1)th location , so just make change like ,
for (int i = 0; i <= myArray.length-1; i++)

selected check boxes count and passing it to another activity

i have 4 check boxes in 1st activity and i wanna store only those user selected check boxes and have to show in another activity my question is how can i count the user selected checkboxes. please help with me logic
int x = 0;
public void onCheckboxClicked(View view) {
checked = ((CheckBox) view).isChecked();
if (((CheckBox) view).isChecked() == true) {
int i = 0;
while (i != 4) {
x = i + 1;
i++;
}
}
}
On Submit Button
if(x!=0) {
show alert();
and passing check boxes selected count
}
You can run a loop and find the number of CheckBox views and then accordingly get the count of checked CheckBoxes
Ex:
main = (LinearLayout) findViewById(R.id.main);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
count = 0;
int childcount = main.getChildCount();
for (int i=0; i < childcount; i++){
View view = main.getChildAt(i);
if (view instanceof CheckBox) {
if(((CheckBox) view).isChecked())
count++;
}
}
text.setText("count: " + count);
}
});
First put checkboxes in an array:
ArrayList<CheckBox> checkList = new ArrayList<CheckBox>();
you can do it with:
for(int i=0 ; i<4; i++)
{
checkList.add(YOURCHECKBOX) ;
}
than you can check which CB are checked (implement where you want it to save only those which are checked..) with:
for(int i=0 ; i<checkList.size(); i++)
{
if(checkList.get(i).isChecked() == true)
{
YOURCODE
}
}

listView count numbers of selected rows

I am trying to find out the total number of selected rows in a customized list-view. If the number of items (rows) more than 2 then we cannot click the list-view again.Here I am using customized checklist(Multiple Choice)
What's wrong with listView.getCheckedItemCount()?
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
int len = lvMain.getCount();
SparseBooleanArray checked = lvMain.getCheckedItemPositions();
for (int i = 1; i < len; i++){
if (checked.get(i)) {
count++;
/* do whatever you want with the checked item */
}
}
if(count>2)
{
/* do whatever you want with the checked item count more than one x value*/
lvMain.setSelected(false);
count=1;
}
}
});
Else, you could try to store your checkboxes and the other element displayed in a row (I've used TextView in my example) in a HashMap when overridden getView method get called and then count how many elements are checked iterating over the Map :
Iterator<Entry<TextView, CheckBox>> it = listCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Entry<TextView, CheckBox> entry = it.next();
if (entry.getValue().isChecked())
i++;
}
return i;
I think you are trying to count the total number of selected rows in multiple listView.
for(i=0; listCount; i++) {
if(mListView.isItemChecked(i)){
}
else {
}
}

get all checked item of listview on check of checkbox without using POJO class [duplicate]

I've a couple of question I haven't been able to figure out.
I'm trying to get all the checked elements from a ListView but:
If I check and then uncheck an element, it's returned as "checked" by the getCheckedItemPositions() function
I don't know how can I iterate through this:
SparseBooleanArray checked = list.getCheckedItemPositions();
The other answers using SparseBooleanArray are nearly correct, but they are missing one important thing: SparseBooleanArray.size() will sometimes only return the count of true values. A correct implementation that iterates over all the items of the list is:
SparseBooleanArray checked = list.getCheckedItemPositions();
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (checked.get(i)) {
// Do something
}
}
I solved my case with this:
public class MyAdapter extends BaseAdapter{
public HashMap<String,String> checked = new HashMap<String,String>();
....
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))){
checked.remove(String.valueOf(item));
}
else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems(){
return checked;
}
}
To set an element is checked:
public class FileBrowser extends Activity implements OnClickListener{
private ListView list;
...
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int item,
long id) {
BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
bla.setCheckedItem(item);
}
});
Then to get the checked items from outside the class..
MyAdapter bAdapter;
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
for (int i=0;i<bAdapter.getCheckedItems().size();i++){
//Do whatever
bAdapter.getItem(Integer.parseInt(it.next());
}
Hope it can help someone.
Jarett's answer is great, but this should be a bit faster, since it's only checking the elements in the sparse array that are present in the underlying array (only those can be true):
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
final int checkedItemCount = checkedItemPositions.size();
for (int i = 0; i < checkedItemCount; i++) {
int key = checkedItemPositions.keyAt(i);
if (checkedItemPositions.get(key)) {
doSomething(key);
} else {
// item was in the sparse array, but not checked.
}
}
Pro tip: look at the source of SparseBooleanArray, it's a pretty simple class:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/util/SparseBooleanArray.java/?v=source
My brain didn't like looping through the SparseBooleanArray and I didn't need a custom adapter, so the following was a little more intuitive for me:
Don't forget to use CHOICE_MODE_MULTIPLE in onCreate():
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Use the following method to get an ArrayList of them:
// This example is to get an ArrayList of names (Strings)
protected ArrayList<String> getNames() {
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < getListView().getCount(); i++) {
if (getListView().isItemChecked(i)) {
// Do whatever you need to in here to get data from
// the item at index i in the ListView
names.add(mUsers.get(i).getName());
}
}
return names;
}
You can iterate through the SparseBooleanArray using a for loop and the SparseBooleanArray's size() and get(index) methods.
EDIT 3/2/2014: People have pointed out that SparseBooleanArray's size() method returns the number of checked values, rather than the true length of the array, so I have mended my answer to account for that. Essentially it is the same, except that rather than iterating for the length of the array, we iterate until we have found all checked items. Since we only care about the number of checked items, it's irrelevant that with this method, we may not actually get to the end of the array (we won't see anything past the last checked item).
SparseBooleanArray checked = list.getCheckedItemPositions();
int numChecked = checked.size();
for (int i = 0; numChecked > 0; i++){
if (checked.get(i)){
//the item at index i is checked, do something
numChecked--; //We found a checked item, so decrement the number of checked items remaining
}
else
//the item is not checked, do something else
}
final long[] checkedIds = lv.getCheckItemIds();
for (int i = 0; i < checkedIds.length; i++) {
Log.d("checkedIds", "id checked: " + checkedIds[i]);
}
Just saw the question and I was facing the same problem.
There is a simpler solution using SparseBooleanArray to exactly count how many items are checked.
This is my onClick procedure:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
SparseBooleanArray a = listView.getCheckedItemPositions();
if(checked(vArray)>0) {
String vCheckedList = "";
for (int i = 0; i < nLength; i++) {
if (a.valueAt(i) && i < nLength-1 && a.size()>1)
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i))+"\n";
else if (a.valueAt(i))
vCheckedList += listView.getAdapter().getItem(vArray.keyAt(i));
}
Toast.makeText(getApplicationContext(), vCheckedList+ " is checked", Toast.LENGTH_SHORT).show();
a.clear();
} else
Toast.makeText(getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
The checked method:
private int checked(SparseBooleanArray vArray) {
int vCounter = 0;
for(int i=0;i<vArray.size(); i++)
if(vArray.valueAt(i))
vCounter++;
return vCounter;
}
It will solve both problem of the checked items.
I had the same problem and here is my solution with SparseBooleanArray :
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();
int size = checkedPositions.size ();
for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));
}
In it's entirety this is the solution I used.
Where pos is the Recyclerview item position
SparseBooleanArray selected = new SparseBooleanArray();
//OnClick listener here or whatever you use to check or uncheck an item
if (selected.get(pos, false)) {
selected.delete(pos);
} else {
selected.put(pos, true);
}
selected.size() will reveal how many items are selected
selected.get(pos) will return true if it's selected
The following as has been stated, iterates over all those items which were selected:
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (selected.get(pos)) {
// Do stuff
}
}
Here is how I get checked items from recyclerview adapter
fun getAllCheckedItems(outList){
for (position in spareBooleanArray.keyIterator()) {
outList.add(mList.get(position)
}
}

Categories

Resources