Trouble getting notifyDataSetChanged() to update my listview - java

I recognize that there are plenty of questions and answers about the notifyDataSetChanged() method already on stackoverflow, but I've reviewed most of them and can't figure out what could be wrong here. I'm trying to get my listview to dynamically add more lines as the user clicks on the "Add Ingredient Button". It will add the first ingredient after the first click, but any subsequent clicks do not result in any change to the list view. Any help is appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_recipe);
ButterKnife.bind(this);
mAddInstructionsButton.setOnClickListener(this);
mAddIngredientButton.setOnClickListener(this);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, ingredientList);
mListView.setAdapter(adapter);
}
public void onClick(View v) {
if(v == mAddIngredientButton) {
if(mIngredientName.getText().toString().trim().equalsIgnoreCase("") || mIngredientMeasurement.getSelectedItem().toString().trim().equalsIgnoreCase("") || mIngredientCount.getText().toString().trim().equalsIgnoreCase("")) {
Toast answerStatus = Toast.makeText(NewRecipeActivity.this, "Fill out all fields", Toast.LENGTH_LONG);
answerStatus.show();
} else {
String ingredient = createIngredientString();
ingredientList.add(ingredient);
adapter.notifyDataSetChanged();
clearIngredientInputs();
Log.i("NewRecipeActivity", "List includes: " + ingredientList);
}
}

You need to add the new Ingredient to the Adapter's list, using the method
adapter.add(ingredient)
like this
String ingredient = createIngredientString();
adapter.add(ingredient);
adapter.notifyDataSetChanged();

Oh boy, I feel silly about this one. The code was working all along just as it was posted in my question. The listview element on my activity was set with a height of 52 pixels, so that any rows that were added to the listview did not appear.
Spent about 4 hours reading posts and changing up all kinds of stuff in the java file, and it was just an issue with the height of the display element. Cue sad trombone sound

Related

Item showing during debug otherwise not showing item in ListView

This is my code, when I debugging then code work properly means list item show in Listview but without debugging list item not showing in this code Listview empty
ImageView cancl1e = convertView1.findViewById(R.id.btncance);
if (jsonArray.length() > 0) {
listView = convertView1.findViewById(R.id.Benificiarylist);
adapter = new Recipient_ListAdapter(MoneyTransferFragment.this,value);
listView.setAdapter(adapter);
cancl1e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog1.dismiss();
}
});
alertDialog1.setView(convertView1);
alertDialog1.show();
} else {
Nodatafound.setVisibility(View.VISIBLE);
}
Kindly handle dialog separately. It's working while debugging because while debugging its getting time between display data dialog I guess. Please specify if wrong.

How to perform clicking on the first item in an ArrayList by Espresso

I have tried to click on the first item of my arraylist for few hours, I have read a lot of questions on Stack Overflow, tutorials and I have tried to implement them in many ways, but it doesn't work.
clickView(getSearchActivity().hintListView);
onData(anything())
.onChildView(withId(R.id.hintLayout))
.atPosition(0)
.perform(click());
onData(allOf(is(instanceOf(String.class))))
.atPosition(0)
.perform(click());
onData(instanceOf(ArrayList.class))
.atPosition(0)
.perform(click());
onData(instanceOf(String.class))
.atPosition(0)
.perform(click());
onData(anything())
.inAdapterView(withId(R.id.hintLayout))
.atPosition(0)
.perform(click());
onData(anything())
.inAdapterView(allOf(withId(R.id.hintLayout), isCompletelyDisplayed()))
.atPosition(0).perform(click());
I have to click on the first item of the ListView, that take ArrayList
id of this ListView is hintLayout.
Does anybody know what is the problem ? and where can it be ?
A ListView must be filled with an adapter. After your adapter is finished just add it to your ListView like this:
private void setListAdapter(ListDataAdapter adapter){
lvYourListView.setAdapter(adapter);
}
In order to get the data back out on the OnClick event you need to something like this in you onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lvYourListView = (ListView) findViewById(R.id.lvListview);
lvYourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListData data = new ListData();
data = (ListData)parent.getItemAtPosition(position);
doSomethingWithData(data);
}
});
If you need help with the adapter - just let me know. I will need to see more of your code in order to do that.

Can't unselect ListView item when deleting it

