Android how simple remove list item from listview? - android

i have a list of folder in directory, on onListItemClick event calling show alert dialog and after click on yes button i processing delete of the file. I would like after successful delete of the file also remove selected item from list or refresh view with new values.
How can i do it most simple?
Code of Package activity:
public class PackageListActivity extends ListActivity
{
// create instance of App helper class
AppHelper helper = new AppHelper();
String folderNameToDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get arrayListOf folders
ArrayList<String> folderArrayList = helper.getListOfFileInDirectory(null);
// convert array listo to simple array
String[] arr = folderArrayList.toArray(new String[folderArrayList.size()]);
// set to aray adapter
setListAdapter(new PackageArrayAdapter(this, arr));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
//Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
this.showAlerDialog(selectedValue);
}

remove the arraylist item by giving the position to be removed and then call notifyDataSetChanged() method by using your adapter
folderArrayList.remove(<index of element to remove>);
PackageArrayAdapter.notifyDataSetChanged();

Related

how do I open different XMLs for various listview items?

I have generated a list using array adapters and listview. Now i want a XML layout to open up each time i click on a list item. The layout format of all XMLs should be same,but the data in each XML should be different(for different list items).
How do i go about it?
Here is the code
public class handgunsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handguns);
ArrayList<String> hg=new ArrayList<String>();
hg.add("M1911");
hg.add("Desert Eagle .50");
hg.add("Glock 17");
hg.add("Sig P226");
hg.add("Browning High-Power");
ArrayAdapter<String> item=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,hg);
final ListView list=(ListView)findViewById(R.id.root);
list.setAdapter(item);
Add item click listener to your list, then get the selected item and pass it where ever you want to
list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// Here is the data, pass it any where
String item = (String) list.getItemAtPosition(position);
}
});

Android - Updating listview based on spinner choice doesn't work

While there are many questions relating to this subject here on stackoverflow, I can say I've looked through many of them and tried different things, but still I don't get it to work.
I have a ListView which I populate with a custom Adapter of custom classes I've created. I also have a spinner, which I'm trying to use as a filter for the list.
This is my simplified code, I removed everything that isn't relevant here make it clearer as possible, also simplifying some of the variable names:
public class OnlineNavActivity extends AppCompatActivity {
private ListView tourList;
private ArrayList<Tour> toursData;
private Spinner filterSpinner;
private TourAdapter tourAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tours_online);
// Set up the spinner
filterSpinner = (Spinner) findViewById(R.id.country_spinner);
addItemsToSpinner();
filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) { // if string does not equal to "All Countries"
toursData = Data.listByFilter(selectedCountry);
}
else {
toursData = Data.dataList;
}
tourAdapter = new TourAdapter(getApplicationContext(), toursData);
tourAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
toursData = Data.dataList;
tourAdapter = new TourAdapter(getApplicationContext(), toursData);
tourAdapter.notifyDataSetChanged();
}
});
// Assign all of the data to the array at first, will change by filter spinner
toursData = Data.dataList;
// Generate the list view
tourList = (ListView) findViewById(R.id.online_nav_list);
tourAdapter = new TourAdapter(this ,toursData);
tourList.setAdapter(tourAdapter);
}
(The Data.listByFilter() is the method I've created in a different class which returns an ArrayList with the applied filter).
The problem is that when I click on the spinner and select an item - nothing happenes.
I have tried to use tourAdapter.clear() and then adding the items with add command but that didn't work (The ListView became empty for any selection in the spinner).
Adding items to the adapter worked as items were added to the ListView and updated there, but this is not what I need, just something that worked while I was trying to figure this out.
Thanks.
Edit:
After trying many things, I finally find a solution. While it doesn't seem like an optimal solution, since I declare a new TourAdapter on every spinner action, this is the only one that worked for me.
What I did, is declaring a new TourAdapter and then calling setAdapter.
Also, I have left onNothingSelected as an empty method. This is what it looks like (all the other code remains the same):
filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) { // if string does not equal to "All Countries"
toursData = Data.listByFilter(selectedCountry);
Log.i(LOG_TAG, "first country is" + toursData.get(0).getCountry());
}
else {
toursData = Data.dataList;
}
tourAdapter = new TourAdapter(getApplicationContext() ,toursData);
tourList.setAdapter(tourAdapter);
//tourAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
The problem is you are creating a new adapter (new TourAdapter(...) within onItemSelected and onNothingSelected methods) every time you click on the Spinner and this adapter is not linked to your list.
In this two methods, instead of creating a new one, you should get the adapter the list already has (you set it with tourList.setAdapter), create a method on the adapter that set the new elements on it and update the list with notifyDataSetChange.
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) {
toursData = Data.listByFilter(selectedCountry);
} else {
toursData = Data.dataList;
}
tourAdapter = ((TourAdapter) tourList.getAdapter()).setNewElements(toursData);
tourAdapter.notifyDataSetChanged();
The setNewElements should be a method in the adapter like this:
public void setNewElements(List<Tour> newElementsList) {
this.myElements = newElementsList;
}
***** Edit *****
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
toursData.clear();
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) {
toursData.addAll(Data.listByFilter(selectedCountry));
}
else {
toursData.addAll(Data.dataList);
}
tourAdapter.notifyDataSetChanged();

