I search a lot of similar question...all of them say I must use something like this code:
arrayAdapter.notifyDataSetChanged();
after this code: bookmarks.remove(pos);
but you can see...in BookMarkActivity class do not use arrayAdapter
public class BookMarkActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
// Reading all contacts
final ArrayList<BookMark> bookmarks = (ArrayList<BookMark>) db.getAllBookMarks();
BuildingAdapter adapter = new BuildingAdapter(context);
// ADDED
final ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(new BookmarkAdapter(this, bookmarks));
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
bookmarks.remove(pos);
return true;
}
});
}
}
I am new in android...but I try change code with this:
private ArrayAdapter<BookMark> arrayAdapter;
arrayAdapter = new BookmarkAdapter(this, bookmarks);
but no success! the listview do not be refresh after delete one item!
ListView displays some data stored in an ArrayList.
When element remove or add in ArrayList, you have to tell the list that the source of the data had changed to show the new data.
So, that is where notifyDatasetChanged() comes in. It tells the ListView that the data has been modified so please reflect the changed data.
final BookmarkAdapter adapter = new BookmarkAdapter(this, bookmarks);
lv.setAdapter(adapter);
and after remove element use below line.
adapter.notifyDataSetChanged();
hope it helps.
Just add two lines on the button/imageView click listeners.
delete.setOnClickListener {
list.removeAt(pos)
notifyItemRemoved(pos)
}
Related
I have a ListView that displays an ArrayList that is dynamically created using an adapter. However, certain elements of each list item view are calculated based on previous item values. I am using Intents to open another activity where the user can edit a selected list item, and the updates are passed back to the main activity. In the main activity I've placed the getIntent, and the associated setters, after the ArrayList is generated and before the adapter. When the main activity is first created the adapter correctly calculates all list view items. But when the user accepts updates in the edit activity and returns to the main activity, only the selected list item is updated. Having the entire list cycle through and update would be fine (it will never be a very long list), but I'm a little surprised that only the selected list item is getting updated. I expected that either the adapter would run as it does when the activity is first created and all items would get updated, or that it wouldn't run at all and none would get updated.
public class MainActivity extends AppCompatActivity {
private final Context thisContext = MainActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView planListView = findViewById(R.id.plan_listview);
final ArrayList<ItemProfile> planSteps = BuildPlan();
if(getIntent().getExtras() != null)
{
int stepNumber = getIntent().getIntExtra("stepNumber", 0);
ItemProfile thisStep = (ItemProfile) getIntent().getSerializableExtra("itemProfile");
planSteps.get(stepNumber-1).setDepth(thisStep.getDepth());
planSteps.get(stepNumber-1).setTime(thisStep.getTime());
planSteps.get(stepNumber-1).setInterval(thisStep.getInterval());
}
ItemsListAdapter planAdapter = new ItemsListAdapter(this, planSteps);
planListView.setAdapter(planAdapter);
planListView.setOnItemClickListener(
new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l)
{
int index = pos-1;
Intent i = new Intent(thisContext, EditItemActivity.class);
i.putExtra("stepNumber", pos);
i.putExtra("stepProfile", planSteps.get(index));
if (index > 0)
{
i.putExtra("groupStart", planSteps.get(index-1).getGroupEnd());
}
startActivity(i);
}
}
);
}
}
Update... I've added the mainActivity code. It creates an ArrayList plan (I'm using a BuildPlan method to populate a dummy plan while I'm developing) then checks for an intent that is returning an updated plan step. If an intent exists the specified step is updated in the plan. The list adapter is then created and set. Finally the clickListener is created and set.
I've done something relatively similar but I used dynamic spinners and listviews from a database.
Here is the code. Basically you invalidate the list view, reset the data and call notifyDataSetChanged() on the adapter.
public ListView lv;
Spinner suburbSpinner;
ArrayAdapter<String> suburbAdapter;
ArrayList<String> suburbs = new ArrayList<>();
ArrayList<Resource> resources = new ArrayList<>();
ArrayAdapter<Resource> arrayAdapter;
public void updateList(String type, String suburb, String businessType, int suburbPos) {
DatabaseHelper db = new DatabaseHelper(this, "fairCanberraDB", null, 1);
lv = findViewById(R.id.list);
// Reset suburb spinner, get new list view resources.
lv.invalidateViews();
resources = db.resourceQuery(type, suburb, businessType);
System.out.println("resource: " + resources);
ArrayList<Resource> suburbQuery = db.resourceQuery(type, "All", businessType);
Spinner suburbSpinner = findViewById(R.id.suburbSpinner);
suburbs.clear();
suburbs.add("All");
for (int x = 0; x < suburbQuery.size(); x++) {
if (suburbs.contains(suburbQuery.get(x).getSuburb())) {
continue;
} else {
suburbs.add(suburbQuery.get(x).getSuburb());
}
}
db.close();
suburbAdapter.notifyDataSetChanged();
arrayAdapter.notifyDataSetChanged();
ArrayAdapter<Resource> arrayAdapter = new ArrayAdapter<Resource>(
this,
android.R.layout.simple_list_item_1,
resources);
lv.setAdapter(arrayAdapter);
if(suburbPos < suburbSpinner.getCount())
{ suburbSpinner.setSelection(suburbPos);}
setSpinnerListener(suburbSpinner);
}
// Register listener for a spinner
public void setSpinnerListener(Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
Spinner businessTypeSpinner = (Spinner) findViewById(R.id.businessTypeSpinner);
Spinner suburbSpinner = (Spinner) findViewById(R.id.suburbSpinner);
String businessType = businessTypeSpinner.getSelectedItem().toString();
if(businessType.contains("Private"))
{
businessType = "private user";
}
updateList(typeSpinner.getSelectedItem().toString(), suburbSpinner.getSelectedItem().toString(),
businessType, suburbSpinner.getSelectedItemPosition());
}
I wrote a simple program that will display an ArrayList and the user can select an item and delete it with a button.
If the user does not select an item but continues to hit the delete button, they will remove the first item on the ArrayList. How do I prevent this from happening? The delete button should only run when an item is selected, so I need to find a way to check for that
int positionID;
ListView listview;
ArrayList<String> valuesArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
valuesArray.add("a");
valuesArray.add("b");
valuesArray.add("c");
valuesArray.add("d");
valuesArray.add("e");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
positionID = (int) id;
}
});
}
public void onClickDelete(View v) {
//need to check if an item is selected. if so, run code below
valuesArray.remove(positionID);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
}
Based on the code you've provided, this is likely happening because the default initialized value for positionID is set to 0. To fix this, you could initialize int positionID = -1 and then in your onClickDelete method, do a check to make sure the positionID is not invalid. Like this:
public void onClickDelete(View v) {
if (positionID < 0) return;
// continue your code here
}
By the way, a few other things you should fix. You should actually interact with adapter directly, so instead of valuesArray.remove(positionID) you should do adapter.remove(positionID). This will automatically update the adapter and refresh the ListView for you so you can get rid of the last two lines of your onClickDelete method.
You can just make valuesArray a local variable in your onCreate method, unless you plan on manipulating it directly elsewhere in your code. If you choose to do that, you can call adapter.notifyDataSetChanged() to make the adapter refresh your ListView.
I am having a problem with ListViews and ArrayLists.
I have an ArrayList of items. Each item has info such as ID, Title, Price etc. I also have another ArrayList of allocations. These allocations contain an "ItemId" variable - so I plan to link this to item. (Without the use of a database.)
This is how I think I will do it. First of all I will convert my ArrayList of items into a ListView using AndroidStudio. When the user clicks on a specific item on this ListView, I will run an if statement (e.g if the Id of the selected item is 2, display the allocation with that itemId)
However there is a problem with this. I can't check the Id in this if statement because my ArrayList has already been converted to a ListView, which I can not search for specific data. Can anyone help me?
Here is the code I have at the moment:
public class ViewItems extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_items_layout);
ListAdapter itemAdapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1, Item.itemArrayList);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(itemAdapter);
itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String itemPicked = ????;
IF STATEMENT GOES HERE;
}});
}
}
You don't 'convert' your ArrayList into a ListView. The ListView merely uses the ArrayList to show your items - the ArrayList is still valid.
More precise, you add your items to the ArrayAdapter, which uses your exact ArrayList. You can use:
itemAdapter.getItem(i);
Complete example:
final ArrayAdapter<Item> itemAdapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1, Item.itemArrayList);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(itemAdapter);
itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Item itemPicked = itemAdapter.getItem(i);
IF STATEMENT GOES HERE;
}
});
Note that since you're putting instances of Item in your ArrayList, itemAdapter.getItem(i) will return an Item, not a String.
Use getItem of your ArrayAdapter
itemAdapter.getItem (i);
I am beginner in android and I am developing one module where user click on the AutocompleteTextView for the places. I have taken the code from the https://developers.google.com/places/training/autocomplete-android
Now i am able to get the Result in the form of List but i am not able to select the text from that autocomplete List.
![enter image description here][1]
As you can see i am getting the List but when i click on the selected list it's doing nothing means my setOnItemClickListener is not getting invoked.
My mainActivity code is like this
public class GoogleMap extends Activity{
private AutoCompleteTextView autoCompView;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
adapter = new PlacesAutoCompleteAdapter(this,R.layout.activity_google_map);
autoCompView.setAdapter(adapter);
autoCompView.setThreshold(1);
// when the user clicks an item of the drop-down list
autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "MultiAutoComplete: " +
"you add color "+arg0.getItemAtPosition(arg2),
Toast.LENGTH_LONG).show();
}
});
}
I'm not sure about the "PlacesAutoCompleteAdapter-Object", but if you're implementing an AutocompleteTextView it's enough to add an ArrayAdapter with the desired (and in this case possible) results:
String[] stringArray = { "Belgium", "France", "Italy", "Germany", "Spain"};
AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, stringArray);
autoCompView.setAdapter(adapter);
So if you're clicking on an item of the list, the selected item is automatically adopted to the textfield, no need for an OnClickListener.
For more information see http://developer.android.com/reference/android/widget/AutoCompleteTextView.html
If you want your code automatically do some stuff if an item is selected you can use TextWatcher: http://developer.android.com/reference/android/text/TextWatcher.html
final TextWatcher watcher = new TextWatcher(){
//Auto-generated methods & stuff...
};
autoCompView.addTextChangedListener(watcher);
Greetings
Here's how my app works. User records a sound and then gives it a certain name. In this example I'll be recording two sound files. Test1.mp3 and Test2.mp3. After I'm done recording for the first time, a dialog appears and I type in 'Test1', same goes for the second recording. Test1.mp3 and Test2.mp3 were now added to the listview. This is the code:
//filename is a variable for the name of the file, these lines execute everytime I record a new file
ArrayList<String> fileNames = new ArrayList<String>();
fileNames.add(filename.toString());
listView = (ListView) findViewById (R.id.mainListView);
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, fileNames);
listView.setAdapter(listAdapter);
So, after I've recorded both files and they're added to listview, I want to set onClickListeners to both listview elements. But how do I do it? How do I make it so that everytime a new recorded file has been added to the listview, it also automatically generates the onclick method. This wouldn't be as complicated but every recorded file, ofcourse, has a different path.
The code now:
//LISTVIEW
fileNames.add(filename.toString()); //adding each filename to ArrayList<String>
listView = (ListView) findViewById (R.id.mainListView);
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, fileNames);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast toast = Toast.makeText(getApplicationContext(), filename, Toast.LENGTH_SHORT);
toast.show();
}
});
This is the code that executes each time new file is recorded
You don't have to add a new listener every time you add an element to the list.
You can use a OnItemClickListener set once and for all, and you will be able to find the item that has been clicked by the index in the callback function
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
which is, parameter int position.
Inside onItemClick implementation, you can then retrieve the element which has been clicked by
arg0.getItemAtPosition(position)
Also, you don't have to add the onItemClickListener every time, you can just prepare it once in the onCreate method of your Activity and never change it.
What you will need to do instead, is making a new adapter (or adding a new item to the adapter) when your new file recording has terminated.
I prepared an almost full sample to show how to use the ListView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> fileNames = new ArrayList<String>();
fileNames.add("Test1.mp3");
fileNames.add("Test2.mp3");
final ListView listView = (ListView) findViewById (R.id.mainListView);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileNames);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Toast toast = Toast.makeText(getApplicationContext(),
(String)arg0.getItemAtPosition(position), Toast.LENGTH_SHORT);
toast.show();
}
});
}
This is enough if the items in the list do not change.
When a recording of your next mp3 file terminates, and you want to add an item to the list, you may just do:
ListView listView = (ListView) findViewById (R.id.mainListView);
fileNames.add("Test3.mp3");
((ArrayAdapter<String>)listView.getAdapter()).notifyDataSetChanged();
Replace "Test3" with your new recorded mp3's filename, and it will show up in the list.
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
switch(position){
case 0:
blablbla
break;
case1 1:
blabla
break;
/....
}
}):