Trudging my way through my introduction to Java and Android on a simple app and have run into an issue with ListView item selection. For one of my activities, I have a layout with two buttons, one of which is a "Delete" button, and a ListView of "passages" which are essentially timestamps for when a device has passed a sensor.
I have implemented the ability to click on an item to select it, which then enables the "Delete" button. A click of the "Delete" button removes the "passage" but I still end up with a selected item, which I don't want.
To implement selection, I added the following property to the ListView:
android:id="#+id/passagesListView"
android:choiceMode="singleChoice"
android:listSelector="#666666"
Selection is supported in OnCreate via a an OnItemClickListener:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
passagesViewAdapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
final ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
final Button deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setEnabled(false);
buildPassageList();
passagesListView.setAdapter(passagesViewAdapter);
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(ViewPassagesActivity.this, "position is " + position,
Toast.LENGTH_LONG).show();
view.setSelected(true);
passagesViewAdapter.notifyDataSetChanged();
selectedItemPos = position;
deleteButton.setEnabled(true);
}
});
}
This part works. However, there is some issue with deletion. As you can see in the comments, I have tried several methods that I found on StackOverflow that seemed to apply but, although I am able to delete the correct item from the list, I am still ending up with a selected item after the call to delete().
public void delete (View view)
{
final Button deleteButton = (Button) findViewById(R.id.deleteButton);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
if(selectedItemPos != -1)
{
Toast.makeText(ViewPassagesActivity.this, "remove " + selectedItemPos,
Toast.LENGTH_LONG).show();
// This did not work, which is strange since it worked similarly for selection when clicked
// View itemView = passagesListView.getChildAt(selectedItemPos);
View itemView = passagesViewAdapter.getView(selectedItemPos, null, passagesListView);
itemView.setSelected(false);
// This was also recommended in various posts on StackOverflow.
// Not clear whether clearChoices applies only to checkBoxes?
// passagesListView.clearChoices();
// passagesListView.requestLayout();
passages.remove(selectedItemPos);
deleteButton.setEnabled(false);
selectedItemPos = -1;
passagesViewAdapter.notifyDataSetChanged();
}}
}
I also ran into some issues trying to track which item is selected via setSelected() and getSelectedItemPosition() and punted by just tracking the index myself. So, as I am new to this, I'm sure there is something I am not understanding about Views or maybe something else such as a misunderstanding of how selection works?
How can I clear the selection?
Thanks!
I don't know what your PassagesViewAdapter class looks like. Maybe you can try
passagesViewAdapter.remove(passages.get(selectedItemPos));
passages.remove(selectedItemPos);
deleteButton.setEnabled(false);
selectedItemPos = -1;
passagesViewAdapter.notifyDataSetChanged();

Deleting elements in empty arraylist crashes my app

I have an arraylist for my spinner, 1 add button to add element into the list and 1 delete button to delete the element inside the list. The elements that I added into the list will show in the spinner. Initially the arraylist is empty with nothing inside. When it is empty and I press the delete button, means that I am trying to delete elements in a arraylist with no element inside and this makes my app crashes.
So, I wanted to add a toast to replace the delete function when the list is empty. When the list is not empty, then the delete function will come back.
Any solution for this?
spinner = (Spinner) findViewById(R.id.spinner1);
adp = new ArrayAdapter<String>(CarSelection.this,android.R.layout.simple_spinner_item, list);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, final int position, long id) {
Button delete = (Button) findViewById(R.id.delete);
View.OnClickListener del = new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position);
}
Firstly,IMHO for better UX, you should not display the spinner if the list is empty.You can show toast message to the user saying that you cant perform this operation.
Anyways here is the code snippet you can use to do the check.You can put this check in whichever place you want
if(!list.isEmpty())
//list is empty
else
list is not empty
Lets say, your ArrayList is called mList, your delete function should look something like -
public void deleteElement(int pos) {
if(mList.isEmpty()) {
//Toast
Toast.makeText(yourContext, "Ooi, list is empty", Toast.LENGTH_SHORT).show();
} else {
mList.remove(pos);
}
}
UPDATE
#Override
public void onClick(View view) {
if(list.isEmpty()) {
//Your Toast
Toast.makeText(yourContext, "Ooi, list is empty", Toast.LENGTH_SHORT).show();
} else {
list.remove(position);
}
}
You should test for the "empty" case. Supposing an array named "elements":
if elements.isEmpty() {
deleteButton.disable();
}
The best is to disable the delete button when there is no elements in the array.

onListItemClick add item to ListView in another activity

I am very sorry if this question already exists, but I couldn't find any answer to my problem. The idea of my application is a Shopping List. The user can see a list of food and on clicking on an item, it should automatically be added to a list.
What I already have is a ListView generated from an xml-file in a raw folder. This is my food, I haven't stored it in a SQLite Database.
What I want to do now is that when I click on an item in this list, it's added to a ListView in another Activity called "ShoppingList.java". It shouldn't open immediately, so the user has the possibility to add more items.
Now, when I click on an item, it's added to a TextView called "selection" in the same Activity on the top of the screen.
How is it possible to add an item from one Activity to another one?
Thank you very much for your help!
public class FishOk extends ListActivity {
TextView selection;
ArrayList<String> items=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.foodok_list);
selection=(TextView)findViewById(R.id.selection);
try {
InputStream in=getResources().openRawResource(R.raw.fish);
DocumentBuilder builder=DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
Document doc=builder.parse(in, null);
NodeList words=doc.getElementsByTagName("product");
for (int i=0;i<words.getLength();i++) {
items.add(((Element)words.item(i)).getAttribute("value"));
}
in.close();
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), 2000)
.show();
}
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(items.get(position).toString());
}
public void onClick(View view) {
ListView lstView = getListView();
String itemsSelected = "Selected items: \n";
for (int i=0; i<lstView.getCount(); i++) {
if (lstView.isItemChecked(i)) {
itemsSelected += lstView.getItemAtPosition(i) + "\n";
}
}
Toast.makeText(this, itemsSelected, Toast.LENGTH_LONG).show();
}
Adding an item to the ListView of an Activity which isn't visible to the user and doesn't yet exist makes no sense. You should have a place where you'll store the data, it can be a SQLite database, a plain text file, or SharedPreferences if there's not much data. When you're clicking on a Button inside your current Activity you should store the information to your data storage, and then retrieve it to populate the ListView when the second Activity starts. Hope this helps.
Activity is a window where you can put your UI stuff so that user can interact with the application.
Now, for using the data in the activities across the application, you have to use either Collections or Database.
But as per your requirement, I think you should use Collections.
Maintain an Arraylist or a HashTable according to your data.
Pass that data from one activity to other.
OR
Maintain a singleton class and update the data in that class. Access the data from other activities.
I hope this helps you.

Categories

Resources