listView having link of webpage as a item of that list

How to add Links on ListView in android? i.e. whenever if I select a list item it open a relative website. for Example I have a list in which there are some items like google,fb,twitter. whenever I click on google it will open google home page and so on.
this is my code please suggest me some code to do this task.
String[] names = new String[] {"Dainik Bhaskar","google"};
ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,android.R.id.text1, names);
//ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,R.id.webView1,names);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
// TODO Auto-generated method stub
if(names[pos].equals("Dainik Bhasker"))
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.bhaskar.com")));
}
else if(names[pos].equals("google"))
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com")));
}
}
Assuming that it's your complete code I don't see:
Where you get reference to the ListView with findViewById(R.id.YOUR_LIST_ID).
See an example of ListView here
The solution is very simple, you just have to add the property android:autoLink to the TextView associated with listview item.

Insert value for items in listview

I have already created a listview with the codes as below that displays apple, orange and banana. When I click on the item (Eg: apple) I want it to be displayed in a different activity as a textview along with the value. Eg: apple = 40 cal. For now I do not have a database to store these values.
This is the code for the listview :
public class ViewMenuList extends ListActivity {
String[] food = { "Apple", "Banana", "Orange"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_list);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, food));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this, "You have selected " + food[position] , Toast.LENGTH_LONG).show();
}
}
You can do a couple different things then. You can simply pass the value using an Intent
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this, "You have selected " + food[position] , Toast.LENGTH_LONG).show();
String name = food[position];
Intent i = new Intent(CurrentActivityName.this, NextActivityName.class);
i.putExtra("foodName", name);
startActivity(i);
}
then retrieve it in the next Activity in onCreate()
Intent intent = getIntent();
String foodName = intent.getStringExtra("foodName");
Then call setText(foodName) on your TextView in the next Activity
You also could store the information in SharedPreferences or in a static variable in a different class that would hold associated information with the food item.

Android: Spinners loose their values when I add dynamically new ListView entries on click of spinner item?

I am developing android apps. In my apps having two activities, first activity is displaying list and in second activity having spinner and listview in the same activity and when user click on the item from spinner the listview will be displayed. when user navigate from first activity to second activity then spinner is properly populated with listview. but problem is that after listview displayed properly then spinner item was blank. I don't know where i am doing wrong. Please anybody have solution.
Here i am posting few code of Second Activity
public class ProjectDetailActivity extends SherlockListActivity {
private List<String> list = new ArrayList<String>();
private ArrayList<HashMap<String, String>> list2 = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_detail);
//get spinner item from server when user comes from first activity.
new LoadPhaseData().execute();
//Listener for Phase spinner
projSpinnerPhase.setOnItemSelectedListener((OnItemSelectedListener) new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
//get listview when user click item from spinner
new LoadPhaseData().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
//this adapter for listview when click item from spinner
ListAdapter phaseAdapter = new SimpleAdapter(getApplicationContext(),
list2, R.layout.phase_avail_list_item,
new String[] {PHASE_NAME}, new int[]
{R.id.phaseName});
setListAdapter(phaseAdapter);
}
private class LoadPhaseData extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
//Here I am calling web service for spinner and listview
}
#Override
protected void onPostExecute(Void result) {
//following adapter for spinner item
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getApplicationContext(),android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
projSpinnerPhase.setAdapter(dataAdapter);
}
}
}
Thanks in advance
This is because you are assigning new Adapter to the Spinner with new values while you are adding new rows to Spinner. Spinner losses its previous row along with the previous data and get another Adapter with new data rows. You need to append these value to the existing data-holder (may be an array or ArrayList) and then call the adapter.notifyDataSetChanged();
You need to move ArrayList to the class-level, (i.e make it class field) then while you have downloaded data. just append new data to the list and call adapter.notifyDataSetChanged();

Categories

Resources