Open context menu on Longclick on ListView - android

I have a simple context menu and I want to make a Toast to display a short message.
The problem is I can't get the item Position to display the specific detail I want because the Position of the adapter is out of scope.
This is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayAdapter<Product> adapter;
private ListView listView;
private ContextMenu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
registerForContextMenu(listView);
adapter.add(new Product("shoe", 150));
adapter.add(new Product("T shirt", 80));
adapter.add(new Product("pants", 100));
adapter.add(new Product("lamp", 300));
adapter.add(new Product("ball", 20));
adapter.add(new Product("egg", 1));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Toast.makeText(MainActivity.this, adapter.getItem(position) + ": " + adapter.getItem(position).getPrice(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View v) {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("choose what to do");
menu.add(1, 0, 0, "product details");
menu.add(1,1,1,"delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 0:
Toast.makeText(MainActivity.this, adapter... + ": " + adapter..., Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}

I assume because it seems like you wanted to know which item has been long pressed by the user and wanted to know the item position so that you can get the value from Adapter Or List.
If I understand you correct PFB solution
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
info.position;//This is your desired position.
now you have the value and you can play with it. Njoy!
Happy Coding!!!

Related

i want to get listview's id of selected item

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());

can't able to delete selected item in a listView via context menu?

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;
}
});

onClick listener not working on predefined listview layout?

I'm using predefined listview layout to show all the native messaging sms into my application.Code i defined in onCreate method:
lvInb = (ListView) findViewById(R.id.lvInb);
lvInb.setOnCreateContextMenuListener(this);
data = fetchInbox();
if(data!=null)
{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
lvInb.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvInb.setAdapter(adapter);
}
for fetchInbox() I've created another method:
public ArrayList<String> fetchInbox()
{
ArrayList<String> sms = new ArrayList<String>();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cr = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
cr.moveToFirst();
while (cr.moveToNext())
{
sms.add(cr.getString(1)+"\n"+cr.getString(3)+"\n");
}
cr.close();
return sms;
}
code to delete row item in listview is:
private void openDelete() {
removeListViewItem();
}
public void removeListViewItem() {
if(intListViewItemPosition != -1){
lvInb.removeViewAt(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
code in activity:
ListView lvInb;
ArrayAdapter<String> adapter;
int intListViewItemPosition = -1;
ArrayList<String> data;
Outside onCreate method:
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu (menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
MenuChoice(item);
return true;
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0,0,0,"Delete");
{
mnu1.setIcon(R.drawable.ic_launcher);
}}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
removeListViewItem();
break;
}
return false;
}
public void removeListViewItem() {
intListViewItemPosition = lvInb.getSelectedItemPosition();
if(intListViewItemPosition != -1){
//lvInb.removeViewAt(intListViewItemPosition);
data.remove(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
delete option i've provided in menu options. but when i select a row item and click on delete option it shows No item selected
Hey in where you are assigning the selected Item position value into "intListViewItemPosition"
If not used please implement this in your listview OnItemClickListener,
intListViewItemPosition= listView.getSelectedItemPosition();
You are trying to remove the selected Item from the listview right ?? for that you have clicked your listview item from the lisview, so you need to implement onClickListener for your listview
your code should be like this,
your_listView_name.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
intListViewItemPosition= listView.getSelectedItemPosition();
}
});
thats it..
first thing call fetchIndex only once:
declare an ArrayList of string in activity:
ArrayList<String> data;
ArrayAdapter<String> adapter
and in onCreate:
lvInb = (ListView) findViewById(R.id.lvInb);
lvInb.setOnCreateContextMenuListener(this);
data= fetchInbox();
if(data!=null)
{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
lvInb.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvInb.setAdapter(adapter);
}
now change change removeListViewItem to:
public void removeListViewItem() {
intListViewItemPosition= lvInb.getSelectedItemPosition();
if(intListViewItemPosition != -1){
//lvInb.removeViewAt(intListViewItemPosition);
data.remove(intListViewItemPosition);
adapter.notifyDataSetInvalidated();
intListViewItemPosition = -1;
}else{
Toast.makeText(this, "No item selected", Toast.LENGTH_SHORT).show();
}
}
also have class level variable for adapter so that you can access it in removeListViewItem.
ArrayAdapter<String> adapter;
and in onCreate just say:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1 , data);
If you declare it again in onCreate the class level one would be null and you might get null pointer when your removeListViewItem will get called.

Making a custom android ListView adapter Clickable

I've been trying to create a clickable listview that takes in a string array and a few images and presents them in a textview style. So far I have managed to create a listview with each of the strings and images, however I am unsure how to use the onClick method so as to make the textviews clickable to start new activities etc.
Here is my code so far (Excluding XML):
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_test2, values);
this.context = context;
this.values = values;
}
/* Print a toast when a list item is clicked, don't know what to do */
public void onClick() {
switch (list item) {
case 0:
Toast.makeText(this.context, "Pressed!", Toast.LENGTH_LONG).show()
break;
}
case 1:
etc....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_test2, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
String s = values[position];
if (s.startsWith("Report a Road Delay")) {
imageView.setImageResource(R.drawable.ic_menu_compose);
} else if (s.startsWith("View Reported Delays")) {
imageView.setImageResource(R.drawable.ic_menu_view);
} else if (s.startsWith("Search a Road for Delays")) {
imageView.setImageResource(R.drawable.ic_menu_search);
} else if (s.startsWith("Update a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_edit);
} else if (s.startsWith("Validate a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_mark);
}
return rowView;
}
}
public class MainActivity extends ListActivity {
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
String[] values = new String[] { "Report a Road Delay",
"View Reported Delays", "Search a Road for Delays",
"Update a Delay Report", "Validate a Delay Report" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This is how it looks so far:
All I basically don't understand is the onClick method; what parameters it takes it, and how to determine which item was clicked. Any help would be appreciated.
Try this:
ListView list1 = getListView();
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//Take action here.
}
}
);
You are looking for an OnItemClickListener and not an OnClickListener
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// DO SOMETHING WITH CICK EVENT HERE
}
}
Now only to discus the params:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked
position The position of the view in the adapter.
id The row id of the item that was clicked.
I got the last part from android reference
You could use this code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a <extView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
// we register for the contextmneu
registerForContextMenu(lv);
}
where lv is the listView.
If you want to add a context menu:
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
Planet planet = aAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + planet.getName());
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
planetsList.remove(aInfo.position);
aAdpt.notifyDataSetChanged();
return true;
}
If you want to have more information give a look on my blog here and here

Getting listview item index in android

I am making an android application that uses a listview. I want to get the index number of an item once an item has been pressed(single-click). I've gone through several tutorials, but none seemed to help. How can i get the index number and pass it to a String. I do then want to delete it, but i'll manage that part my self. I only need the index number and pass it to a string. The code where i'll get the index number is straigt after the onCreate method. Please help and thanks in advance! This is the code that i am using:
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout;
public String DeleteIndexNumber;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
//This is where i need the index number to be passed to the string "DeleteIndexNumber"
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
break;
}
}
}
notice the parameters for the onItemClick method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
position will give you the index you desire..
Isn't it position parameter in onItemClick ?
The position parameter in onItemClick will give you the index of the clicked Item in the list.

Categories

Resources