How to get a String-Array of the whole ListView - android

I have a ListView with dynamically added TextViews and how do I get all TextView objects of the ListView in a String-Array ?
For testing I would like to display the whole String-Array in my Toast in the onItemClickmethod
onCreate:
final ListView sessionLv = (ListView) findViewById(R.id.session_list);
sessionLv.setAdapter(sessionAdapter);
sessionLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView c = (TextView) view.findViewById(R.id.stepTime);
String playerChanged = c.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(),
playerChanged +" wurde angeklickt!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
The adapter for the dynamically added TextView objects in my ListView
class SessionItemAdapter extends ArrayAdapter<Map> {
ArrayList<Map> values;
Context context;
SessionItemAdapter(Context context, ArrayList<Map> values) {
super(context, R.layout.session_list_layout_row, values);
this.values = values;
this.context = context;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.session_list_layout_row, parent, false);
TextView tv = (TextView) rowView.findViewById(R.id.stepTime);
final int rowId = (Integer) values.get(position).get("id");
int beepStringId = getResources().getIdentifier("exercise_typ_" + values.get(position).get("type"), "string", getPackageName());
rowView.setTag(rowId);
tv.setText(getResources().getString(beepStringId));
ImageButton deleteSession = (ImageButton) rowView.findViewById(R.id.session_item_del);
deleteSession.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*if (!startStopToggle.isChecked()) {*/
sessionAdapter.remove(values.get(position));
sessionAdapter.notifyDataSetChanged();
}
});
return rowView;
}

Hope this will help,
//in your item click
sessionLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SessionItemAdapter adapter = (SessionItemAdapter) parent.getAdapter();
List<String> allPlayers = adapter.getAllPlayers();
// Log your list or whatever you want to do with it
Log.i(TAG, "allPlayers: " + allPlayers.toString());
}
});
//in your adapter getAllPlayers() would be something like this
public List<String> getAllPlayers(){
List<String> list=new ArrayList<String>();
for (Map item : values) {
int beepStringId = context.getResources().getIdentifier("exercise_typ_"
+ item.get("type"), "string", context.getPackageName());
String str = context.getResources().getString(beepStringId);
list.add(str);
}
return list;
}

Related

Set checkBox in CustomAdapter Visible by clicking on ListView Element in Fragment

is it possible to call a method in my CustomAdapter to set a checkbox Visible/Gone by clicking on an Element on my Fragments Listview? Ive got those two methods:
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
But How do I access them from my Fragment? Or do I have do chose another way?
(I want to set the checkbox visible by after "long click" on one of the ListView Elements)
Fragment:
public class ListViewFragment extends Fragment {
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
Log.d("DATALIST", dataListArray[0]);
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
((MainActivity) getActivity()).fabmain.animate().translationY(300);
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
((MainActivity) getActivity()).fabmain.animate().translationY(0);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
listViewOk = true;
setFabsVisible(roomNrOk, locationOk, true);
setFabdeleteVisible(listViewOk);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
(CustomListAdapter).setCheckBoxSelectItemVisible();
return true;
}
});
[...]
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
[...]
}
CustomAdapter:
class CustomListAdapter extends ArrayAdapter<String> {
String doubleTab = "\t\t";
CheckBox checkBoxSelectItem;
public CustomListAdapter(Context context, String[] dataListFinal) {
super(context, R.layout.list_item_datalist ,dataListFinal);
}
public String allElementsAdapter = "";
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
return customView;
}
public String getAllElements(){
return allElementsAdapter;
}
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
}
first change your Custom Adapter constructor with following
ArrayList<Boolean> mIsVisible;
public CustomListAdapter(Context context, String[] dataListFinal,ArrayList<Boolean> isVisible) {
super(context, R.layout.list_item_datalist ,dataListFinal);
mIsVisible = isVisible;
}
then modify getView()
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
if(mIsVisible.get(position)){
checkBoxSelectItem.setVisibility(View.VISIBLE);
}else{
checkBoxSelectItem.setVisibility(View.GONE);
}
return customView;
}
After that modify your activity CustomAdapter creation part
final ArrayList<Boolean> isVisible=new ArrayList<Boolean>();
for(int count =0 ;count<dataListArray.length; count++){
isVisible.add(false);
}
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray, isVisible);
And last modify listener part
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(isVisible.get(position))
isVisible.set(position,false);
else
isVisible.set(position,true);
dataListAdapter.notifyDataSetChanged();
return true;
}
});
Done...!!!!!
It works with ((BaseAdapter)dataListAdapter).notifyDataSetChanged();

How do i get the name of the clicked item of the ListView?

