Android ListView duplicating onclicking an item - android

I am having a problem in my listview. Actually I have implemented Facebook Like Feed from Facebook Like Custom Feed
which is fetching data from MySQL database. At bottom of every list item I am having a Like Button from this library Material Favourite Button. My Problem is that when i click like on 1st List item, The 5th list item gets automatically liked and if i click on 2nd List item 4th list item gets liked and so on. I tried everything i could do but nothing resolved this problem. I tried to add view holder also to my list adapter class as suggested in various answered questions here but it didn't resolve my issue. Kindly Help! Below is my adapter class:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private int lastPosition = -1;
private DatabaseHandler db;
ViewHolder holder;
int id = 0;
String email;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, parent,false);
holder = new ViewHolder();
holder.materialFavoriteButtonNice =
(MaterialFavoriteButton) convertView.findViewById(R.id.like_anim);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
//get User Email
db = new DatabaseHandler(activity.getApplication());
db = new DatabaseHandler(activity.getApplication());
HashMap<String, String> user = db.getUserDetails();
email = user.get("email").toString();
// End get User Email ID for sending it to db
//Getting Views from Layout
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
final TextView like = (TextView) convertView.findViewById(R.id.like_box_no);
TextView share = (TextView) convertView.findViewById(R.id.share_no);
TextView comment = (TextView) convertView.findViewById(R.id.comment_no);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
//End Getting Views from Layout
final FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Check for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Chcek for empty Like
if (!TextUtils.isEmpty(item.getLike())) {
like.setText(item.getLike());
like.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
like.setText("0");
}
// Chcek for empty Comment
if (!TextUtils.isEmpty(item.getComment())) {
comment.setText(item.getComment());
comment.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
comment.setText("0");
}
// Chcek for empty Share
if (!TextUtils.isEmpty(item.getShare())) {
share.setText(item.getShare());
share.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
share.setText("0");
}
if (item.getFav().equals("1")) {
holder.materialFavoriteButtonNice.setFavorite(true, false);
holder.materialFavoriteButtonNice.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.materialFavoriteButtonNice.setFavorite(false, false);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
imageLoader.get(item.getProfilePic(), ImageLoader.getImageListener(profilePic, R.drawable._businessman, R.drawable._businessman));
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
//Animating the List View
Animation animation = AnimationUtils.loadAnimation(activity.getApplication(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
//End Animating the List View
//onClick Like
holder.materialFavoriteButtonNice.setOnFavoriteChangeListener(new MaterialFavoriteButton.OnFavoriteChangeListener() {
#Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
Toast.makeText(activity.getApplication(), "Fav Changed : " + item.getId(), Toast.LENGTH_SHORT).show();
if (favorite) {
new send_json().execute();
} else {
holder.materialFavoriteButtonNice.setFavorite(false, true);
new send_json_unlike().execute();
}
}
});
return convertView;
}
static class ViewHolder {
MaterialFavoriteButton materialFavoriteButtonNice;
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.like_func(email, String.valueOf(id));
Log.d("BG Like, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json_unlike extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.unlike_func(email, String.valueOf(id));
Log.d("BG UnLike, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
}
}

Dont use ViewHolder instance global . Make it inside function scope . And try to change the logic . Only update the model inside the array and just call notifyDataSetChanged() method. I think it will solve your issue.

Related

ListView item state not getting saved onScroll in Android

I am having ListView and there is a Like button at the bottom of every List item. I am not able to save the state of the button while Scrolling. The state of the button gets reset while i scroll up or down. I think i need to add a pojo class to get and set the state of button But i have no idea how to do it So can anyone help me with the code?
My Adapter class:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private int lastPosition = -1;
private DatabaseHandler db;
int id = 0;
String email;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
final FeedItem item = feedItems.get(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, parent,false);
holder = new ViewHolder();
//Getting Views from Layout
holder.likebutton =
(LikeButton) convertView.findViewById(R.id.star_button);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
holder.url = (TextView) convertView.findViewById(R.id.txtUrl);
holder.like = (TextView) convertView.findViewById(R.id.like_box_no);
holder.share = (TextView) convertView.findViewById(R.id.share_no);
holder.comment = (TextView) convertView.findViewById(R.id.comment_no);
holder.profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
//End Getting Views from Layout
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//get User Email
db = new DatabaseHandler(activity.getApplication());
HashMap<String, String> user = db.getUserDetails();
email = user.get("email").toString();
// End get User Email ID for sending it to db
holder.name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
if (item.getFav().equals("1")) {
holder.likebutton.setLiked(true);
} else {
// status is empty, remove from view
holder.likebutton.setLiked(false);
}
// Check for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Chcek for empty Like
if (!TextUtils.isEmpty(item.getLike())) {
holder.like.setText(item.getLike());
holder.like.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.like.setText("0");
}
// Chcek for empty Comment
if (!TextUtils.isEmpty(item.getComment())) {
holder.comment.setText(item.getComment());
holder.comment.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.comment.setText("0");
}
// Check for empty Share
if (!TextUtils.isEmpty(item.getShare())) {
holder.share.setText(item.getShare());
holder.share.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.share.setText("0");
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
//Setting preloading Image to profile pic
imageLoader.get(item.getProfilePic(), ImageLoader.getImageListener(holder.profilePic, R.drawable._businessman, R.drawable._businessman));
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
//Animating the List View
Animation animation = AnimationUtils.loadAnimation(activity.getApplication(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
//End Animating the List View
//onClick Like Button
//Toast.makeText(activity.getApplication(), "Fav Changed : " + item.getId(), Toast.LENGTH_SHORT).show();
//if Favourite Clicked Do this
holder.likebutton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
new send_json().execute();
likeButton.setLiked(true);
}
#Override
public void unLiked(LikeButton likeButton) {
new send_json_unlike().execute();
likeButton.setLiked(false);
}
});
return convertView;
}
public static class ViewHolder {
public LikeButton likebutton;
public TextView name;
public TextView timestamp;
public TextView statusMsg;
public TextView like;
public TextView share;
public TextView comment;
public TextView url;
public NetworkImageView profilePic;
public FeedImageView feedImageView;
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.like_func(email, String.valueOf(id));
Log.d("BG Like, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
}
}
//Sending UnLike Request with email id and feed id to Remote Mysql Db
public class send_json_unlike extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.unlike_func(email, String.valueOf(id));
Log.d("BG UnLike, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
}
}
My Fragment:
public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private static final String TAG = MainFragment.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
View view;
private CircleRefreshLayout mRefreshLayout;
private boolean count=false;
JSONObject feedObj;
FeedItem item;
public MainFragment() {
}
public static MainFragment newInstance(String text) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void registerForContextMenu(View view) {
super.registerForContextMenu(view);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main, container, false);
mRefreshLayout = (CircleRefreshLayout) view.findViewById(R.id.refresh_layout);
listView = (ListView) view.findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
view.setFocusableInTouchMode(true);
view.requestFocus();
//Listeneing to Back Button
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().finish();
Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
//Starting start Loader Animation Thread and fetching the feed
mRefreshLayout.post(new Runnable() {
#Override
public void run() {
startAnim();
count=true;
fetch();
}
});
mRefreshLayout.setOnRefreshListener(
new CircleRefreshLayout.OnCircleRefreshListener() {
#Override
public void refreshing() {
// do something when refresh starts
count = true;
fetch();
}
#Override
public void completeRefresh() {
// do something when refresh complete
}
});
listView.setAdapter(listAdapter);
return view;
}
private void fetch()
{
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
feedItems.clear();
parseJsonFeed(response);
}
if (count){
stopAnim();
mRefreshLayout.finishRefreshing();
count=false;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
item.setLike(feedObj.getString("like"));
item.setComment(feedObj.getString("comment"));
item.setShare(feedObj.getString("share"));
item.setFav(feedObj.getString("fav"));
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onRefresh() {
}
//start Animation on Start
void startAnim(){
view.findViewById(R.id.avloadingIndicatorView).setVisibility(View.VISIBLE);
}
//stop Animation on start
void stopAnim(){
view.findViewById(R.id.avloadingIndicatorView).setVisibility(View.GONE);
}
}
well you fetch your data once only and add the items in 'feedItems'. then on 'userFunction.like_func' you like or dislike using the 'userFunction.unlike_func' which we do not know what they do but probably they do not update 'feedItems' collection and precisely do not call 'setFav' on the clicked item. This is why the likes are not updated. You can:
1) update(call setFav) required fields in the async tasks or even better create volley request for those.
2) in 'holder.likebutton.setOnLikeListener(new OnLikeListener() {'
add:
item.setFav("1") or item.setFav("0")
holder.likebutton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
new send_json().execute();
likeButton.setLiked(true);
item.setFav("1")
}
#Override
public void unLiked(LikeButton likeButton) {
new send_json_unlike().execute();
likeButton.setLiked(false);
item.setFav("0")
}
});
this however does not guarantee synchronization with remote data as the request may fail and this is why 1) should be done also

