Detecting a ListView click in a custom adapter - java

I have a created a ListView with a custom layout showing the users saved on Parse.com
This is the code for the custom adapter I have created
public class StatusAdapter extends ArrayAdapter {
protected Context mContext;
protected List mStatus;
public StatusAdapter(Context context, List status) {
super(context, R.layout.usertem, status);
mContext = context;
mStatus = status;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.usertem, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView
.findViewById(R.id.userName);
holder.statusHomepage = (TextView) convertView
.findViewById(R.id.userEmail);
holder.proPic = (ParseImageView) convertView
.findViewById(R.id.medopic);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseUser statusObject = (ParseUser) mStatus.get(position);
// title
String username = statusObject.getString("name");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getEmail();
holder.statusHomepage.setText(status);
ParseFile picc = statusObject.getParseFile("profile_picture");
holder.proPic.setParseFile(picc);
holder.proPic.loadInBackground();
return convertView;
}
public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
ParseImageView proPic;
}
}
But the problem I have is that I want to listen to list item clicks where my activity extends simple activity not List Activity this is my activity
public class UsersList extends Activity {
private ParseQueryAdapter<ParseObject> mainAdapter;
protected List<ParseUser> mUsers;
ListView listhope;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users_list);
listhope = (ListView) findViewById(R.id.userlistlist);
ParseQuery<ParseUser> query = new ParseQuery<ParseUser>("_User");
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> list, ParseException e) {
if (e == null) {
mUsers = list;
StatusAdapter adapter = new StatusAdapter(listhope.getContext(), mUsers);
listhope.setAdapter(adapter);
} else {
}
}
});
}
[...]
Please help fast

In your onCreate write
listhope.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//position is the row on which the user has clicked
ParseUser parseUser=mUsers.get(position);
//now you have the objext parseUser and this objects is what you needed.
}
});

Related

Checkbox not saving when reopening

I have 3 classes relating to my checkbox section of my app in Android studio, atm the check box loads, but when selecting and deselecting the value doesn't save when I go bak into it from the main menu. any help would great!!!
public class WatchList extends AppCompatActivity {
ArrayList dataModels;
ListView listView;
private WatchListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("watchlist", "created watchlist activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch_list);
listView = (ListView) findViewById(R.id.listview2);
dataModels = new ArrayList();
dataModels.add(new WatchListClass(R.drawable.kookaburra,"Kookaburra","Albury", false));
dataModels.add(new WatchListClass(R.drawable.cockatoo, "Cockatoo" , "Bathurst", true));
dataModels.add(new WatchListClass(R.drawable.emu,"Emu", "Echuca", true));
dataModels.add(new WatchListClass(R.drawable.magpie, "Magpie", "Sydney", true));
adapter = new WatchListAdapter(dataModels, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
WatchListClass dataModel= (WatchListClass) dataModels.get(position);
dataModel.checked = !dataModel.checked;
adapter.notifyDataSetChanged();
}
});
}
}
public class WatchListAdapter extends ArrayAdapter {
private ArrayList dataSet;
Context mContext;
private static class ViewHolder {
TextView birdWatchName, birdWatchLocation;
ImageView birdWatchImage;
CheckBox checkBox;
}
public WatchListAdapter(ArrayList data, Context context) {
super(context, R.layout.watch_list, data);
this.dataSet = data;
this.mContext = context;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public WatchListClass getItem(int position) {
return (WatchListClass) dataSet.get(position);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.watch_list, parent, false);
viewHolder.birdWatchImage = (ImageView) convertView.findViewById(R.id.birdWatchImage);
viewHolder.birdWatchName = (TextView) convertView.findViewById(R.id.birdWatchName);
viewHolder.birdWatchLocation = (TextView) convertView.findViewById(R.id.birdWatchLocation);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
WatchListClass item = getItem(position);
viewHolder.birdWatchImage.setImageResource(item.birdWatchImage);
viewHolder.birdWatchName.setText(item.birdWatchName);
viewHolder.birdWatchLocation.setText(item.birdWatchLocation);
viewHolder.checkBox.setChecked(item.checked);
return result;
}
}
public class WatchListClass {
public String birdWatchName, birdWatchLocation;
int birdWatchImage;
boolean checked;
WatchListClass(int birdWatchImage, String birdWatchName,String birdWatchLocation, boolean checked) {
this.birdWatchName = birdWatchName;
this.birdWatchLocation = birdWatchLocation;
this.birdWatchImage = birdWatchImage;
this.checked = checked;
}
}
u can user shared preferences for check Box
try this one
How to save checkbox value with shared preferences?
you can use local database in app to store check box values and retrieve it back.

adding url to list view

