Delete item from listview when the item is clicked - java

I currently have this code to display chosen items in a listview:
public class DisplayOrder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_order);
bar();
Button btn = (Button) findViewById(R.id.btnHome);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(DisplayOrder.this, Options.class);
startActivity(myIntent);
}
});
}
private void bar() {
ListView lv = (ListView) findViewById(R.id.listViewDisplay);
List<String> itemsOrdered = new ArrayList<String>();
for (Map.Entry<Item, Integer> entry : Datastore.currentTable.getOrder().getItems().entrySet()) {
itemsOrdered.add((entry.getKey().name) + " x " + String.valueOf(entry.getValue()) + " £" + (entry.getKey().price * entry.getValue()));
}
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_display_order, R.id.textView8, itemsOrdered);
lv.setAdapter(arrayAdapter);
}
}
What i want to do is, when I click one of the items, for it to be deleted but Im not sure how to do that. Any guidance would be much appreciated.

You should detect when you click in each item of ListView by setOnItemClickListener.
Then inside this method, just delete the list datasource and notifyDataSetChanged
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > parent, View view,int position, long id) {
itemsOrdered.remove(position); // remove item at index in list datasource
arrayAdapter.notifyDataSetChanged(); // call it for refresh ListView
Toast.makeText(getApplicationContext(), "remove item at " + position, Toast.LENGTH_LONG).show();
}
});

You have to override the listener “setOnItemClickListener” like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
itemsOrdered.remove(item);
arrayAdapter.notifyDataSetChanged();
}
});
This code removes the ítem from the list, but you have to notify the change to the adapter. When the adapter is notified the listview is updated.

Related

How do i copy an item in an list into a list in another activity?

Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.

OnItemClickListener() not working with List Adapter

I am fetching data in to list adapter through calling a function named getAllDishes(). Now I want to add OnItemClickListener() on list when I click on a particular item, it opens another activity and pass the id of selected item. I am new to android. All suggestions are welcome.
Main Activity
public class MainActivity extends ListActivity {
private DishOperation dishDBoperation;
#Override
public void onCreate(Bundle savedInstanceState) {
Button btListe;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dishDBoperation = new DishOperation(this);
dishDBoperation.open();
List values = dishDBoperation.getAllDishes();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
//This is what i tried
OnItemClickListener listener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Result.class);
startActivity(intent);
finish();
}
}
Try this way , You can use this
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Do your Staff Here
Intent intent = new Intent(MainActivity.this, Result.class);
startActivity(intent);
}
});
Or
You can use
getListView().setOnItemClickListener(listener);
After setListAdapter(adapter);
Set the ItemClickListener to list view :
listview.setOnItemClickListener(listener);
In your case, add this line: getListView().setOnItemClickListener(listener);
like this:
OnItemClickListener listener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Result.class);
startActivity(intent);
finish();
}
}
getListView().setOnItemClickListener(listener);
You need to actually set the click listener to the ListView. In your onCreate, after the call to setAdapter(adapter), call getListView().setOnItemClickListener(listener);

How to retrieve Firebase data and create an android list view

I am trying to retrieve data from firebase and creating an android list view from the data retrieved. For example I'd like to retrieve all the messages from https://docs-examples.firebaseio.com/web/data and create an android list view for each message. Where the child's of the messages would simply be data displayed for each single list view.
This https://www.firebase.com/docs/android/guide/retrieving-data.html helps explain the supported Firebase datatypes but still find it difficult to understand. Your help is much appreciated.
Thank You!
Listview.java
public class ListingsActivity extends ListActivity {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
ActionBar actionBar = getActionBar();
actionBar.hide();
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/data/messages/");
final Map < String, Object > data;
final List <? > data2;
// Attach an listener to read the data at our posts reference
ref.addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("Data: " + snapshot.getValue());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Something went wrong!");
}
});
// Binding Array to ListAdapter
// this.setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_listings, R.id.label, firebaseData));
ListView lv = getListView();
System.out.println("HERE!!!");
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView <? > parent, View view,
int position, long id) {
// selected item
String fproduct_label = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListView.class);
// sending data to new activity
i.putExtra("fproduct_label", fproduct_label);
startActivity(i);
}
});
}
}
SingleView.java
public class SingleListView extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("fproduct_label");
// displaying selected product name
txtProduct.setText(product);
}
}

