Delete from database via ViewList MultiSelection - android

I have the next code.
public class ListAnotaciones extends ListActivity {
AnotacionesOpenHelper openHelper = AnotacionesOpenHelper.getAnotaciones(this);
SQLiteDatabase bd;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelper.getReadableDatabase();
cursor = bd.rawQuery("select * from anotaciones", null);
final ArrayList<Cursor> lista = new ArrayList<Cursor>();
try {
String [] from = {"titulo", "fecha"};
int [] to = {R.id.anotacionesTexto, R.id.anotacionesFecha};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.anotacion, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
int seleccion = getListView().getCheckedItemCount();
boolean borrado = false;
if(checked){
lista.add((Cursor)getListView().getItemAtPosition(position));
lista.get(0).moveToFirst();
Toast.makeText(getApplicationContext(),lista.get(0).getString(0),Toast.LENGTH_SHORT).show();
}else{
/*
SQLiteCursor seleccionado = (SQLiteCursor)getListView().getItemAtPosition(position);
for(int i = 0;i < lista.size();i++){
if(lista.get(i).getString(0).equals(seleccionado.getString(0))){
lista.remove(i);
borrado = true;
break;
}
}
*/
}
mode.setTitle(seleccion + " Notas Seleccionadas");
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.ctx_borrar,menu); //Inflamos el menĂº creado como XML en 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.CtxLblBorrar:
/*
for(int i = 0 ; i < lista.size();i++){
Toast.makeText(getApplicationContext(),lista.get(i).getString(0),Toast.LENGTH_SHORT).show();
bd.delete("anotaciones","_id = " + lista.get(i).getString(0),null);
}
*/
while(lista.get(0).moveToNext()){
bd.delete("anotaciones","_id = " + lista.get(0).getString(0),null);
}
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.CtxLblBorrar:
Toast.makeText(getApplicationContext(),"Se ha pulsado Borrar - " + getListView().getCheckedItemCount(),Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"OPCION NO PROGRAMADA",Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ctx_borrar, menu);
}
}
I'm trying to delete from the database and then update the ListView. I've seen several solutions here but I can't adapt the solutions to my code (I'm pretty new with android).
More specifically, I don't know how to "save" the options than I need to delete.
If you need more code please say so.

SOLVED
I'm so sorry, I'm a little blind,
It's the code for my question
public class ListAnotaciones extends ListActivity {
AnotacionesOpenHelper openHelper = AnotacionesOpenHelper.getAnotaciones(this);
SQLiteDatabase bd;
Cursor cursor;
Context contexto = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelper.getWritableDatabase();
cursor = bd.rawQuery("select * from anotaciones", null);
final ArrayList<Long> borrar = new ArrayList<Long>();
try {
String [] from = {"titulo", "fecha", "texto"};
int [] to = {R.id.anotacionesTitulo, R.id.anotacionesFecha,R.id.anotacionesTexto};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.anotacion, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new AbsListView.MultiChoiceModeListener(){
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
Toast.makeText(getApplicationContext(),Long.toString(id),Toast.LENGTH_SHORT).show();
if(checked){
borrar.add(id);
}else{
for(int i = 0; i < borrar.size();i++){
if(borrar.get(i) == id){
borrar.remove(i);
}
}
Toast.makeText(getApplicationContext(),"Deseleccionado",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.ctx_borrar,menu); //Inflamos el menĂº creado como XML en Menu
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.CtxLblBorrar:
Toast.makeText(getApplicationContext(),"Se ha pulsado Borrar",Toast.LENGTH_SHORT).show();
for(int i = 0 ; i < borrar.size();i++){
bd.delete("anotaciones","_id=" + borrar.get(i),null);
}
return true;
default:
return false;
}
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
}
);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
Thanks you anyway for the solves

Related

Get the position of Selected Item in Action Mode

When i long press any item in the list view then Contextual action bar showed. Now what i want that when i press the delete button after selecting items then the selected items get deleted but I am unable to get the position of selected items.
My code for multi choice mode is:
listViewMessages.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listViewMessages.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
mode.setTitle(listViewMessages.getCheckedItemCount()+ " Selected");
}
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
deleteScreenedMessageFromInbox();
mode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
When i click on delete button then this method is calling:
deleteScreenedMessageFromInbox();
and i have to pass an argument in this method which is the position of selected items. Code for this method is:
public void deleteScreenedMessageFromInbox(Integer position) {
Integer id = smsIDs.get(position);
String deleteScreenedMessage = "delete from " + "sms" + " where " + "id" + " = " + id;
DBsms smsDb = new DBsms(this);
SQLiteDatabase dbw = smsDb.getWritableDatabase();
dbw.execSQL(deleteScreenedMessage);
dbw.close();
any solutions for this?
Here is what I would suggest:
List<Integer> positionsList = new ArrayList<>();//declare this as a member variable--outside of any method
listViewMessages.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listViewMessages.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
mode.setTitle(listViewMessages.getCheckedItemCount()+ " Selected");
if(checked)
positionsList.add(position)
else
positionsList.remove(position)
}
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu:
deleteScreenedMessageFromInbox();
mode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
Then on your deleteScreenedMessageFromInbox() access positionsList like so:
public void deleteScreenedMessageFromInbox() {
DBsms smsDb = new DBsms(this);
SQLiteDatabase dbw = smsDb.getWritableDatabase();
for(int position : positionsList) {
Integer id = smsIDs.get(position);
String deleteScreenedMessage = "delete from " + "sms" + " where " + "id" + " = " + id;
dbw.execSQL(deleteScreenedMessage);
}
dbw.close();
}
implement the onitemclickListener and get the item id and save it in any variable and delete the item whenever user click on delete and next call adapter.notifyDataSetChanged();
for example
listViewMessages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
//you can pass position from here to your method like this
deleteScreenedMessageFromInbox(position)
String value = (String) adapter.getItemAtPosition(position);
adapter.remove(value);
adapter.notifyDataSetChanged();
}
});