How to show title of a row in a textview in Main Activity when an image in the row is clicked

I have a custom adapter with an image in each row.On clicking the image i would like to display the title of the row that the image is part of.
I have implemented an interface in my activity that allows me to display a relative layout whenever the image is clicked where the textview that displays the row title exists.This relative layout is in in my activity_main.xml.
Problem: I have been able to accomplish all his except that only the title of the first row is displayed across all the other image clicks in my listview.
Also: I know that setting listView.setOnItemSelectedListener(this); is the best way to go because this can handle the position of the title but i cannot use this as per my requirements.Is there a way to hack this?
So that my textview displays the title of the row that is different in each case?
MainActivity.java:
public class MainActivity extends ActionBarActivity implements FeedListAdapter.AdapterCallback {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
RelativeLayout error, player;
private List<FeedItem> feedItems;
private String URL_FEED = "http://10.0.3.2/main_feed_warship/main_feed.js";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
mToolBarTextView.setText("Home");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
player = (RelativeLayout) findViewById(R.id.player);
player.setVisibility(View.GONE);
ImageView cancel = (ImageView) findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.setVisibility(View.GONE);
}
});
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
;
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
*/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onMethodCallback() {
//On Image click this relative layout is called
player.setVisibility(View.VISIBLE);
//And the title of the row with the image that is clicked is displayed
//Only the first row title is dispalyed across all image clicks
String name = ((TextView) findViewById(R.id.name))
.getText().toString();
TextView title=(TextView)findViewById(R.id.music_title);
title.setText(name);
}
}
FeedListAdapter.java:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private AdapterCallback mAdapterCallback;
private LayoutInflater inflater;
String title;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
try {
this.mAdapterCallback = ((AdapterCallback) activity);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement AdapterCallback.");
}
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
final FeedItem item = feedItems.get(position);
name.setText(item.getName());
String fontPath = "fonts/Lato-Light.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(activity.getAssets(), fontPath);
// Applying font
name.setTypeface(tf);
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
timestamp.setVisibility(View.GONE);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.GONE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.GONE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
//The image in each row that is clicked to call the method below from my activity
ImageView play=(ImageView)convertView.findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mAdapterCallback.onMethodCallback();
} catch (ClassCastException exception) {
}
}
});
return convertView;
}
public static interface AdapterCallback {
void onMethodCallback();
}
}
This is a long shot, but did you try utilizing the Tag. It goes like this:
1- In your adapter, set the ImageView tag to be the TextView (title) id:
feedImageView.setTag(name.getId());
2- When the imageView is clicked, you get the tag (i.e. the id of the TextView).
feedImageView.getTag();
3- Now, you have the correct reference to your title.
I'm not sure if passing the TextView id will be enough, but I think utilizing the Tag is the way to go. You just need to figure out what you should pass, and where you should pass it. FYI, you could pass the title (as a string) in the tag!