How do I get the name of the clicked item of the ListView ?
public void addExercise(View view) {
LayoutInflater mInflater = LayoutInflater.from(this);
final View exercises = mInflater.inflate(R.layout.exercises, null);
final Spinner spinner = (Spinner) exercises.findViewById(R.id.sessionTypeSpinner);
final ListView listView = (ListView) exercises.findViewById(R.id.listViewexercises);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter2 = new CustomListViewAdapter(getApplicationContext(),
R.layout.exercises_custom_row, rowItems);
listView.setAdapter(adapter2);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
final ListView listView = (ListView) exercises.findViewById(R.id.listViewexercises);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(getApplication(),
R.layout.exercises_custom_row, rowItems);
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
int arme = workoutDBAO.addSession(workoutId, position);
Map newRow = new HashMap();
newRow.put("id", arme);
newRow.put("type", 10 + position);
sessionAdapter.add(newRow);
}
});
break;
case 1:
ListView listView1 = (ListView) exercises.findViewById(R.id.listViewexercises);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles1.length; i++) {
RowItem item = new RowItem(images[i], titles1[i], descriptions[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter1 = new CustomListViewAdapter(getApplication(),
R.layout.exercises_custom_row, rowItems);
listView1.setAdapter(adapter1);
// ListView Item Click Listener
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ArrayList<RowItem> title = rowItems;
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + title.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
new AlertDialog.Builder(this)
.setTitle(R.string.action_add_step)
.setView(exercises)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int exerciseNr = spinner.getSelectedItemPosition();
}
}).show(); //
}
//OnClick on Item that you created
class ListViewItemClickHandler implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item was clicked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
class SessionItemAdapter extends ArrayAdapter<Map> {
ArrayList<Map> values;
Context context;
SessionItemAdapter(Context context, ArrayList<Map> values) {
super(context, R.layout.session_list_layout_row, values);
this.values = values;
this.context = context;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.session_list_layout_row, parent, false);
TextView tv = (TextView) rowView.findViewById(R.id.stepTime);
final int rowId = (Integer) values.get(position).get("id");
int beepStringId = getResources().getIdentifier("exercise_typ_" + values.get(position).get("type"), "string", getPackageName());
rowView.setTag(rowId);
tv.setText(getResources().getString(beepStringId));
ImageButton deleteSession = (ImageButton) rowView.findViewById(R.id.session_item_del);
deleteSession.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*if (!startStopToggle.isChecked()) {*/
sessionAdapter.remove(values.get(position));
sessionAdapter.notifyDataSetChanged();
}
});
return rowView;
}
I want to show it in the Toast that is in the OnItemClickmethod of the ListViewItemClickHandler class.
So I think somehow there I must get the name of the clicked item to show it but I don't know how so please help me!
Edit
My RowItem class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Try this:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position).getTitle(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}

Custom spinner is not invoke custom listview?