Android Webview: Override Contextual Action Bar

I am trying to override a contextual action bar in Android Webview. When I long click on a selected word, the custom action bar is displayed. However, when I click on the action bar button, nothing happens.
It seems like the onContextItemSelected() function is not called. This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
mWebView = (WebView) findViewById(R.id.wv);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_word:
Toast.makeText(CheckDictionary.this,"Save Word Meaning Successfully",Toast.LENGTH_LONG).show();
break;
default:
break;
}
if (mActionMode != null) {
mActionMode.finish();
}
return super.onContextItemSelected(item);
}
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
mode.setTitle("Save Word Meaning");
Menu menu = mode.getMenu();
menu.clear();
mode.getMenuInflater().inflate(R.menu.dictionary_menu, menu);
}
super.onActionModeStarted(mode);
}
#Override
public void onActionModeFinished(ActionMode mode) {
mActionMode = null;
super.onActionModeFinished(mode);
}
}
I am doing this job on my old projects like this:
private String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9","10"};
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new SelectionAdapter(this,
R.layout.row_list_item, R.id.textView1, data);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#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
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
mode.finish();
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " selected");
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<? arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return false;
}
});
}
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));
if (mSelection.get(position) != null) {
v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light);
}
return v;
}
}
You can make changes in this code according to your needs...
try below steps
public class MyWebView extends WebView {
MyActivity theListener;
Context context;
GestureDetector gd;
public MyWebView(Context context, AttributeSet attributes) {
super(context, attributes);
this.context = context;
gd = new GestureDetector(context, sogl);
}
// This is new
public void setListener(MyActivity l) {
theListener = l;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return gd.onTouchEvent(event);
}
GestureDetector.SimpleOnGestureListener sogl =
new GestureDetector.SimpleOnGestureListener() {
public boolean onDown(MotionEvent event) {
return true;
}
public void onLongPress(MotionEvent event) {
theListener.onLongClick(MyWebView.this);
}
};
}
and in activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
MyWebView mwv = (MyWebView) findViewById(R.id.mwv);
registerForContextMenu(mwv);
}
public boolean onLongClick(View v) {
openContextMenu(v);
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context, menu);
}

SearchView Suggestion doesn't work with one character

I have a problem with my SearchView Suggestion, when I write one character in the SearchView the Suggestion doesn't come.
But when I write two characters in the EditText of my SearchView the Suggestion will come.
So I want that my Suggestion already come when I write one character in the EditText of my SearchView, what can I do?
My Code from MainActivity:
private SearchView mSearchView;
private SimpleCursorAdapter mAdapter;
private ArrayList<String> mList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = new ArrayList<String>();
mList.add("Test 1");
mList.add("Test 2");
mList.add("Test 3");
mList.add("Test 4");
mList.add("Test 5");
mList.add("Test 6");
mList.add("Test 7");
mList.add("Test 8");
mList.add("Test 9");
mList.add("Test 10");
ListView listView = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mList);
listView.setAdapter(adapter);
mAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.suggestion, null, new String[] {""}, new int[] {R.id.suggestion_textView}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setSuggestionsAdapter(mAdapter);
// onItemClick
mSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener()
{
#Override
public boolean onSuggestionSelect(int position)
{
return false;
}
#Override
public boolean onSuggestionClick(int position)
{
// Only for Test
finish();
return false;
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
final MatrixCursor c = new MatrixCursor(new String[] { BaseColumns._ID, "" });
for (int i=0; i < mList.size(); i++)
{
c.addRow(new Object[] {i, mList.get(i)});
}
mAdapter.changeCursor(c);
return false;
}
});
return true;
}
I found a solution myself. It's not clean but it will work.
I have debug into SearchView and then I found the ID of the AutoCompleteTextView from SearchView. Than I set the Threshold for the AutoCompleteTextView from 2 to 1. Now it works.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) searchItem.getActionView();
// Solution
int autoCompleteTextViewID = getResources().getIdentifier("android:id/search_src_text", null, null);
AutoCompleteTextView searchAutoCompleteTextView = (AutoCompleteTextView) mSearchView.findViewById(autoCompleteTextViewID);
searchAutoCompleteTextView.setThreshold(1);
///////////
mSearchView.setSuggestionsAdapter(mAdapter);
// onItemClick
mSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener()
{
#Override
public boolean onSuggestionSelect(int position)
{
return false;
}
#Override
public boolean onSuggestionClick(int position)
{
// Only for Test
finish();
return false;
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
final MatrixCursor c = new MatrixCursor(new String[] { BaseColumns._ID, "" });
for (int i=0; i < mList.size(); i++)
{
if (mList.get(i).toLowerCase().startsWith(s.toLowerCase()))
{
c.addRow(new Object[]{i, mList.get(i)});
}
}
mAdapter.changeCursor(c);
return false;
}
});
return true;
}