How to fetch the image using JSON in ListFragment?

I am new to android development,I am parsing my data using JSON Parsing method,I extend my class with List Fragment and I want my data in list view but the problem is i am getting all the data perfectly except the images,i don't know how to solve it,my response looks like this
{"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age+" years");
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
// updating listview
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
}
Try to AndroidQuery with custom adapter :
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#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.list_item, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propic);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
How to set adapter to ListView :
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
You can use universal image loader for viewing images from your server.Z
Just pass the image url and your view and you are good to go.
For your reference here is the link to Universal Image loader with all its documentation.
https://github.com/nostra13/Android-Universal-Image-Loader
Hop it helps you.
I am hardly suggest you to use Android Query for this. Its mind blowing api given by Android itself. You can download image, download bitmap or whatever you wanna do you can.
You can download the jar file from here :here Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return aList.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(aList.get(position).get(TAG_NAME));
holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
holder.txtCast.setText(aList.get(position).get(TAG_CAST));
holder.txtAge.setText(aList.get(position).get(TAG_AGE));
aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtProfile;
TextView txtCast;
TextView txtAge;
ImageView imgUser;
}
}
In source code of SimpleAdapter:
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
You can see if your view is ImageView , the code will use the url String be the resId in
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {#link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* #param v ImageView to receive an image
* #param value the value retrieved from the data set
*
* #see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
And your error is here , so you need Override the getView function of SimpleAdapter.Here is code:
Uri uri = Uri.parse("http://gujjumatch.com/images/Girlnoimage.jpg");
image.setImageURI(uri);
You need to create adapter and extend it to BaseAdapter and add all your items and call it in your AsyncTask's method and it will return your output as said by Haresh Chellana.

List View Custom adapter item(button) text repeating on scrolling

I am facing problem with listview in android. I've a custom adapter with 3 textviews and a button whose text changes as per response from server. Actually I've a feature of search friend in my app,so the list appears with each user and its status on button text. Like if already friend then button text is Friend and button is disabled.Else Add Friend, and button enabled. After clicking Add Friend text of button changes to Request Sent. But the problem is that when i click on a button text of some other buttons also changes on scrolling. Please help me. If needed I'll put the code.
Here is my adapter class:
class ListViewCustomAdapter extends BaseAdapter {
private static final String REQUEST = "Request";
private static final String ACCEPT = "Accepted";
private static final String RECEIVE = "Receive";
private Activity context;
private ArrayList<FriendList> friendList;
private SessionManager sessionManager;
private String authToken;
private ProgressDialog progressDialog;
ViewHolder mViewHolder;
private HashMap<Integer, String> buttonTextMap;
public ListViewCustomAdapter(Activity activity,
ArrayList<FriendList> _friendList) {
this.context = activity;
this.friendList = _friendList;
sessionManager = new SessionManager(context);
authToken = sessionManager.getAuthorizationKey();
buttonTextMap = new HashMap<Integer, String>();
}
public int getCount() {
// TODO Auto-generated method stub
return friendList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return friendList.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.friend_list_view_item, null);
mViewHolder = new ViewHolder();
mViewHolder.profilePicture = (ImageView) convertView
.findViewById(R.id.friendPicureImageView);
mViewHolder.friendName = (TextView) convertView
.findViewById(R.id.firstNameTextView);
mViewHolder.email = (TextView) convertView
.findViewById(R.id.emailTextView);
mViewHolder.gender = (TextView) convertView
.findViewById(R.id.genderTextView);
mViewHolder.addButton = (Button) convertView
.findViewById(R.id.addFriendButton);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
byte[] imageByteArray = Base64.decode(friendList.get(position)
.getFriendProfilePic(), Base64.DEFAULT);
mViewHolder.profilePicture.setImageBitmap(BitmapFactory
.decodeByteArray(imageByteArray, 0, imageByteArray.length));
if (friendList.get(position).getFriendFirstName()
.equalsIgnoreCase("null")) {
mViewHolder.friendName.setText(friendList.get(position)
.getFriendLastName());
} else if (friendList.get(position).getFriendLastName()
.equalsIgnoreCase("null")) {
mViewHolder.friendName.setText(friendList.get(position)
.getFriendFirstName());
} else if (friendList.get(position).getFriendLastName()
.equalsIgnoreCase("null")
&& friendList.get(position).getFriendFirstName()
.equalsIgnoreCase("null")) {
mViewHolder.friendName.setText("No Name");
} else {
mViewHolder.friendName.setText(friendList.get(position)
.getFriendFirstName()
+ " "
+ friendList.get(position).getFriendLastName());
}
if (!friendList.get(position).getFriendEmail().equalsIgnoreCase("null")) {
mViewHolder.email
.setText(friendList.get(position).getFriendEmail());
}
if (!friendList.get(position).getFriendGender()
.equalsIgnoreCase("null")) {
if (friendList.get(position).getFriendGender()
.equalsIgnoreCase(Constants.MALE))
mViewHolder.gender.setText(Constants.SET_MALE);
else if (friendList.get(position).getFriendGender()
.equalsIgnoreCase(Constants.FEMALE)) {
mViewHolder.gender.setText(Constants.SET_FEMALE);
}
}
if (friendList.get(position).getFriendRequestStatus()
.equalsIgnoreCase(REQUEST)) {
/*
* buttonTextMap.put(position, "Request sent");
* buttonActiveStateMap.put(position, false);
*/
mViewHolder.addButton.setText("Request Sent");
mViewHolder.addButton.setEnabled(false);
} else if (friendList.get(position).getFriendRequestStatus()
.equalsIgnoreCase(ACCEPT)) {
/*
* buttonTextMap.put(position, "Add friend");
* buttonActiveStateMap.put(position, true);
*/
mViewHolder.addButton.setText("Friend");
mViewHolder.addButton.setEnabled(false);
} else if (friendList.get(position).getFriendRequestStatus()
.equalsIgnoreCase(RECEIVE)) {
/*
* buttonTextMap.put(position, "Add friend");
* buttonActiveStateMap.put(position, true);
*/
mViewHolder.addButton.setText("Accept");
mViewHolder.addButton.setEnabled(true);
}
buttonTextMap.put(position, mViewHolder.addButton.getText().toString());
Log.d("FriendList", "position in getview===== " + position);
mViewHolder.addButton.setTag(position);
mViewHolder.addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int which = -1;
Object obj = v.getTag();
if(obj instanceof Integer){
which = ((Integer)obj).intValue();
Log.e("FriendListActivity", "position button 1 ======= "+which);
}
if(which >-1){
Log.e("FriendListActivity", "position button 2======= "+which);
}
Button button = (Button) FriendListActivity.listView.getChildAt(which).findViewById(R.id.addFriendButton);
//Button button = (Button) v;
if (button.getText().toString().equalsIgnoreCase("Accept")) {
Intent intent = new Intent(context,
NotificationsActivity.class);
context.startActivity(intent);
context.finish();
} else {
int id = button.getId();
addFriend(button, friendList.get(position)
.getFriendUserId(),which);
}
}
});
return convertView;
}
static class ViewHolder {
TextView friendName;
TextView email;
TextView gender;
ImageView profilePicture;
Button addButton;
}
private void addFriend(final Button _button, final String userId,
final int _position) {
final JSONObject jsonObject = new JSONObject();
Log.e("FriendListActivity", "position in addFriend=== " + _position);
try {
jsonObject.put("authToken", authToken);
jsonObject.put("targetFriendId", userId);
jsonObject.put("requestType", "FriendRequest");
jsonObject.put("status", "Requested");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
progressDialog.dismiss();
if (msg.what == 1) {
_button.setText("Request sent");
_button.setEnabled(false);
Toast.makeText(context, "Request sent successfully.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Request unsuccessfull.",
Toast.LENGTH_LONG).show();
}
}
};
progressDialog = ProgressDialog.show(context, "", "Loading...");
new Thread() {
#Override
public void run() {
String response = DoFriendRequest
.makeHttpPostRequest(jsonObject);
Message message = new Message();
if (response != null) {
message.what = 1;
handler.sendEmptyMessage(message.what);
} else {
handler.sendEmptyMessage(0);
}
}
}.start();
}
So finally I found the solution after a long research and completely understanding listview's recycling and use of convertview. As I am getting the status for each button from server, so in my addFriend() method I was just updating the text of the button(of the view only) which is pressed, but not in the list from where I am getting the data for the listview(each row of listview). So what I did, whenever I update the label-status of the button for a row, I've to update my datalist(in my case friendList by setting friendList.get(position).setFriendStatus("null")) and call adapter.notifyDatasetChanged() after that. I also forgot to add a check-filter for the "null" status of button. If anyone has any confusion please ask me.
This is the link which I referred for understanding listview getView() method-
How ListView's recycling mechanism works

