Navigation Draw Submenu Array Error - android

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++)

Related

How to clear elements from SimpleAdapter?

I am trying to fill the listview on a SET button.As i select the values spinner and according to list will fill. Problem i am facing is at many times i click on SET button it will add items to listview .
setButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
for (int i = 0; i < DeviceID.size(); i++)
{
//initialize row data
for (int j = 0; j < 5; j++) {
if (j == 0)
str = DATE.get(i);
else if (j == 1)
str = TIME.get(i);
else if (j == 2)
str = DeviceID.get(i);
else if (j == 3)
str = SMSTEXT.get(i);
map.put(columnTags[j], str);
}
mylistData.add(map);
}
final String[] columnTags = new String[]{"one", "two", "three", "four", "five", "six", "lat", "log"};
final int[] columnIds = new int[]{R.id.textView5, R.id.textView8, R.id.textView9,R.id.checkbox, R.id.textView10};
arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.location_locator_textview, columnTags, columnIds);
listview.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
});
It looks like your list mylistData is a global variable. So, the old items are still in the list.
Either make it local inside the onClick method, or clear it in the first line of the onClick method. (Also the same case for map)
public void onClick(View view){
mylistData.clear();
map.clear();
//your code
}
You can call listview.setAdapter(null); before you set your items into listview
Try to modify the list of an element in your adapter and then call notifyDataSetChanged().
It would be easier if you post the code

ListView Pagination with NEXT and PREVIOUS buttons

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.

How to delete multiple selected line items from a listview?

I have implemented a simple method to delete multiple items from a listview following this solution Removing muliple items from listview using Check box in Android, then modified it a small bit to allow for a switch statement for the two button click events, add & delete.But the problem is when I click the delete button the app crashes giving me these errors: http://pastebin.com/2NmCQk2B
I'm not sure why I'm getting the null pointer exception as I believe I have assigned everything correctly.
Can someone better explain why I could be getting this error? Or perhaps a better way of deleting selected line items from a listview?
The complete class is posted below for better understanding:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd,mDel;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
SparseBooleanArray mCheckStates ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mDel = (Button)rootView.findViewById(R.id.delBtn);
mAdd.setOnClickListener(this);
mDel.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
public void onClick(View v)
{
switch(v.getId()){
case R.id.newList:
//DO something
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
break;
case R.id.delBtn:
//DO something
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
list.remove(i);
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
}
}
You need to use valueAt(), the working code should be
SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = mListView.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
Remove from adapter instead from listview try following:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
if(checked!=null){
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
adapter.remove(mListView.getItemAtPosition(i));
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
getCheckedItemPositions Returns:
A SparseBooleanArray which will return true for each call to get(int position) where position is a checked position in the list and false otherwise, or null if the choice mode is set to CHOICE_MODE_NONE.
I used loop this way, and it worked:
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();

Swapping two rows in ArrayAdapter

I've created a ListView that in each row has a button with UP and DOWN arrow. Pressing these buttons makes the row to be shifted one position up or down.
I've achieved it by implementing OnClickListener for both buttons in a the override method getView. It works as it should however I fill bad with that cuz it seems to be highly memory consuming and lots of code is doubled.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = inflater.inflate(R.layout.row_layout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
CheckBox checkBox = (CheckBox) rowView.findViewById(R.id.checkbox);
checkBoxes.add(position, checkBox);
String address = this.getItem(position).getAddress();
String tokenizedAddress = tokenizeAddress(address);
textView.setText(tokenizedAddress);
ImageButton buttonUp = (ImageButton)rowView.findViewById(R.id.button_up);
ImageButton buttonDown = (ImageButton)rowView.findViewById(R.id.button_down);
buttonUp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ListAdapter adapter = ListAdapter.this;
if(position != 0 ){
GameTask current = adapter.getItem(position);
ArrayList<GameTask> list = new ArrayList<GameTask>();
for( int i = 0; i < adapter.getCount(); i++ )
list.add(adapter.getItem(i));
list.remove(position);
list.add(position-1, current);
adapter.clear();
for( int i = 0; i < list.size(); i++ ){
adapter.add(list.get(i));
}
adapter.notifyDataSetChanged();
}
}
});
buttonDown.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ListAdapter adapter = ListAdapter.this;
if(position != adapter.getCount()-1 ){
GameTask current = adapter.getItem(position);
ArrayList<GameTask> list = new ArrayList<GameTask>();
for( int i = 0; i < adapter.getCount(); i++ )
list.add(adapter.getItem(i));
list.remove(position);
list.add(position+1, current);
adapter.clear();
for( int i = 0; i < list.size(); i++ ){
adapter.add(list.get(i));
}
adapter.notifyDataSetChanged();
}
}
});
return rowView;
}
Both listeners do almost the same, the only difference is the condition and the value of shifting +1/-1. I was wondering about creating the inner class implementing OnClickListener in the extended ArrayAdapter class however, I have no idea, how I could then pass the position of the row clicked to this inner class.
Instead of adding and removing elements from your ArrayList, you can better implement Collections.swap(List list, int firstElementIndex, int secondElementIndex) it would be much easier as you don't have to iterate through the whole Collection. A simple example for the same can be found here.
You could make a method that would be used by both buttonUp and buttonDown. This method could take as a parameter the type of action that was pressed (UP/DOWN), and the position of item in ListView, and then call this method in both of your click listener passing the appropriate action.
Example:
// 2 new constants
private static final int UP = 0;
private static final int DOWN = 1;
// Based on "type", increment or decrement the position.
private void changeRow(int type, int position){
if(type==UP){
position=position-1;
}else if(type==DOWN){
position=position+1;
}
// ........
// Then in your "for" cicle you specify:
list.add(position, current);
// ........
}
Then in the onClick() method of buttonUp you specify:
changeRow(UP, position);
and for buttonDown:
changeRow(DOWN, position);
This can be easily achieved
The way to do this is to store the data to be displayed in an List
Then when the user clicks the up or down arrow
Swap the references of data items which are shifting position using Collections.swap(List, int, int)
Then call notifyDataSetChanged on the adapter

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