I am currently having issues accessing public array list in an setPositiveButton onClick function. accessing it with this doesn't work. Here is my code:
Declaring the array list with title modules.
public class DisplayModulesActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
ArrayList<Modules> modules;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_modules);
modules = new ArrayList<Modules>();
modules.add(new Modules("387COM Smartphone App Development"));
ListView listView = (ListView) findViewById(R.id.moduleList);
adapter = new ArrayAdapter<Modules>(this,
android.R.layout.simple_list_item_1, modules);
listView.setAdapter(adapter);
registerForContextMenu(listView);
listView.setOnItemClickListener(this);
}
}
I want to access the array list here and remove something from it (line with modules.remove(i); it does not work.
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.delete_module) {
AlertDialog.Builder confirmDel = new AlertDialog.Builder(this);
confirmDel
.setMessage("Are you sure you want to delete this module and all its contents?");
confirmDel.setCancelable(true);
confirmDel.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface,
int i) {
Log.v("Test", "Confirm Delete YES pressed");
// AdapterView.AdapterContextMenuInfo info =
// (AdapterView.AdapterContextMenuInfo)
// item.getMenuInfo();
// int i = info.position;
modules.remove(i);
// adapter.notifyDataSetChanged();
}
});
confirmDel.setNegativeButton("No", null);
confirmDel.show();
}
}
Any ideas please?
FIX
public boolean onContextItemSelected(final MenuItem item)
{
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final int arrayItem = info.position;
if(item.getItemId() == R.id.delete_module)
{
AlertDialog.Builder confirmDel = new AlertDialog.Builder(this);
confirmDel.setMessage("Are you sure you want to delete this module and all its contents?");
confirmDel.setCancelable(true);
confirmDel.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.v("Test", "Confirm Delete YES pressed");
modules.remove(arrayItem);
adapter.notifyDataSetChanged();
}
});
confirmDel.setNegativeButton("No", null);
confirmDel.show();
}
You problem is, that i is not the position of the item in the ArrayList modules.
It is the position of the positive button (which might be 0 or 1 or 2 on every click, no matter which icon; maybe it's -1).
To fix this problem do the following:
Save/use the position given in onItemClick(AdapterView<?> parent, View view, int position, long id) and somehow pass it through to the onClickListener() of the dialog. Use this position to remove an item from your modules list.
E.g. in onItemClick() save position to a filed of your class mClickedPosition and call modules.remove(mClickedPosition) in the listener.
just add this in your code:
adapter = new ArrayAdapter<Modules>(this,android.R.layout.simple_list_item_1,modules);
listView.setAdapter(adapter);
do this ;)
public boolean onContextItemSelected(MenuItem item)
{
if(item.getItemId() == R.id.delete_module)
{
AlertDialog.Builder confirmDel = new AlertDialog.Builder(this);
confirmDel.setMessage("Are you sure you want to delete this module and all its contents?");
confirmDel.setCancelable(true);
confirmDel.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
Log.v("Test", "Confirm Delete YES pressed");
//AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//int i = info.position;
modules.remove(i);
adapter = new ArrayAdapter<Modules>(this,android.R.layout.simple_list_item_1,modules);
listView.setAdapter(adapter);
}
});
confirmDel.setNegativeButton("No", null);
confirmDel.show();
}
Related
I have a listview in which when you select a row, it's checkbox becomes checked / unchecked. However, I have a onItemLongClick that displays a dialog.
Problem is when I long-click a row in the listview, it becomes checked and I don't want that to happen, I just need it to display a dialog. This is confusing me because the onItemClick is also called when I use onItemLongClick.
Here's the code for onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkmark);
TextView tv3 = (TextView)view.findViewById(R.id.tx_amount);
String shitts = listView.getItemAtPosition(position).toString();
HashMap<String, String> data = new HashMap<>();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
try {
checkBox.setChecked(!checkBox.isChecked());
String[] a = shitts.split(", ");
String[] sep = a[0].split("=");
String betamount = sep[1];
String[] sepx = a[2].split("=");
String betnumber = sepx[1];
String showbetnumber = betnumber.replaceAll("[;/:*?\"<>|&{}']","");
if(checkBox.isChecked()){
hash.put(showbetnumber,tv3.getText().toString());
}else {
tv3.setText(betamount);
checked.removeAll(Collections.singletonList(position));
hash.remove(showbetnumber,tv3.getText().toString());
}
}catch (Exception e){
}
}
});
and here's the code for onItemLongClick
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String x = input.getText().toString();
txAmt.setText(x);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return false;
}
});
Any help is appreciated!
Create a boolean isLongClick and set it to false.
onItemLongClick(), set isLongClick to true.
On your dialog, set isLongClick to false again when any button is clicked or if the dialog was dismissed.
Finally, wrap all your code inside onItemClick() in:
if (!isLongClick) {
// onItemClick() code
}
The source of this solution
I have ArrayList of object (citiesInSpinner) each object have two value(Id, Name)
I have already get it in alert dialog
I use this function to alert dialog:
public void test()
{
FillSpinner();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SearchFligtsActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select City");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,citiesInSpinner);
lv.setAdapter(adapter);
/* alertDialog.setItems(citiesInSpinner, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
/////
}
});*/
alertDialog.show();
/**/
}
now I want to make something to get the ((ID)) of item (I mean the Id of City)
I tried to do that but I failed...
any help Please !!
and thank you
Simply use
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
City city = citiesInSpinner.get(position)
//get your id -> city.Id
}
});
I am performing listview's selected item id. but i'm unable to get item id. please help me..
public class ViewAllActivity extends AppCompatActivity {
ListView lv;
DbHelper dbh;
String selected;
final String ar[]={"Delete","Update"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
lv = (ListView) findViewById(R.id.listView);
dbh = new DbHelper(ViewAllActivity.this);
final ArrayList<DoctorPojo> arraylist = dbh.getData();
ArrayAdapter<DoctorPojo> adapter=new ArrayAdapter<DoctorPojo>(ViewAllActivity.this,android.R.layout.simple_list_item_1,arraylist);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
AlertDialog.Builder alert=new AlertDialog.Builder(ViewAllActivity.this);
alert.setTitle("Which Action You Want to Perform...!!!");
alert.setItems(ar, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selected=ar[which];
if(selected == "Delete") {
//Toast.makeText(ViewAllActivity.this, " Delete is pressed", Toast.LENGTH_LONG).show();
Intent i=new Intent(ViewAllActivity.this,DeleteActivity.class);
i.putExtra("id", arraylist.get((int) lv.getSelectedItemPosition()).toString());
startActivity(i);
}
else
{
Toast.makeText(ViewAllActivity.this, " Update is pressed", Toast.LENGTH_LONG).show();
}
}
});
alert.create().show();
return false;
}
});
}
}
here i cant get my listview's id. i want it because i want to pass that id because i want to delete that perticular record.and also want to perform update operation. so for that i want id os that listview's selected item. so please help me.
Try this:
DoctorPojo mPojo=arrayList.get(position);
i.putExtra("id",mPojo.getId());
I'm trying to delete the selected item in listview through Context menu.
here is my code.
public class MainActivity extends AppCompatActivity
{
EditText editText;
Button add;
ListView listView;
final DBFunctions db=new DBFunctions(MainActivity.this);
ArrayAdapter<String> adapter;
String[] values;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.editText);
add= (Button) findViewById(R.id.button);
listView= (ListView) findViewById(R.id.listView);
values=db.getAlldata();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,values);
listView.setAdapter(adapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editText.getText().toString();
if (!name.equals("")) {
editText.setText("");
long check = db.insertData(name);
if (check < 0) {
Toast.makeText(MainActivity.this, "Error in insert query", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, name + " inserted", Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
} else {
editText.setError("this field is empty");
}
}
});
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
int position=listView.getSelectedItemPosition();
String data=values[position]; //error line
Log.e("Value ", data );
Log.e("Position ", position+"" );
switch (item.getItemId())
{
case R.id.delete_name:
long check=db.deleteData(data);
if(check<0)
{
Toast.makeText(MainActivity.this,"Error in query",Toast.LENGTH_SHORT).show();
}
else
{
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,data+" deleted",Toast.LENGTH_SHORT).show();
}
return true;
default :
return super.onContextItemSelected(item);
}
}
}
when i run above code i get following error:
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
at pack.madhan.listviewdemo.MainActivity.onContextItemSelected(MainActivity.java:72)
at android.app.Activity.onMenuItemSelected(Activity.java:2628)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3864)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)
is it possible to delete selected item in listview via context menu ?
please help me on this.
finally i found an answer
Error Code:
int position=listView.getSelectedItemPosition();
String data=values[position];
Updated Code:
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String data=values[info.position];
where info.position gives the position of item in listView.
To refer click here
Based on the logstack, your function listView.getSelectedItemPosition() returns -1.
int position=listView.getSelectedItemPosition();
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
-1 is not a correct index, and is the cause of this OutOfBoundsException.
I've never tried to keep track of the latest element selected in a list, but you could do as follow :
Add a variable at the begining of your MainActivity to keep track of the selectedItem;
// First item of the list is selected by defaul to avoid out of bound
int selectedItem = 0;
And update this variable with the onItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = id;
}
});
How can I catch such event? onCreateContextMenu is quite similiar, but I don't need menu.
It's hard to know what you need to achieve. But my guess is that you want to perform some acion over the item that receives the long click. For that, you have two options:
add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.
.
listView.setOnItemLongClickListener (new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
//do your stuff here
}
});
if you are creating a custom adapter, add a View.OnLongClickListener when creating the View in the method Adapter#getView(...)
Normally, you'd associate a long click on a list view with a context menu, which you can do by registering the listView with Activity.registerForContextMenu(View view) to give a more consistent user interface experience with other android apps.
and then override the onContextItemSelected method in your app like this:
#Override
public void onCreate(Bundle savedInstanceState) {
listView = (ListView) findViewById(R.id.your_list_view);
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(getString(R.string.menu_context_title));
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.some_item:
// do something useful
return true;
default:
return super.onContextItemSelected(item);
}
The position in the list is also held in info.id
If you just want to capture the long click event, then I think what Snicolas is suggesting would work.
Add a custom View.OnLongClickListener to your views. It can be shared by many instances, then you can use the parameter of
onLongClick(View v)
to know which view has been clicked and react accordingly.
Regards,
Stéphane
//Deleted individual cart items
//on list view cell long press
cartItemList.setOnItemLongClickListener (new OnItemLongClickListener() {
#SuppressWarnings("rawtypes")
public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) {
final CharSequence[] items = { "Delete" };
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Action:");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
cart = cartList.get(position);
db.removeProductFromCart(context, cart);
new AlertDialog.Builder(context)
.setTitle(getString(R.string.success))
.setMessage(getString(R.string.item_removed))
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CartDetailsActivity.this, HomeScreen.class);
startActivity(intent);
}
})
.show();
}
});
AlertDialog alert = builder.create();
alert.show();
//do your stuff here
return false;
}
});