Custom spinner is not invoke custom listview? - android

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();
}

Related

Multiple choice listview not showing all objects

I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview
The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());
I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end

Android Java: Unable to selectively highlight rows in a ListView via onScroll listener

I have another blocker as I study Android Development.
This time my problem is when I wanted to "selectively" highlight a row in a ListView populated by data from an adapter.
This ListView is actually within a dialog, and purpose is to show a list of friends, where user can multi-select and highlight it as he selects.
The selected values by the way, is stored in an ArrayList "arr_FriendsShare" so that the next time he opens the listview, rows will be highlighted (via onScrollListener) for those previously selected.
What is currently happening, only the "recently" or "last" clicked row/item is highlighted; and seems to be clearing all the previously highlighted rows.
I cannot understand why it is behaving that way, as row's value is successfully stored to/removed from arr_FriendsShare ArrayList, as I click on it.
Below is my listener codes, and thanks in advance for the usual help:
//Item click listener for Select Friends ListView
listview_SelectFriends.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String friends_ListItemSelected = (String)adapter.getItemAtPosition(position);
if(!arr_FriendsShare.contains(friends_ListItemSelected)){
arr_FriendsShare.add(friends_ListItemSelected);
}
else{
removeItemFromArrayListString(Main.this, arr_FriendsShare, friends_ListItemSelected);
}
}
});
listview_SelectFriends.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = firstVisibleItem; i < (visibleItemCount + firstVisibleItem); i++) {
String listViewItemText = view.getItemAtPosition(i).toString();
if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.red_light));
view.setSelector(cd);
}
else if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
view.setSelector(cd);
}
}
}
});
Additional Code Block:
ArrayList<String> stringArray = new ArrayList<String>();
String jsonURL = <SOME URL HERE>;
stringArray = Global.getStringArrayFromJSON(Main.this, jsonURL, "friends", "FriendUsername");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.friends_list_layout, null);
ListView listview_SelectFriends = (ListView) convertView.findViewById(R.id.layout_Friends);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
listview_SelectFriends.setAdapter(adapter);
Change
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
to
// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = new FriendsAdapter(Main.this, stringArray);
add this method in your activity
private void setResetSelection(int index, boolean setSelection){
View v = listview_SelectFriends.getChildAt(index);
if(v != null){
TextView name = (TextView) v.findViewById(R.id.name);
if(setSelection)
name.setBackgroundResource(R.color.red);
else
name.setBackgroundResource(R.color.transparent);
}
}
and create a new class as
public class FriendsAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> mFriends;
private ArrayList<String> mSelectedFriends = new ArrayList<String>();
public GoodPeopleAdapter(Context context, ArrayList<String> friends) {
mInflater = LayoutInflater.from(context);
mFriends= friends;
}
public void setSelectedFriends(ArrayList<String> selectedFriends){
mSelectedFriends = selectedFriends;
}
#Override
public int getCount() {
return mFriends.size();
}
#Override
public Object getItem(int position) {
return mFriends.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if(convertView == null) {
view = mInflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
String name = mFriends.get(position);
holder.name.setText(name);
if(mSelectedFriends.contains(name))
holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choice
return view;
}
private class ViewHolder {
public TextView name;
}
}
Add following line at the end of method onItemClick
adapter.setSelectedFriends(arr_FriendsShare);
Add this in the if part of onItemClick
setResetSelection(position, true);
and this in else part
setResetSelection(position, false);
Also create a new xml layout with name row_layout with a textview with id name.

Deleting the checked items in the listview

I want to make an app which includes a listView with check boxes and a two buttons named add and delete selected. I want to delete all the item that are checked in the list view.I am unable to do that despite of my lot of efforts. Any help would be appreciated.
Here is my code
package com.example.chkbokinlistview;
public class Adapter extends ArrayAdapter<Movies> {
ArrayList<Movies> data;
Context context;
int id;
private Holder h;
public Adapter(Context context, int textViewResourceId, ArrayList<Movies> objects) {
super(context, textViewResourceId, objects);
this.data = objects;
this.context = context;
this.id = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int p = position;
View v = convertView;
LayoutInflater l = ((Activity)context).getLayoutInflater();
h = new Holder();
if (v == null) {
v = l.inflate(id, parent, false);
h.tv = (TextView) v.findViewById(R.id.textView1);
h.cb = (CheckBox) v.findViewById(R.id.checkBox1);
v.setTag(h);
}else{
h = (Holder) v.getTag();
h.cb.setChecked(true);
}
h.tv.setText(data.get(position).movieName);
h.cb.setChecked(data.get(position).deleted);
return v;
}
public void delete(){
//how to delete all the items that are checked
}
class Holder{
TextView tv;
CheckBox cb;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
bDelete = (Button) findViewById(R.id.bDelete);
bAdd = (Button) findViewById(R.id.bAdd);
list = new ArrayList<Movies>();
a = new Adapter(this, R.layout.listitem, list);
lv.setAdapter(a);
bDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
a.delete();
}
});
bAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final EditText et = new EditText(MainActivity.this);
dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
list.add(new Movies(et.getText().toString(), false));
a.notifyDataSetChanged();
dialog.dismiss();
}
})
.setTitle("ADD Movie")
.setView(et)
.create();
dialog.show();
}
});
}
On checking the checkbox add that position in an ArrayList let say toBeDeleted, and when you click delete button, just remove items from your ArrayList named data according to the positions that you have in toBeDeleted and call the adapter method notifyDataSetChanged().
Add a checkedChangedListener in the getView method for your CheckBox.
h.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
// TODO Auto-generated method stub
if (arg1) {
list.add(position);
} else {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == position) {
list.remove(i);
break;
}
}
}
}
});
Where list is a ArrayList<Integer>,
and for deleting
private void delete() {
for(int i = 0 i<list.size;i++)
data.remove(list.get(i));
}
but before deleting you have to sort the list in decending order, in order to remove correctly, otherwise you may get an IndexOutofBoundException

