I am getting the teams from an arraylist and show on a listview with their logos. It is working without problem. But I want to remove an item when I click long on a listview item with an yes - no alert dialog. Here is my codes and custom adapter.
package com.mesutemre.takimlarlistview;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class TakimBaseAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater = null;
private TextView lblAd, lblAciklama;
private ImageView imgTakim;
private ArrayList<Takim> items;
public TakimBaseAdapter(Context context, ArrayList<Takim> items) {
this.context = context;
this.items = items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.activity_main, null);
lblAd = (TextView) vi.findViewById(R.id.textView1);
lblAd.setTextColor(Color.BLUE);
lblAciklama = (TextView) vi.findViewById(R.id.textViewAciklama);
imgTakim = (ImageView) vi.findViewById(R.id.takimImage);
lblAd.setText(items.get(position).getTakim_ad());
lblAciklama.setText(items.get(position).getTakim_aciklama());
int logoID = context.getResources().getIdentifier(
items.get(position).getImage(), "drawable",
context.getPackageName());
imgTakim.setImageResource(logoID);
return vi;
}
}
And I put the items of ArrayList of teams in MainActivity and it is here;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*final ArrayAdapter<Takim> adapter = new TakimAdapter(this,
R.layout.activity_main, getTakimlar());*/
final BaseAdapter adapter = new TakimBaseAdapter(MainActivity.this, getTakimlar());
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
Takim stakim = (Takim) parent.getItemAtPosition(position);
Toast.makeText(getBaseContext(),
"Takım : " + stakim.getTakim_ad(), Toast.LENGTH_SHORT)
.show();
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long arg3) {
final Takim stakim = (Takim) parent.getItemAtPosition(position);
// burada AlertDialog.Builder'ın constructor'ına dikkat edin.
// Listactivitymizin context'ini atıyoruz.
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Bu takımı silmek istediğinizden emin misiniz?");
builder.setPositiveButton("Evet",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
getTakimlar().remove(which);
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Hayır",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
adapter.notifyDataSetChanged();
}
});
builder.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Takimlar ekleniyor
private ArrayList<Takim> getTakimlar() {
ArrayList<Takim> takimList = new ArrayList<Takim>();
takimList.add(new Takim("Galatasaray", "19", "galatasaray"));
takimList.add(new Takim("Fenerbahçe", "18", "fenerbahce"));
takimList.add(new Takim("Beşiktaş", "13", "bjk"));
takimList.add(new Takim("Trabzonspor", "6", "trabzon"));
takimList.add(new Takim("Bursaspor", "1", "bursaspor"));
return takimList;
}
}
I am getting ArrayOutofBound Exception because of getTakimlar().remove(which);. How can I remove an item from my ArrayList in this situation?
Try :
if (view == null || takimList.isEmpty()) {
} else {
takimList.remove(which);
adapter.notifyDataSetChanged();
}
Use takimList.remove(which);
instead of getTakimlar().remove(which);
Related
Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.
Activity
public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {
String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;
ImageView Ivseats;
public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_event_total_user_seats);
initviews();
callSeatsApi();
GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String a = String.valueOf(position);
Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
v.setBackgroundColor(Color.GREEN);
adapter.notifyDataSetChanged();
}
});
}
private void initviews() {
GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
GridUserSeats.setOnItemClickListener(this);
textView1=(TextView) findViewById(R.id.textView1);
// textView2=(TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
first_name = intent.getStringExtra("first_name");
last_name = intent.getStringExtra("last_name");
}
private void callSeatsApi() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("events", event_id);
RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
switch (mode)
{
case EM_SEATS:
EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
GridUserSeats.setAdapter(adapter);
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import cfirst.live.com.R;
import cfirst.live.com.model.BasketModel;
import cfirst.live.com.model.EM_event_total_UserSeatsModel;
public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private String[] mobileValuesD;
private static class ViewHolder {
TextView TvEmUserSeats;
ImageView IvUsreSeats,available,selctedimag;
}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
super(context, R.layout.list_em_get_seats, data);
this.dataSet = data;
this.mContext=context;
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(tagCollection[position]);
EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
EM_event_total_UserSeatsModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);
viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
String blue_available = "seat3.png";
String red_booked = "seat1.png";
String get_seat = dataModel.getBookedStatus();
viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
if(Integer.parseInt(get_seat) == 1){
Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);
}else
{
Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);
}
return convertView;
}
}
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:
public void toggleSelection(int item) {
if (selectedItems.get(item, false)) {
selectedItems.delete(item);
} else {
selectedItems.put(item, true);
}
notifyDataSetChanged();
}
public void setSelectedItems(List<Object> objects) {
if (objects != null) {
for (Object object : objects) {
toggleSelection(object.getId());
}
notifyDataSetChanged();
}
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<Integer>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.
SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();
After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.
// create an Arraylist and add the selected position in a list
List <int> selectedArray = new ArrayList<>();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int click = (int) parent.getItemAtPosition(position);
selectedArray.add(click);
}
I am developer a Apps which contain Various Name & Country List. I want to pass Employee Name & Country name to another activity on click on Child Item of Expandable ListView.
How to set On Click Listener Method on my Activity?
package nasir.main.activity;
import java.util.ArrayList;
import nasir.adapter.EntryItem;
import nasir.adapter.MyListAdapter;
import nasir.adapter.SectionItem;
import nasir.bd.poem.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
public class Employee_List extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
Button Collapse;
Button Expand;
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<SectionItem> section = new ArrayList<SectionItem>();
ArrayList<EntryItem> items = new ArrayList<EntryItem>();
ExpandableListView expandableList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poem_list);
expandableList = (ExpandableListView) findViewById(R.id.expandableList);
Expand = (Button) findViewById(R.id.Expand);
Collapse = (Button) findViewById(R.id.Collapse);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
Collapse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
Collapse.setVisibility(View.GONE);
Expand.setVisibility(View.VISIBLE);
}
});
Expand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
Expand.setVisibility(View.GONE);
Collapse.setVisibility(View.VISIBLE);
}
});
// display the list
displayList();
// expand all Groups
// expandAll();
collapseAll();
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
//method to Collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
}
// method to expand all groups
private void displayList() {
// display the list
load_Part_1_Data();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(Poem_List.this, section);
// attach the adapter to the list
myList.setAdapter(listAdapter);
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
Intent intent = new Intent(Poem_List.this, Details_Information.class);
startActivity(intent);
return false;
}
});
}
private void load_Part_1_Data() {
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.ic_launcher, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "Margerate Milan", "Computer Operator", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Abraham Jhon", "Salse Man", getString(R.string.app_name)));
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.blank_image, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "England", "Europe", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Japan", "Asia", getString(R.string.app_name)));
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.Class
package nasir.adapter;
import java.util.ArrayList;
import nasir.bd.poem.R;
import nasir.main.activity.Details_Information;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<SectionItem> continentList;
private ArrayList<SectionItem> originalList;
public MyListAdapter(Context context, ArrayList<SectionItem> continentList) {
this.context = context;
this.continentList = new ArrayList<SectionItem>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<SectionItem>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View view, ViewGroup parent) {
final EntryItem country = (EntryItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView Rank = (ImageView) view.findViewById(R.id.Rank);
TextView Poem = (TextView) view.findViewById(R.id.Poem);
TextView Poetry = (TextView) view.findViewById(R.id.Poetry);
Rank.setImageResource(country.getRank());
Poem.setText(country.getPoem().trim());
Poetry.setText(country.getPoetry().trim());
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Details_Information.class);
Bundle bundle=new Bundle();
intent.putExtras(bundle);
intent.putExtra("header", country.getDetails_Doc());
context.startActivity(intent);
}
});
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) {
SectionItem continent = (SectionItem) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
ImageView Group_icon = (ImageView) view.findViewById(R.id.Group_Icon);
Group_icon.setImageResource(continent.getIcon());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if (query.isEmpty()) {
continentList.addAll(originalList);
} else {
for (SectionItem continent : originalList) {
ArrayList<EntryItem> countryList = continent.getSectionList();
ArrayList<EntryItem> newList = new ArrayList<EntryItem>();
for (EntryItem country : countryList) {
if (country.getPoem().toLowerCase().contains(query) || country.getPoetry().toLowerCase().contains(query) ) {
newList.add(country);
}
}
if (newList.size() > 0) {
SectionItem nContinent = new SectionItem(continent.getIcon(), continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
In the Employee_List activity , you can access the data through index of child and group obtaining from ChildClickListener
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
//Here You can access the child data by
final EntryItem country = (EntryItem) listAdapter .getChild(arg2, arg3);
//From here you can pass the data through Intent
...
return false;
}
});
I've seen many examples of setOnLongClickListener in a ListView, but I'm using an AndroidHive's ExpandableListView, so it doesn't seem to recognized (error: setOnLongClickListener cannot be resolved to a type). How would I go about making it so that I can use setOnLongClickListener?
ExpandableListView expListView;
...
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
MainActivity.java (listener located in first method):
package com.example.groceryrunnerv4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition) .setPaintFlags(CHILD.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
return false;
}
});
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Adds food group data
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data groups
listDataHeader.add("Produce");
listDataHeader.add("Grains");
listDataHeader.add("Meat & Seafood");
listDataHeader.add("Frozen");
listDataHeader.add("Canned");
listDataHeader.add("Bakery");
listDataHeader.add("Beverages");
listDataHeader.add("Other");
// Adding child data items
List<String> Produce = new ArrayList<String>();
Produce.add("Chaquita Bananas");
Produce.add("Apples (8)");
Produce.add("Kiwi");
Produce.add("Romaine Lettuce (3)");
List<String> Grains = new ArrayList<String>();
Grains.add("Whole Grain Bread");
Grains.add("Whole Wheat English Muffins");
Grains.add("Pasta");
Grains.add("Oatmeal");
List<String> MeatSeafood = new ArrayList<String>();
MeatSeafood.add("My dead friends");
List<String> Frozen = new ArrayList<String>();
Frozen.add("Edamame");
Frozen.add("Bean Burgers");
List<String> Canned = new ArrayList<String>();
Canned.add("Amy's Lentils");
Canned.add("Jam");
Canned.add("Peanu Butter");
List<String> Bakery = new ArrayList<String>();
Canned.add("Fresh Bread");
List<String> Beverages = new ArrayList<String>();
Canned.add("Water");
listDataChild.put(listDataHeader.get(0), Produce);
listDataChild.put(listDataHeader.get(1), Grains);
listDataChild.put(listDataHeader.get(2), MeatSeafood);
listDataChild.put(listDataHeader.get(3), Frozen);
listDataChild.put(listDataHeader.get(4), Canned);
listDataChild.put(listDataHeader.get(5), Bakery);
listDataChild.put(listDataHeader.get(6), Beverages);
}
// Method for activity events
public void onButtonClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.CreateLG:
createLGPopup(v);
break;
case R.id.EditButton:
createEditButtonPopup(v);
break;
case R.id.SaveButton:
Toast.makeText(getApplicationContext(), "List saved.",
Toast.LENGTH_SHORT).show();
break;
case R.id.ListButton:
// chooseListDialog()
}
}
// findViewById(R.id.GetStarted).setVisibility(View.INVISIBLE);
// TextView text = (TextView) findViewById(R.id.GetStarted);
// text.setText(choice);
// CreateLG Button's Popup Menu
public void createLGPopup(View v) {
PopupMenu LGMenu = new PopupMenu(this, v);
LGMenu.getMenuInflater().inflate(R.menu.createlg_menu, LGMenu.getMenu());
LGMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Create List")) {
createListDialog();
}
else if (choice.equals("Create Group")) {
createGroupDialog();
}
return false;
}
});
LGMenu.show();
}
// Create Edit Button's Popup Menu
public void createEditButtonPopup(View v) {
PopupMenu EditMenu = new PopupMenu(this, v);
EditMenu.getMenuInflater().inflate(R.menu.editlist_menu, EditMenu.getMenu());
EditMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Edit List Name")) {
editListDialog();
}
else if (choice.equals("Clear All Items")) {
Toast.makeText(getApplicationContext(), "All list items deleted.",
Toast.LENGTH_SHORT).show();
}
else if (choice.equals("Delete List")) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText("Grocery Runner");
Toast.makeText(getApplicationContext(), "\"" + text.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
EditMenu.show();
}
// Create List Dialog
public AlertDialog.Builder dialogBuilder;
private void createListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new list");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list created.",
Toast.LENGTH_SHORT).show();
//add list to ListsButton
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
// Create Group Dialog
private void createGroupDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new group");
dialogBuilder.setMessage("Name your group: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
createGroup(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" group created.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
public void createGroup(String inputGroup){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data group
listDataHeader.add(inputGroup);
// Adding child data items
List<String> group = new ArrayList<String>();
Integer groupIndex = listDataHeader.indexOf(inputGroup);
listDataChild.put(listDataHeader.get(groupIndex), group);
}
// Create List Dialog
private void editListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Edit list name");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
}
ExpandableListAdapter.java:
package com.example.groceryrunnerv4;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
getExpandableListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPosition = ExpandableListView.getPackedPositionGroup(id);
int childPosition = ExpandableListView.getPackedPositionChild(id);
// You now have everything that you would as if this was an OnChildClickListener()
// Add your logic here.
// Return true as we are handling the event.
return true;
}
return false;
}
});
from Android: long click on the child views of a ExpandableListView?
I have a Listview of EditText and I need to get the String values of each edited row when I click a confirm button, but I don't know how.
I have tried to adapt some sample with no success ( I get always the default values and not the edited values).
My attempt is this
public class MyActivity extends Activity {
static int nItems;
ImageButton confirmButton;
ListView myList;
ListViewAdapterEditText adapterG1, adapterG2, adapterG3;
#Override
public void onCreate(Bundle savedInstanceState) {
.....
myList = (ListView) findViewById(R.id.listaG1);
myList.setItemsCanFocus(true);
adapterG1 = new ListViewAdapterEditText();
myList.setAdapter(adapterG1);
}
OnClickListener mConfirmButtonListener = new OnClickListener() {
public void onClick(View v) {
ArrayList a1 = adapterG1.getItems();
for (int i = 0; i < nItems; i++) {
System.out.println(a1.get(i)
+ "\n\n");
}
};
public class ListViewAdapterEditText extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItems = new ArrayList();
ListItem listItem;
public ListViewAdapterEditText() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < nItems; i++) {
listItem = new ListItem();
listItem.caption = "Caption" + i;
myItems.add(listItem);
}
notifyDataSetChanged();
}
public int getCount() {
return myItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<String> getItems() {
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < nItems; i++) {
ListItem li = (ListItem) myItems.get(i);
items.add(li.getCaption());
}
return items;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item_row,
null);
holder.caption = (EditText) convertView
.findViewById(R.id.ItemCaption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill EditText with the value you have in data source
holder.caption.setText(((ListItem) myItems.get(position)).caption);
// holder.caption.setText(myItems.get(position).caption);
holder.caption.setId(position);
// we need to update adapter once we finish with editing
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
}
}
});
return convertView;
}
class ViewHolder {
EditText caption;
}
class ListItem {
String caption;
public String getCaption() {
return caption;
}
}
}
}
Could someone help me to solve this problem?
Are you sure your OnFocusChangeListener is called? If you edit the text in EditText then tap the confirm button, this listener will not be called in touch mode since the focus is still on the EditText.
Update: Consider the situation you edited the text in a EditText while didn't confirm and scrolled the ListView so that the item view is recycled, I'm not sure what is your preferred way, but if you want store the edited data, you can use setRecyclerListener(android.widget.AbsListView.RecyclerListener) to get notified when a item view is recycled so you can saved the edit result. To save the result of EditText showing on screen, you use methods like getChildAt to get item views visible on screen then get the EditText's text.
Update2: Another better and clean way is use TextWatcher and addTextChangeListener, this will notifies you when the text in EditText is changed.
Update3: I just write the following sample and test it, and it works on my phone. :)
Update4: I removed the previous code cause its performance is bad and creates a lot objects, you can check the following full sample instead:
Activity code :
package com.example.asynctasktest;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
/**
* #author Daniel Chow
*
* May 26, 2013 12:57:49 AM
*/
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final TestAdapter adapter = new TestAdapter(this);
listView.setAdapter(adapter);
Button confirmButton = (Button) findViewById(R.id.confirm_button);
confirmButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
List<String> items = adapter.getItems();
for (int i = 0, n = items.size(); i < n; i++) {
Log.e("", items.get(i));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Adapter code:
/**
*
*/
package com.example.asynctasktest;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
/**
* #author Daniel Chow
*
* May 26, 2013 1:13:02 AM */
public class TestAdapter extends BaseAdapter {
private List<String> items = new ArrayList<String>();
private Context context;
public TestAdapter(Context context) {
this.context = context;
for (int i = 0; i < 12; i++) {
items.add("caption " + i);
}
}
public List<String> getItems() {
return new ArrayList<String>(items);
}
#Override
public int getCount() {
return 12;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = new EditText(context);
holder = new ViewHolder();
holder.editText = (EditText) convertView;
holder.watcher = new EditTextWatcher();
holder.editText.addTextChangedListener(holder.watcher);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.watcher.setTarget(position);
holder.editText.setText(items.get(position));
return convertView;
}
private class EditTextWatcher implements TextWatcher {
private int target;
public void setTarget(int target) {
this.target = target;
}
#Override
public void afterTextChanged(Editable s) {
items.set(target, s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
private static class ViewHolder {
EditText editText;
EditTextWatcher watcher;
}
}
I usually follow a simpler technique
public class Item_Adapter extends BaseAdapter {
private String[] Val;
public Item_Adapter () {
Val= new String[nItems];
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
///bla bla
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
Val[position]= Caption
.getText().toString();
}
}
});
///bla bla
return convertView;
}
/////most important returning your array so you can use it in the Activity
public String[] getVal() {
return Val;
}
I need some help to do a simple click in a listview item to open a new Activity. I have seen a lot of this kinda issues here but no one helped me.
public class CustomListView extends ListActivity {
private EfficientAdapter adap;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
adap = new EfficientAdapter(this);
setListAdapter(adap);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
startActivity(new Intent(CustomListView.this, next.class));
}
public static class EfficientAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Context context;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adaptor_content, null);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
}
});
convertView.setTag(holder);
}else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
...
}
}
I tried also adding the next code inside of onCreate method from CustomListView class but it doesn't work either
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startActivity(new Intent(CustomListView.this, next.class));
}
});
Remove the onListItemClick() from your CustomListView class and place the startActivity() method inside the convertView.setOnClickListener().
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), two.class));
}
});
Try this code. I am sure It is gonna help you and dont set class to an xml file like this;
setContentView(R.layout.second);
make sure that you did put that code above in your class, else you are gonna get an error while openin a new activity.
package com.exampled.list;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String [] names ={
"Iphone",
"Samsung",
"Nokia",
"Ericsson",
"BlackBerry",
"Benq"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,names));
}
public void onListItemClick(ListView Parent, View v, int position,long id){
startActivity(new Intent(MainActivity.this, Second.class));
//Toast.makeText(this, "Clicked on : " + names[position], Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In you code one.this refers to the Context.
Since your Activity's name is CustomListView, you should write CustomListView.this instead of one.this.
You could also use getApplicationContext().
Try putting the startActivity(new Intent(one.this, two.class));-code into
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {...}
});
What does one.this refer to? It should be a Context