I am creating an app in android studio.
I need to update the list view with a new url that is sent via text message.
How do I add the new url to my list?
This is what I currently have for my main code.
public class MainActivity extends AppCompatActivity {
ListView list;
WebView webView;
ArrayList<String> sites = new ArrayList<>("https://www.google.com", "https://www.yahoo.com", "https://www.apple.com");
String [] url = {"https://www.google.com", "https://www.yahoo.com", "https://www.apple.com"};
MyBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listview);
MyListAdapter adapter = new MyListAdapter(this, sites);
sites.add("new site");
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setDividerHeight(5);
webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient(){});
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
Toast.makeText(getApplicationContext(), sites.get(position), Toast.LENGTH_SHORT).show();
webView.loadUrl("https://www.google.com");
webView.loadUrl(url[position]);
}
});
receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver,filter);
}
}
This is myAdapterList:
public class MyListAdapter extends ArrayAdapter<String> {
private Activity context_;
private ArrayList<String> sites;
//constructor
public MyListAdapter(Activity context, ArrayList<String> sites){
super(context,R.layout.row,sites);
context_ = context;
this.sites = sites;
}
public View getView (int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater inflater = context_.getLayoutInflater();
convertView = inflater.inflate(R.layout.row,null);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if(holder == null){
holder = new ViewHolder(convertView);
holder.tv_link.setText(sites.get(position));
}
else{
holder.tv_link.setText(sites.get(position));
}
return convertView;
}
private class ViewHolder{
TextView tv_link;
public ViewHolder(View row){
tv_link = (TextView) row.findViewById(R.id.tv_link);
}
}
}

Get parent layout from custom Adapter

Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.

Dynamically loading data to a new view

First im loading the data dynamically to a grid which is in the PMenu.java, then each item has view more button. once I pressed that I want to load the image, name and its amount in the item description view.
Im using a custom grid to load data to the grid in PMenu.java, and I have placed a button in the custom grid, so that it will navigate to viewmore.java.
I want to know once i press the button then how to load the data to viewmore.java file
PMenu.java fragment
GridView grid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_grid_main, container, false);
new PMenuAsyncTask(getActivity(), this).execute();
grid = (GridView) view.findViewById(R.id.grid);
return view;
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> descriptions = new ArrayList<String>();
List<String> imageUrls = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
Log.i("ImageURL ", object.getString("ImageURL"));
imageUrls.add(object.getString("ImageURL"));
Log.i("Description ", object.getString("Description"));
descriptions.add(object.getString("Description"));
}
}
CustomGrid adapter = new CustomGrid(getActivity(), descriptions,
imageUrls);
grid.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomGrid class
public class CustomGrid extends BaseAdapter {
private Context context;
private final List<String> descriptions;
private final List<String> imageUrls;
public CustomGrid(Context c, List<String> descriptions, List<String> imageUrls) {
this.context = c;
this.descriptions = descriptions;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return descriptions.size();
}
#Override
public Object getItem(int position) {
return descriptions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.fragment_pizza, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position)).into(holder.ivImage);
Button backButton = (Button) convertView.findViewById(R.id.button1);
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent next = new Intent(context, viewmore.class);
context.startActivity(next);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
context.startActivity(next);
}
});
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
}
}
viewmore.java
public class viewmore extends Activity {
private Context context;
private final List<String> descriptions;
private final List<String> imageUrls;
public viewmore(Context c, List<String> descriptions, List<String> imageUrls) {
this.context = c;
this.descriptions = descriptions;
this.imageUrls = imageUrls;
}
private ActionBar actionBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_viewmore);
String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
return true;
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.activity_viewmore, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position)).into(holder.ivImage);
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
}
}
You can use intent.putExtra("key", value) methods before starting the viewmore Activity.
Then in the viewmore Activity, you can get these data from the getIntent().get*Extra("key") methods.
Like:
Intent next = new Intent(context, viewmore.class);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
context.startActivity(next);
Then (in viewmore Activity):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_viewmore);
String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
// Get the TextView using its ID defined in the layout activity_viewmore.xml
TextView tv = (TextView) findViewById(R.id.my_text_view);
tv.setText(description);
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Picasso.with(this).load(imageUrl).into(imageView);
}

Android JSON Data not parsing into ListView

Android not parsing JSON data into ListView, I am using this tutorial and just made few changes in ListViewAdapter.java
Like in my new implementation i used ViewHolder, and my code looks like this:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
ViewHolder holder;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
// Create a ViewHolder and store references to the two children views
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Capture position and set results to the TextViews
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
// Capture ListView item click
return convertView;
}
}
Edited: Click on ListItem code
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
But i don't no why i am not getting data into ListView !
The issue is that you are not assigning the HashMap to `resultp that has the information you want to display
public View getView(final int position, View convertView, ViewGroup parent) {
holder = null;
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here's the change
resultp = data.get(position);
// Here's the change
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
return convertView;
}
To attach OnItemClickListener to your ListView, in the Activity that contains the ListView, add the following:
public class MyActivity implements OnItemClickListener{
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
}
Or, if you don't want your Activity to implement OnItemClickListener, then,
public class MyActivity {
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
}
First of all try to fix this:
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

Categories

Resources