Android delete selected items listview using contextmenu actionbar

So far this is what I've tried:
private String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten"};
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new SelectionAdapter(this,
R.layout.row_list_item, R.id.textView1, data);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#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
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " selected");
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return false;
}
});
}
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;
}
}
But I need to know how to get the selected items and put it inside OnActionItemClicked like what I've tried here:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
I commented out mAdapter.removeSelection() because I don't know what to put inside.
Any ideas? help is pretty much appreciated. Thanks.
Their are multiple things you could do.. The easiest way i think is as follows:
It doesn't work because the onActionItemClicked expects one item. But you select multiple items.
The easiest way is to create a loop in which you handle the normal procedure the onActionItemClicked expects
ListView mListView = getListView();
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
Long[] longConverts = new Long(mListView.getCheckedItemIds());
private List<Long> itemids = new ArrayList<Long>(Arrays.asList(longConverts));
for(int i=0;i<itemids.size();i++){
mListView.remove(itemids.get(i));
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
I think this should work.. It retrieves the selected items first from the ListView then put them in a array and loops over that array to remove the items one by one..
I hope this works for you

"Add to favorites" option in a soundboard app

I have this code for my soundboard,
public class soundboardActivity extends Activity {
View lastClickedView;
public static void setIntArrayPref(Context context, String key, ArrayList<Integer> values) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray a = new JSONArray();
for (int i = 0; i < values.size(); i++) {
a.put(values.get(i));
}
if (!values.isEmpty()) {
editor.putString(key, a.toString());
} else {
editor.putString(key, null);
}
editor.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// Contextual Menu
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("OPTIONS");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contex_apm, menu);
lastClickedView = v;
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ctxtapm_opcio1:
//favorites
switch (lastClickedView.getId()){
case R.id.a1: favorites.add(R.raw.sound1);
return true;
}
case R.id.a2: favorites.add(R.raw.sound2);
return true;
}
case R.id.a3: favorites.add(R.raw.sound3);
return true;
}
setIntArrayPref(this, "favoritos", favorites);
return true;
case R.id.ctxtapm_opcio2:
//share
return true;
default:
return super.onContextItemSelected(item);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apm);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(R.id.a1, R.raw.sound1);
map.put(R.id.a2, R.raw.sound2);
map.put(R.id.a3, R.raw.sound3);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
final MediaPlayer sound = MediaPlayer.create(this,entry.getValue());
Button button = (Button) findViewById(entry.getKey());
registerForContextMenu(button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sound.start();
}
});
}
FavoritesActivity code:
public class FavoritosActivity extends Activity {
ArrayList<Integer> favorites=new ArrayList<Integer>();
public View getView (int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = this.getLayoutInflater();
View item = inflater.inflate(R.layout.buttonsample, null);
return item;
}
public static ArrayList<Integer> getIntArrayPref(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(key, null);
ArrayList<Integer> favoritos = new ArrayList<Integer>();
if (json != null) {
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
int musicaid = a.optInt(i);
favoritos.add(musicaid);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return favoritos;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.proba);
favorites = getIntArrayPref(this, "favoritos");
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_list_item_1, favorites);
lv.setAdapter(arrayAdapter);
}
}
question is, how can I implement an "add to favorites" option ( favorites are in another activity) for the contextual menu?
thanks a lot!
Over ride onCreateOptionsMenu with in that create one more ArrayList for favorites .
Store the song id in arraylist for each time.
Store this array list in SharedPreferences object
When user select favourites play navigate to next activity get SharedPreferences.
According to position from the list of favourites play the song.
I hope the above solution is clear for you

Categories

Resources