Pass a variable value from Base Adapter to activity

I have a set a variable in my Base Adapter class, now I want to get(pass) this variable in my related Activity. I am not getting how to do this.
Here is my code.
public class TourDescAdapter extends BaseAdapter {
private List<Descriptions> descriptList;
private LayoutInflater mInflater;
ViewHolder holder;
#SuppressWarnings("unused")
private OnClickListener clickListener;
Activity context;
//TourDescription tourDesc;
ArrayList<HashMap<String, Object>> obj = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> discountedTourDetails = null;
String price = null, prodId = null;
String promoTourname, tourName;
public TourDescAdapter(List<Descriptions> descriptList,
TourDescription activity) {
this.context = activity;
this.descriptList = descriptList;
mInflater = LayoutInflater.from(activity);
clickListener = (OnClickListener) activity;
}
#Override
public int getCount() {
return this.descriptList.size();
}
#Override
public Object getItem(int position) {
return this.descriptList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.tourlist, null);
/****
* Creates a ViewHolder and store references to the two children
* views we want to bind data to
****/
holder = new ViewHolder();
holder.rlayout = (RelativeLayout) convertView
.findViewById(R.id.tourlayout);
holder.title = (TextView) convertView
.findViewById(R.id.tourtitletext);
holder.desc = (TextView) convertView.findViewById(R.id.tourdes);
holder.amountButton = (Button) convertView
.findViewById(R.id.amtBtn);
holder.pinButton = (Button) convertView.findViewById(R.id.pinBtn);
holder.arrowButton = (Button)convertView.findViewById(R.id.arrowBtn);
holder.serialText = (EditText)convertView.findViewById(R.id.pinText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText((String) descriptList.get(position)
.getImageTitle());
holder.desc.setText((String) descriptList.get(position)
.getImageDescription());
((ImageView) holder.rlayout.getChildAt(0)).setImageBitmap(BitmapFactory
.decodeFile((RaconTours.PATH + RaconTours.city + File.separator
+ TourDescription.currentTour.getObjtourName()
+ File.separator + descriptList.get(position)
.getImagePath().split("/")[2]).replace(" ", "_")));
if (position == 0) {
SharedPreferences settings = context.getSharedPreferences("downloadDetails", 0);
String isTourDownloaded = settings.getString(TourDescription.currentTour.getObjtourName(), "");
if (isTourDownloaded.equals("true")) {
//if (!(TourDescription.downloadFile.exists())||TourDescription.downloadFile.exists() == false ) {
//if (TourDescription.currentTour.getIsTourDownloaded() == true) {
//holder.pinButton.setVisibility(View.INVISIBLE);
//holder.arrowButton.setVisibility(View.INVISIBLE);
//holder.serialText.setVisibility(View.INVISIBLE);
}
holder.amountButton.setVisibility(View.VISIBLE);
holder.amountButton.setText("Start");
} else {
File promoPlistPath = new File(RaconTours.PATH + "promocode.txt");
checkPromoCode(promoPlistPath);
if (discountedTourDetails != null) {
tourName = (String) discountedTourDetails.get("promoTour");
price = (String) discountedTourDetails.get("discountPrice");
prodId = (String) discountedTourDetails.get("disProId");
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText("$" +price);
//promoPlistPath.delete();
} else {
// Enabling the two buttons
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText(TourDescription.currentTour
.getObjPrice());
}
}
} else {
holder.amountButton.setVisibility(View.INVISIBLE);
holder.pinButton.setVisibility(View.INVISIBLE);
holder.arrowButton.setVisibility(View.INVISIBLE);
holder.serialText.setVisibility(View.INVISIBLE);
holder.title.setBackgroundColor(Color.WHITE);
holder.title.setTextColor(Color.BLACK);
holder.title.setGravity(Gravity.CENTER_HORIZONTAL);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.INVISIBLE);
}
return convertView;
}
#SuppressWarnings("unchecked")
private void checkPromoCode(File promoPlistPath) {
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(
new FileInputStream(promoPlistPath));
obj = (ArrayList<HashMap<String, Object>>) inStream
.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
if (promoTourname.equals(TourDescription.currentTour.getObjtourName())) {
discountedTourDetails = tmpObj;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ViewHolder {
Button pinButton;
Button amountButton;
RelativeLayout rlayout;
TextView title;
TextView desc;
Button arrowButton;
EditText serialText;
}
}
Here
prodId = (String) discountedTourDetails.get("disProId");
I want to pass prodId to related activity.
Note: Base Adapter is called from the activity
adapter = new TourDescAdapter(currentTour.getListOfDescriptions(), this);
setListAdapter(adapter);
Any one can tell me how to do this?
Couldn't you just use String iGotTheString = adapter.prodId?

Categories

Resources