I am using a contextual action bar and wish to retrieve each value selected to pass to another activity after I click on the 'mail' button. How can I do this?e
Code for the CAB.
mAdapter = new SelectionAdapter(this, R.layout.activity_result, R.id.name, new String[] {TAG_NAME, TAG_ROOM_PRICE});
setListAdapter(mAdapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.email:
}
return false;
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle("No: of resorts selected: " + nr);
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return true;
}
});
Selection adapter class which is used to define the object mAdapter
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
}
return v;
}
}
I wish to retrieve the String value of every selection that I make
I found the solution.
mAdapter.setNewSelection(position, checked);
String get_list = resortsList.get(position).get(TAG_NAME);
stringList.add(get_list);
And to remove the item selected when deselected:`int i;
for(i = 0 ; i < stringList.size(); i++){
if(stringList.get(i).equals(resortsList.get(position).get(TAG_NAME))){
stringList.remove(i);
Log.d("String List: ", stringList.toString());
break;
}
}`
Related
I've got a Lsitview populated with CheckedTextViews. My goal is to be able to delete multiple rows at onece, if possible with MultiChoiceModeListener.
To use it, I have to set the ListView CHOICE_MODE_MULTIPLE_MODAL.
The frist problem is now: I cant just chek the checkboxes now, because the listview isnt ChOICE_MODE_MULTIPLE anymore.
I hade the idear to set it CHOICE MODE MULTIPLE and just set an OnItemClickListenerfor the ListView, but then the ChoiceModeMultiple and its Method onItemStateChaed Method always gets called, even if i just wanna check a checkbox in my App.
Any solutions on how to fix that?
The Code (layout is the ListVIew) :
layout.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int i, long l, boolean b) {
if (!list_items.contains(list.get(i))) {
count++;
list_items.add(list.get(i));
actionMode.setTitle(count + " items selected");
} else if (list_items.contains(list.get(i))) {
count--;
list_items.remove(list.get(i));
actionMode.setTitle(count + " items selected");
}
}
}
Try this example, please refer this and solve
public class MainActivity extends AppCompatActivity {
ListView list;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> arrayList = new ArrayList<>();
ArrayList<String> arrayList2 = new ArrayList<>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listItems);
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");
arrayList.add("four");
arrayList.add("five");
arrayAdapter = new ArrayAdapter<String>(this,R.layout.list_layout,R.id.textView,arrayList);
list.setAdapter(arrayAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position, long l, boolean b) {
count = count+1;
actionMode.setTitle(count + " items selected");
arrayList2.add(arrayList.get(position));
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.list_menu,menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete_id:
for(String msg : arrayList2) {
arrayAdapter.remove(msg);
}
Toast.makeText(getApplicationContext(),"deleted",Toast.LENGTH_SHORT).show();
count=0;
actionMode.finish();
return true;
default:
Toast.makeText(getApplicationContext(),"Nothing selected",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapterView.setSelected(true);
}
});
}
}
I want to display items in list view with four attributes: id, name, marks, and date. Its working fine but when I scroll the listview and select the 1st item, it also selects the 16th item and sometimes the app crashes. I searched a lot but can't understand what's the problem.
//Adapter class
public class Adapter extends ArrayAdapter<Item> {
private Activity activity;
int id;
ArrayList<Item> items;
public Adapter(Activity context, int resource, ArrayList<Item> objects) {
super(context, resource, objects);
this.activity=context;
this.id=resource;
this.items=objects;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(id, null);
}
Item item = items.get(position);
TextView tv_id = (TextView) convertView.findViewById(R.id.tv_id);
TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
TextView tv_marks = (TextView) convertView.findViewById(R.id.tv_marks);
TextView tv_date = (TextView) convertView.findViewById(R.id.tv_date);
tv_id.setText(item.getId());
tv_name.setText(item.getName());
tv_marks.setText(item.getMarks());
tv_date.setText(item.getDat());
return convertView;
}
//item class-----------
public class Item {
private String id;
private String name;
private String surname;
private String marks;
private String dat;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
public String getDat() {
return dat;
}
public void setDat(String dat) {
this.dat = dat;
}
}
// List view Class
public class List_Viwer extends AppCompatActivity {
Context ctx = this;
ListView listView;
Adapter adapter;
CheckBox checkBox;
DatabaseHelper myDb = new DatabaseHelper(this);
ArrayList<Item> arrayList=new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list__viwer);
//checkBox.setVisibility(View.GONE);
Cursor cursor = myDb.getAllData();
if(cursor!= null) {
if (cursor.moveToFirst()){
do{
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
arrayList.add(item);
}while (cursor.moveToNext());
}
adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView temp_txt = (TextView) view.findViewById(R.id.tv_id);
String tempID = temp_txt.getText().toString();
// Toast.makeText(ctx, ID, Toast.LENGTH_LONG).show();
Intent i = new Intent(ctx, View_Person.class);
i.putExtra("ID", tempID);
ctx.startActivity(i);
}
});
//-----------------Long Clikced Listener Starts from here-----------------------------
listView.setAdapter(adapter);
listView.setChoiceMode(listView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
ArrayList<String> list_ids = new ArrayList<String>();
int count = 0;
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
String data = adapter.getItem(position).getId();
Toast.makeText(ctx, data, Toast.LENGTH_SHORT).show();
if (list_ids.contains(data)) {
for (int i = 0; i < list_ids.size(); i++) {
// String temp = list_ids.get(i);
if (data == list_ids.get(i)) {
count--;
mode.setTitle(count + " Items Selected");
list_ids.remove(i);
listView.getChildAt(position).setBackgroundResource(R.drawable.bg1);
}
}
}
else {
// listView.getChildAt(pos).setBackgroundColor(Color.YELLOW);
count++;
mode.setTitle(count + " Items Selected");
listView.getChildAt(position).setBackgroundResource(R.drawable.bg2);
list_ids.add(data);
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflator = mode.getMenuInflater();
inflator.inflate(R.menu.menu_delete, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.action_delete:
for (int i=0; i<list_ids.size(); i++)
{
String temp = list_ids.get(i);
myDb.deleteData(temp);
}
Toast.makeText(ctx, count+" Items Deleted.", Toast.LENGTH_SHORT).show();
mode.finish();
count = 0;
list_ids.clear();
arrayList.clear();
refreshdata(); //gets data from method and Sets to list View item
//listView.clearChoices();
//adapter.notifyDataSetChanged();
//break;
default:
return false;
//break;
}
//return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkBox", "false");
editor.apply();
count = 0;
list_ids.clear();
arrayList.clear();
refreshdata();
// listView.clearChoices();
listView.setBackgroundColor(Color.TRANSPARENT);
// listView.clearChoices();
// listView.setBackgroundColor(Color.TRANSPARENT);
}
}); //-----------Lon clik listener ends---------------------------------
} //-------------On Create bundel method ends------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// adapter.getFilter().filter(newText);
// getPlanets(newText);
arrayList.clear(); // MUST CLEAR THE PREVIOUS DATA FROM LIST
Cursor cursor = myDb.SearchData(newText);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
// item.setCheckBox();
arrayList.add(item);
} while (cursor.moveToNext());
}
listView.setAdapter(adapter);
}
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
public void refreshdata(){
final Cursor cursor = myDb.getAllData();
if(cursor!= null) {
if (cursor.moveToFirst()){
do{
Item item = new Item();
item.setId(cursor.getString(0));
item.setName(cursor.getString(1));// gets id fromm database
item.setSurname(cursor.getString(2)); //gets title from database
item.setMarks(cursor.getString(3));
item.setDat(cursor.getString(4));// gets content / body from database
arrayList.add(item);
}while (cursor.moveToNext());
}
adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
}
/// my log cat
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: FATAL EXCEPTION: main
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: java.lang.NullPointerException
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: at com.hexa.adnan.mysqllitedemo.List_Viwer$2.onItemCheckedStateChanged(List_Viwer.java:101)
12-10 03:48:51.453 6587-6587/com.hexa.adnan.mysqllitedemo E/AndroidRuntime: at android.widget.AbsListView$MultiChoiceModeWrapper.onItemCheckedStateChanged(AbsListView.java:6077)
I am creating an android app in which the user can capture the images and these images are displayed in gridview.when the user wants to delete one or more images by touching the images i am getting an java index out of bounds exception.The example which i have seen has used the image adapter extending to a arrayadapter but i am using an image adapter which extends to base adapter. So i don't know because of it does the error occurs.
grid.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = grid.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
adapter.toggleSelection(position);
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.delete_mode, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
int selecteditem = (int) adapter
.getItem(selected.keyAt(i));
//Remove selected items following the ids
String imgPath = listOfImagesPath.get(selecteditem);
File file=new File(imgPath);
file.delete();
adapter.removeitem(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
adapter.removeSelection();
}
});
Image adapter(which i have created):
public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
private SparseBooleanArray mSelectedItemsIds;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
mSelectedItemsIds = new SparseBooleanArray();
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void removeitem(int position){
imgPic.remove(position);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
Image adapter(the example which i saw for deleting multiple images in grid)
public class ListViewAdapter extends ArrayAdapter<WorldPopulation> {
// Declare Variables
Context context;
LayoutInflater inflater;
List<WorldPopulation> worldpopulationlist;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context, int resourceId,
List<WorldPopulation> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Capture position and set to the ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
return view;
}
#Override
public void remove(WorldPopulation object) {
worldpopulationlist.remove(object);
notifyDataSetChanged();
}
public List<WorldPopulation> getWorldPopulation() {
return worldpopulationlist;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
Error:
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.remove(ArrayList.java:403)
at nidhinkumar.gridcam.Cam$ImageListAdapter.removeitem(Cam.java:360)
at nidhinkumar.gridcam.Cam$4.onActionItemClicked(Cam.java:200)
at android.widget.AbsListView$MultiChoiceModeWrapper.onActionItemClicked(AbsListView.java:6693)
at com.android.internal.policy.impl.PhoneWindow$DecorView$ActionModeCallbackWrapper.onActionItemClicked(PhoneWindow.java:3430)
at android.support.v7.view.SupportActionModeWrapper$CallbackWrapper.onActionItemClicked(SupportActionModeWrapper.java:168)
at android.support.v7.app.AppCompatDelegateImplV7$ActionModeCallbackWrapperV7.onActionItemClicked(AppCompatDelegateImplV7.java:1703)
at android.support.v7.app.AppCompatDelegateImplV7$ActionModeCallbackWrapperV7.onActionItemClicked(AppCompatDelegateImplV7.java:1703)
at android.support.v7.view.StandaloneActionMode.onMenuItemSelected(StandaloneActionMode.java:136)
I'm getting this error only when i try to delete the image after capturing.When i reload the page again and delete the image it works fine.
You might have problem here:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
In this line
SparseBooleanArray selected = adapter
.getSelectedIds();
selected is not an array. so its size will always be one. and you are subtracting 1 from it thus making its size 0. Therefore, it'll always give array index out of bound exception whenever you'll try to access it.
A simple fiz may be this :
SparseBooleanArray[] selected = adapter
.getSelectedIds();
I have a bunch of images from sdcard that are load asynchronously on a gridview. Everything works fine, but when accessing a multi select contextual action menu by long clicking in any image the entire activity reloads and all images are loaded again. How to prevent it?
Myadapter
public class PhotosGridViewImageAdapter extends BaseAdapter {
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
File targetDirector;
PhotosGridViewImageAdapter myTaskAdapter;
public AsyncTaskLoadFiles(PhotosGridViewImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + File.separator + AppConstant.PHOTO_ALBUM + File.separator;
targetDirector = new File(targetPath);
myTaskAdapter.clear();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
ArrayList<String> itemList = new ArrayList<String>();
void add(String path) {
itemList.add(path);
}
void clear() {
itemList.clear();
}
void remove(int index){
itemList.remove(index);
}
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public PhotosGridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
convertView = imageView;
holder = new ViewHolder();
holder.image = imageView;
holder.position = position;
convertView.setTag(holder);
} else {
//imageView = (ImageView) convertView;
holder = (ViewHolder) convertView.getTag();
((ImageView)convertView).setImageBitmap(null);
}
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
// get screen dimensions
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
//imageView.setImageBitmap(image);
return image;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
v.image.setImageBitmap(result);
}
}.execute(holder);
return convertView;
}
/*
* Resizing image size
*/
public Bitmap decodeFile(String filePath, int WIDTH, int HEIGHT) {
try {
File f = new File(filePath);
if(filePath.contains(".jpg")) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HEIGHT = HEIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}else if(filePath.contains(".mp4")){
return ThumbnailUtils.createVideoThumbnail(filePath, 0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
class ViewHolder {
ImageView image;
int position;
}
}
Contextual action menu code
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
I appreciate any help!
==UPDATE==
Here is the MainActivity code:
public class PhotosGridViewActivity extends Activity {
private PhotosUtils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private PhotosGridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initilizing Grid View
InitilizeGridLayout();
}
private void InitilizeGridLayout() {
setContentView(R.layout.photos_grid_view);
utils = new PhotosUtils(PhotosGridViewActivity.this);
gridView = (GridView) findViewById(R.id.grid_view);
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());
// Gridview adapter
adapter = new PhotosGridViewImageAdapter(PhotosGridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
gridView.getItemAtPosition(position);
Intent i = new Intent(PhotosGridViewActivity.this, PhotosScreenViewActivity.class);
i.putExtra("position", position);
PhotosGridViewActivity.this.startActivity(i);
}
});
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(co.glurl.appoid.R.menu.photo_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
/** Go to the user's add photos. */
startActivity(new Intent(this, PhotoIntentActivity.class));
break;
//case R.id.settings:
/** Go to the user's settings photos. */
// startActivity(new Intent(this, PhotoGridSettings.class));
// break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
My soluction. Thanks to #pushbit for guiding me through it.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = new ImageView(_activity);
}
// Trigger the download of the URL asynchronously into the image view.
if(_filePaths.get(position).contains(".jpg")) {
Picasso.with(_activity)
.load(new File(_filePaths.get(position)))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}else if(_filePaths.get(position).contains(".mp4")){
VideoRequestHandler videoRequestHandler;
Picasso picassoInstance;
videoRequestHandler=new VideoRequestHandler();
picassoInstance = new Picasso.Builder(_activity.getApplicationContext())
.addRequestHandler(videoRequestHandler)
.build();
picassoInstance
.load(videoRequestHandler.SCHEME_VIDEO+":"+_filePaths.get(position))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}
return imageView;
}
public static boolean deleteToPhotoAlbum(Integer position) {
File file = new File(_filePaths.get(position));
boolean deleted = file.delete();
return deleted;
}
public class VideoRequestHandler extends RequestHandler {
public String SCHEME_VIDEO = "video";
#Override
public boolean canHandleRequest(Request data)
{
String scheme = data.uri.getScheme();
return (SCHEME_VIDEO.equals(scheme));
}
#Override
public Result load(Request data, int arg1) throws IOException
{
Bitmap bm = ThumbnailUtils.createVideoThumbnail(data.uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND);
return new Result(bm, Picasso.LoadedFrom.DISK);
}
}
I want to delete multiple selected items (row) in my listview (Gmail style).
If I select (with longClick) a row, nothing happens.
I've found this code on internet, and i've tried to insert it in my project.
MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(Lista.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selectedItem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selectedItem);
}
}
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.delete_menu, menu);
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position,
long arg2, boolean arg3) {
final int checkedOut = Lista.getCheckedItemCount();
actionMode.setTitle(checkedOut + " selezionato");
adapter.toggleSelection(position);
}
and this is the adapter
public class ListaAdapter extends ArrayAdapter<ListViewItem> {
private Context context;
private ArrayList<ListViewItem> items;
private SparseBooleanArray mSelectedItemsIds;
public ListaAdapter(Context context, int resourceId,
ArrayList<ListViewItem> items) {
super(context, resourceId, items);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.items = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtSubTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_view_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.TitoloPrincipale);
holder.txtSubTitle = (TextView) convertView
.findViewById(R.id.Sottotitolo);
holder.imageView = (ImageView) convertView.findViewById(R.id.Image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListViewItem list = getItem(position);
holder.txtTitle.setText(list.getNomeFarmaco());
holder.txtSubTitle.setText(list.getFasceOrarie());
holder.imageView.setImageResource(list.getIcon());
// convertView
// .setBackgroundColor(mSelectedItemsIds.get(position)
// : Color.TRANSPARENT);
return convertView;
}
public void remove(ListViewItem item) {
items.remove(item);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
have you got any idea?
tks
That code has nothing to do with long-clicks. The only occurrence of "long" is for a long parameter to a method. :-)
This sample project demonstrates an action mode starting up based upon a long-click of a list row. The key is onItemLongClick():
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemChecked(position, true);
return(true);
}
Here (courtesy of registering the activity as the OnItemLongClickListener for the ListView), we toggle on CHOICE_MODE_MULTIPLE_MODAL and check the item that was long-clicked, thereby activating the action mode.
The major problem you have not setMultiChoiceModeListener for listview like below
(Plz, see carefully onCreateActionMode and the loop in onActionItemClicked)
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
// TODO Auto-generated method stub
switch (menuItem.getItemId()) {
case R.id.mnDelete:
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
items.remove(sparseBooleanArray.keyAt(i));
adapter.notifyDataSetChanged();
mode.finish();
break;
default:
break;
}
return true;
}
});
}
I've solved. thank you all.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selecteditem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.delete_menu, arg1);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2,
boolean arg3) {
final int checkedCount = Lista.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}
}