Delete an item using an OnItemLongClickListener - java

I want to delete an item from the ListView using an OnItemLongClickListener.
This is my code to make an AlertDialog appear when I OnLongClick an item.
I also need to now what code to use when I delete an Item
public class DeleteItem extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView) findViewById(R.id.listView);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this);
alert.setMessage("Are you sure you want to delete this?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Here I need the delete code
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return false;
}
});
}
}

ArrayAdapter has the method remove(int index):
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1,
final int position, long arg3) {
AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this);
alert.setMessage("Are you sure you want to delete this?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ArrayAdapter yourArrayAdapter = (ArrayAdapter) arg0.getAdapter();
yourArrayAdapter.remove(position);
yourArrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return false;
}
});
Adjust the cast with the generic type of your adapter. It works only if you provide a Collection of elements to the adapter. If you provided an Array it will throw an exception

Related

Adding and removing textviews from a dynamic list in Android Studio?

I've been struggling with this for a while now, looking for any tips how to proceed. I'm trying to create a fragment that has an add button, that will create a new textview and when clicking the textview , you would have the option to delete it.
Adding textviews works fine. The problem is in the foreach loop that sets up listeners for each textview and adds the option to delete them. It's forcing me to declare the current parameter final, or the deletion won't work. But if I do declare it final, then I can't add any new textviews to the list, so they wont have listeners.
So if anyone could give me some kind of a hint, that would be hugely appreciated.
Here's the list and the adding part.
//Variables
List<TextView> TextViews = new ArrayList<TextView>();
#Override
//Put button functionality here
public void onClick(View v) {
final LinearLayout myLayout = (LinearLayout) view.findViewById(R.id.linearlayout);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// Set up the input/
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
And here is the foreach loop that sets up listeners for each TextView. They are both called in OnCreateView.
for (final TextView current : TextViews) {
current.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(current);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
}
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addViewToLayout();
}
});
void addViewToLayout(){
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertToDelete(v)
}
});
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
void showAlertToDelete(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(v);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}

I Have Crash Error when I Clicked Button; The specified child already has a parent. You must call removeView() on the child's parent first

I have this error:
The specified child already has a parent. You must call removeView()
on the child's parent first.
When I clicked buildNot.setPosiviteButton.
Help me please, thanks guys!
This is my Java source code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
That is because nothing is selected.
list.getSelectedItemPosition() will always return -1.
"Click" and "select" are separate things. "Select" in a ListView is done via the pointing device (D-pad, trackball, arrow keys, etc.).
list.getSelectedItemPosition() will always return -1 if you are not using D-pad, trackball or arrow keys.
You should store the position in onItemClick(AdapterView<?> parent, View view, int position, long id) as a class member and access it in buildNot.setPositiveButton onClick.
Coding below, where mPosition is a class member of your class.
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) adapter.getItem(mPosition);
item += "YourText";
adapter.insert(item, mPosition);
dialog.cancel();
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mPosition = position;
alertNot.show();
}
});
Try change your code like below, maybe help
public class MainActivity extends ListActivity {
int posmy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlistnew);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
final ListView list = getListView();
final ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
final EditText etDers = new EditText(MainActivity.this);
final EditText etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//adapter = (ArrayAdapter ) list.getAdapter();
//String item = (String) list.getSelectedItem();
//int position = list.getSelectedItemPosition();
int position=posmy;
String item = "YourText" + etNot.getText().toString();
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
posmy=position;
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
}

Calling AlertDialog.Builder in Java For Android Fragment When Back Button Is Pressed

I have a simple application (really!) that displays a list and then displays the details of an item on the list based on the user's choice. I do this using Fragments. The details portion is a Fragment which has an EditText in it. Currently, if the user types in the EditText and clicks on the Save button, an AlertDialog.Builder pops up asking her if she wants to save. If she chooses yes, the text is saved to a database. I want the same thing to happen if the user hits the back button. In my class that extends FragmentActivity, I have:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onKeyDown(keyCode, event);
DetailFrag frag = (DetailFrag) getSupportFragmentManager().findFragmentById(R.id.frag_stitchdetail);
frag.onKeyDown(keyCode, event);
return false;
}
In my class that extends Fragment (the details portion), I have:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getRepeatCount() == 0
&& Edited) {
return true;
}
else
return false;
}
I'm not sure where to put the code that will call the AlertDialog.Builder. I want to put it in the Fragment class because the code needs to get the rowID of the detail from the list (a class that extends ListFragment). That information isn't available to the FragmentActivity class. For clarification, here's the code I use to operate the Save button. It's called from the onCreateView method of the Fragment class and I want to re-use this code (put it in its own method, probably) when the back button is hit.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
Typeface danielFont = Typeface.createFromAsset(getActivity().getAssets(),
"danielbk.ttf");
final EditText notes = (EditText)view.findViewById(R.id.stitchnotes);
notes.setTypeface(danielFont);
notes.setTextSize(12);
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
//getActivity().finish();
}
});
alert = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alert.show();
}
});
notes.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
Edited = true;
}
});
return view;
}
The rowID that's used when I declare updateURI comes from the ListFragment class like so:
DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_stitchdetail);
if (frag != null && frag.isInLayout()) {
//more code
frag.setRowID(stitchid);
}
setRowID is defined in the Fragment class:
public void setRowID(int row_id)
{
rowID = row_id;
}
and rowID is a private static int in the Fragment class.
Can someone please point me in the right direction?
Two options I can see.
One:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
backPressed = true;
alert.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
Add the following lines to your dialog yes and no OnClickListeners:
if (backPressed){
finish();// - to exit the Activity
}
Alternately, create two separate builders as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// other code
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertSave = builder.create();
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
finish();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
alertBack = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alertSave.show();
}
});
// other code
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
alertBack.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
private void saveNotes() {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}

Remove element from listview (swipe or click)

I'm trying to create a dynamic listview. I can add an item but i can't remove it right now. The code actually it's very simple and every guide i saw are too much complicated for me and my code. I want something simple to add in my MainActivity to remove the item selceted. I don't care in which way, swipe like gmail or by click or any other way.. I just want i simple way to remove an element of the list. This is the Activity
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}
}
}
Is it possible insert some part of code to remove an item inside my activity code? Thanks
try this, While ListView item long ClickListener you can do it
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
This should help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
Put this method in your onCreate:
lvItem .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
});
}
Of course it is possible.
ArrayList.html#remove
Or if you don't know the index just iterate through the list.
Calling remove in foreach loop in Java
Do this way..
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
To delete item from list just do one thing, get onLongClickListener of listView.
Then open the context menu which has two options
Delete
Cancel
When user picks first item delete it from list. Then call listadapter notify datasetChanged method.
Use this library, I used this and it works very fine, if you prefer Swipe try this:
https://github.com/47deg/android-swipelistview
Try below code:
single click:
listview .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
showDialog(int position);
});
}
public void showDialog(int position){
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
alertDialog = builder.create();
alertDialog.setOnDismissListener(new myOnDismissListener());
alertDialog.setTitle(TITLE OF DIALOG);
alertDialog.setMessage(MESSAGE YOU WANT TO SHOW IN DIALOG);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
YOUR ARRAY.remove(position);
YOUR ADAPTER.notifyDataSetChanged();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertDialog.show();
}

how to unselect all my checkbox

I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});

Categories