Display ListView TextView based on count acting strange

I have a ListView that is being populated with collection of items using a custom adapter. One of the properties of the collection is a count, and I have two TextViews in my ListView layout, one for the text and one for the count. I'd like not to display the count TextView if the count is zero. The code I have works fine when the ListView is initially loaded, but when I scroll the ListView, the count will show on random rows and constantly change if scroll the ListView up and down. This is the code I have:
public class Main extends ListActivity
{
private static CustomAdapter adapter = null;
#Override
public void onCreate(Bundle icicle)
{
List<Item> items = new ArrayList<Item>();
items = GetItems();
adapter = new CustomAdapter();
for (Item item : items)
adapter.addItem(item);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
/* ADAPTER */
private class CustomAdapter extends BaseAdapter
{
private final List<Item> mData = new ArrayList<Item>();
private final LayoutInflater mInflater;
public CustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Item item) {
mData.add(item);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Item item = (Item)this.getItem(position);
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.main, parent, false);
holder.text = (TextView)convertView.findViewById(R.id.text);
holder.count = (TextView)convertView.findViewById(R.id.count);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.text.setText(item.getTitle());
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setVisibility(View.INVISIBLE);
return(convertView);
}
}
static class ViewHolder {
TextView text, count
}
Layout:
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
EDIT:
I was able to get it working by doing a hacky workaround. It seems setting the TextView's visibility to Invisible or Gone was causing the issue, so I just changed the color of the items with a zero count to the background color:
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setTextColor(Color.WHITE);
If anyone has a real fix, please let me know.
You should just do this:
if (item.getCount() > 0) {
holder.count.setText(item.getCount().ToString());
holder.count.setVisibility(View.VISIBLE);
}
else
holder.count.setVisibility(View.INVISIBLE);
Because you use a ViewHolder, you need to consider the fact that you might get an old View that's not showing the count. This means we need to make sure that the visibility of count is set to VISIBLE. Equally we want to hide it if the count is zero - so we change the visibility even though we might get a View that is all ready invisible.
I think you wrong a part of your code, Amend test this code:
if (item.getCount() > 0)
holder.count.setText(item.getCount());
else
holder.count.setVisibility(View.INVISIBLE);
Please go through this code you may helpful for the same.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
s = new ListAdapter(this, R.id.lv_user, mListUsers);
lvUsers.setAdapter(s);
lvUsers.setClickable(true);
// lvUsers.setTextFilterEnabled(true);
lvUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
Object o = lvUsers.getItemAtPosition(position);
UserBO obj = (UserBO) o;
Intent intent = new Intent(Select.this,Update.class);
intent.putExtra("pid", ""+obj.getId());
intent.putExtra("name", obj.getName());
//put data which you want to show and select.
startActivity(intent);
}
});
}
public ArrayList<UserBO> getUsers()
{
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
//Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM profiledatabase";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
try {
user.pid = Integer.parseInt(list.get(0));
//write code to get data from table
} catch (Exception e) {
//Log.i("***" + Select.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> {
// --CloneChangeRequired
private ArrayList<UserBO> mList;
// --CloneChangeRequired
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) {
// --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
}
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.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position);
// --CloneChangeRequired
if (listItem != null)
{
// setting list_item views
//( (TextView) view.findViewById(R.id.tv_pid) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.tv_name) ).setText( listItem.getName() );
( (TextView) view.findViewById(R.id.tv_email)).setText(listItem.getEmail());
( (TextView) view.findViewById(R.id.tv_contact) ).setText( listItem.getContact()+"" );
}}catch(Exception e)
{
//Log.i(Select.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}

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