Item showing during debug otherwise not showing item in ListView - java

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.

Related

Trouble getting notifyDataSetChanged() to update my listview

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

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.

Problems to re-setAdapter the listview

I have a problem to update a listview, but doesn't work. Gives the NullPointerException on ".SetAdapter", does anyone know what can be?
Complete code: http://pastebin.com/AZdMi4sc
//Get filter from another fragment, using Interface, works fine.
public void setFilter(String tag) {
getFeedFilter(tag);
}
//Get only itens
private void getFeedFilter(String filter) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("FeedPost");
query.whereContains("Type", filter);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> responseList, ParseException e) {
if (e == null) {
List<Feed> items = new ArrayList<Feed>();
for(int i = 0; i < responseList.size(); i++) {
items.add(new Feed(responseList.get(i).getString("objectId"),
responseList.get(i).getString("Title"));
}
adapter = new FeedAdapter(getActivity(), items);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter); // The error occurs here.
} else {
System.out.println("error: "+ e);
}
}
});
}
Logcat log:
04-27 03:52:23.175 4415-4415/com.fatos.application.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.fatos.application.app.fragment.FeedFragment$6.done(FeedFragment.java:256)
at com.parse.FindCallback.internalDone(FindCallback.java:45)
at com.parse.FindCallback.internalDone(FindCallback.java:31)
at com.parse.Parse$5$1.run(Parse.java:853)
.....
1) you should check if the adapter isn't null.this will fix your crash.
if(adapter!=null)
listView.setAdapter(adapter);
2) you should check if the items returned from response are ok, your problem might be there.
3) your code mixed up, you should init your views and set listeners on one method,
I always call init in fragment - OnCreateView ...
4) The problem might be with your listView, when you are using custom view make sure you give the full location of the custom listview class as your view instead of ListView.
Also, if you just update your adapter, you should not re create your adapter every time. create method in your adapter which set the new data. and just call adapter.notifyDataSetChanged();
For example:
In your adapter code add this:
public void setData(ArrayList<object> newData) {
this.data = newData;
}
then, in your activity notify adapter :
if(items!=null && items.size()>0) {
if(adapter==null){
adapter = new FeedAdapter(getActivity(), items);
}
else {
adapter.setData(yourArrayList);
adapter.notifyDataSetChanged();
}
else {
make toast for us or log to notice items are null...
}
if(adapter!=null)
listView.setAdapter(adapter);
I also think you should init your view and set listeners on your onCreateView method,
because everything is split in your code.

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