I have a custom listview and spinner.First of all i am filling the listview and then i am clicking dropdown spinner.I am choosing a item(city).I want to update listview with new result.But whatever i can custom adapter getview is not call. So listview is not update. This is my screen
How can i do it?
I am filling spinner here
private void getCityListWithSpinner() {
cityListRequest = new CityListRequest(new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
System.out.println("Objemizzz " + obj.toString());
cityArrayList = (ArrayList<CityList>) obj;
Spinner ss = (Spinner) findViewById(R.id.cityfilmspinner);
CinemaCitySelector2 citySelector = new CinemaCitySelector2();
cityList.add("Seçiniz");
for (int i = 0; i < cityArrayList.size(); i++) {
cityList.add(cityArrayList.get(i).getCinemaCity());
citySelector.CinemaCitySelector2(
CinemaCityMoviePickerActivity.this, ss, cityList,2);
}
}
CinemaCitySelector:
public class CinemaCitySelector2 implements OnItemSelectedListener {
Context context2;
Spinner spinner2;
CityListInCityRequest cityListInCityRequest2;
ArrayList<Cinema> cityListInCityArrayList2;
ListView list_cinema_movie_selectorr2;
CinemaListViewAdapter2 adapter2;
View row2;
int act2 = 0;
Spinner cityspinner;
public void CinemaCitySelector2(Context context, Spinner spinner,
ArrayList<String> cityList, int activityfrom) {
this.context2 = context;
this.spinner2 = spinner;
act2 = activityfrom;
// Declaring an Adapter and initializing it to the data pump
ArrayAdapter adapter = new ArrayAdapter(context,
android.R.layout.simple_list_item_1, cityList);
// Setting Adapter to the Spinner
spinner.setAdapter(adapter);
// Setting OnItemClickListener to the Spinner
spinner.setOnItemSelectedListener(CinemaCitySelector2.this);
}
// Defining the Callback methods here
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
String city = spinner2.getItemAtPosition(pos).toString();
LayoutInflater layoutInflater = LayoutInflater.from(context2);
row2 = layoutInflater.inflate(
R.layout.activity_cinemacitymoviepicker, null, false);
list_cinema_movie_selectorr2 = (ListView) row2
.findViewById(R.id.listfilmincinema);
if (!city.equals("Seçiniz")) {
cityListInCityRequest2 = new CityListInCityRequest(
new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
// adapter.clear();
// adapter.notifyDataSetChanged();
// list_cinema_movie_selector.setAdapter(adapter);
System.out.println("Objemizzz " + obj.toString());
cityListInCityArrayList2 = (ArrayList<Cinema>) obj;
// adapter.notifyDataSetChanged();
adapter2 = new CinemaListViewAdapter2(context2,
R.layout.cinema_list,
cityListInCityArrayList2);
list_cinema_movie_selectorr2
.setAdapter(adapter2);
}
#Override
public void asyncOperationFailed(Object obj, int queue) {
// TODO Auto-generated method stub
System.out.println("Objemizzz2 " + obj.toString());
}
}, city);
}
}
public void onNothingSelected(AdapterView arg0) {
// TODO Auto-generated method stub
}
}
CinemaListViewAdapter2:
public class CinemaListViewAdapter2 extends ArrayAdapter<Cinema> {
Context context;
int arraycount=0;
public CinemaListViewAdapter2(Context context, int resourceId,
ArrayList<Cinema> items) {
super(context, resourceId, items);
this.context = context;
arraycount=items.size();
}
/*private view holder class*/
private class ViewHolder {
BlackBrandTextview cinemaName;
RelativeLayout cinemalist;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Cinema rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.cinema_list, null);
holder = new ViewHolder();
holder.cinemaName = (BlackBrandTextview) convertView.findViewById(R.id.txt_cinema_name);
holder.cinemalist=(RelativeLayout)convertView.findViewById(R.id.cinemalist);
holder.cinemaName.setText(rowItem.getCinemaName());
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
holder.cinemaName.setText(rowItem.getCinemaName());
}
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
holder.cinemaName.setText(rowItem.getCinemaName());
return convertView;
}
I'd create a method to update the adapter once an item on your spinner is chosen:
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
city = (String) parent.getItemAtPosition(position);
resetCinema(city); //or onRestart();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
And resetCinema(city) rechages the view depending on the city value. You can do this manually:
public void resetCinema(String city) {
//show list view elements depending on city
}
or just call a refresh of the whole Activity:
protected void onRestart() {
Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
}
I suggest you to call
adapter2.notifyDataSetChange();
But anyway there is no need to initialize a new adapter every time.
you should create a method inside the adapter like this:
public void setMyArray(ArrayList<Cinema> items) {
myArray.clear();
myArray.addAll(items);
notifyDataSetChange();
}

ListView pull to refresh, I can only click on the first item, why?

I am using this library : https://github.com/erikwt/PullToRefresh-ListView
I implement my PullToRefresh-ListView with my custom Adapter. Here is the result :
My problem is the next : I can only click on the first item (Title 1, Description 1), the others doesn't work. Here is my code for the onClickItem :
myAdapter = new ListToRefreshAdapter(this, R.layout.list_item, myItemList);
myList = (PullToRefreshListView) findViewById(R.id.refreshList);
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Context context = view.getContext();
TextView title = (TextView) view.findViewById(R.id.titleItem);
TextView desc = (TextView) view.findViewById(R.id.descItem);
String titleItem = title.getText().toString();
String descItem = desc.getText().toString();
Toast.makeText(context, "Item Title: " + titleItem + ", Item Desc: " + descItem, Toast.LENGTH_SHORT).show();
Log.i("TOUCH EVENT TEST", "OK");
startActivity(new Intent(getApplicationContext(), ItemDetails.class));
}
});
Here is my adapter :
public class ListToRefreshAdapter extends ArrayAdapter<ItemObject> {
protected Context myContext;
protected int resId;
protected ItemObject[] myListdata = null;
protected LayoutInflater myInflater = null;
public ListToRefreshAdapter(Context myContext, int resId, ItemObject[] myListData) {
super(myContext, resId, myListData);
this.myContext = myContext;
this.resId = resId;
this.myListdata = myListData;
myInflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = myInflater.inflate(resId, null);
}
TextView title = (TextView) convertView.findViewById(R.id.titleItem);
TextView desc = (TextView) convertView.findViewById(R.id.descItem);
ImageView imgItem = (ImageView) convertView.findViewById(R.id.imgItem);
ItemObject itemObject = myListdata[position];
title.setText(itemObject.itemTitle);
desc.setText(itemObject.itemDesc);
imgItem.setBackgroundResource(R.drawable.item_no_picture);
return convertView;
}
}
Anybody has an idea of what I'm doing wrong ? Is it the library or my implementation ?
Thank you for answers :)
I found the answer. My ListView was in a FrameLayout. I change it with a LinearLayout and it works.
Thank you !

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..

Categories

Resources