Editable ListView Items

I want to Edit my ListView items. for example; I have a listView item i clicked this item and I add string value with edit text afterwards I again click this item and I add new string value alongside to previous string value, and again, again, again. When I click this item I want edit this listitem. How I do that?
Java sourcecode:
public class MainActivity extends Activity {
TextView tvDers;
EditText etDers, etDersSaati;
EditText etNot;
LinearLayout LayoutDers;
ArrayAdapter<String> adapter;
ListView list;
#Override
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);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
}
});
list.setAdapter(adapter);
final AlertDialog alertDers = build.create();
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
}
Save item values in ordering Collection. Set this collection in adapter. Add and remove this values and after call notifyDataSetChanged for adapter.
Try like this.
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String item = (String) parent.getItemAtPosition(int position);
item += "YourText";
ArrayAdapter adapter = (ArrayAdapter ) parent.getAdapter();
adapter.insert(item, position);
}
Sorry, but now I can't test this code. So I can not say for sure that it is correct. Try different variants and you'll get.
UPDATE
From dialog clickListener you can try this:
#Override
public void onClick(DialogInterface dialog, int which) {
ArrayAdapter adapter = (ArrayAdapter ) listView.getAdapter();
String item = (String) listView.getSelectedItem();
item += "YourText";
adapter.insert(item, position);
}

Why my listview is empty?

I have a arraylist in which users can input their text. And it is displayed in the screen as a listview. That works, but when i try to get the values of the arraylist it says that: Invalid index 0, size is 0. So im guessing for some reason the listview isnt populating?
This is how I add values to the list:
public class ZaidejaiActivity extends ActionBarActivity implements View.OnClickListener{
public Button mBtnIstrinti;
public Button mBtnPrideti;
public Button mBtnPradeti;
public EditText mYrasytiVarda;
public ListView mZaidejai;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidejai);
mBtnPrideti = (Button) findViewById(R.id.pridėtiBtn);
mBtnPrideti.setOnClickListener(this);
mYrasytiVarda = (EditText) findViewById(R.id.VardoYrasymoBtn);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the mZaidejai variable to your list in the xml
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
mZaidejai.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// remove item from List.
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
list.remove(position);
AlertDialog.Builder builder = new AlertDialog.Builder(ZaidejaiActivity.this);
builder.setMessage("Delete?");
builder.setTitle("Confirm Action");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
adapter.notifyDataSetChanged();
}
//checked.clear();
});
builder.setNegativeButton("Cancel", null);
builder.create();
builder.show();
}
});
mBtnPradeti = (Button) findViewById(R.id.žaistiBtn);
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
});
}
#Override
public void onClick(View v) {
String input = mYrasytiVarda.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}else{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Klaida:");
alertDialog.setMessage("Blogai yrašytas vardas");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
}
EDIT
In this activity I want to get the values of the list:
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mZaidejas;
public TextView mKlausimas;
public Button mKitasKlausimas;
public Button mGryzti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
//show the first players name
mZaidejas = (TextView)findViewById(R.id.ZaidejoVardas);
mZaidejas.setText(list.get(0));
/** mGryzti = (Button)findViewById(R.id.GryztiMeniuBtn);
mKitasKlausimas = (Button)findViewById(R.id.KitasBtn);
mKitasKlausimas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
*/
Unfortunately your list==empty. So add some values on it.
list.add("ABC");
list.add("XYZ");
and then setAdapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
Your not adding any values to it. And your list is empty and add some values to it like list.add("hyd");
list.add("city");
and pass those values to adapter
Rather doing
adapter.add(input);
Do
list.add(input);
adapter.notifyDataSetChanged();
So, as others have said you should change the adapter.add(input); on the onClick method to
list.add(input);
adapter.notifyDataSetChanged();
Also, on an unrelated matter, you should really move the list.remove(position); call to the following onClick method of the positive button, before the adapter.notifyDataSetChanged(); call, so it wont be removed if the user cancels the action :)
at the first time your list adapter is empty (getCount() = 0) and you do -1 in the for
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
if (adapter.getCount() > 0)
{
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
}
});
and for this code :
mZaidejas.setText(list.get(0));
but on Create your list is empty !!!

Categories

Resources