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
Related
I'm hoping that someone here could help me. I'm trying to delete an item from my Listview by clicking a button from another activity. I'm sending a an intent and resultcode in the onActivityResult to the activity that contains the listview but nothing is happening. Any help would be greatly appreciated. Thanks
Delete Button Activity
private void deleteClicked() {
Intent result = new Intent();
result.putExtra("myReminder", item);
getActivity() .setResult(12, result);
getActivity().finish();
}
ListView Activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e(TAG, "REMOVE CALLEDcode");
if (requestCode == 05) {
if (resultCode == 12) {
Chops item = (Chops) data.getSerializableExtra("myReminder");
removeChop(item);
refreshFragment();
}
}
}
private void removeChop(Chops item) {
// TODO Auto-generated method stub
Log.d(TAG, "REMOVE CALLED");
for (Iterator iterator = SaveTheChops.listofchops.iterator(); iterator.hasNext(); ) {
Chops deleteChop = (Chops) iterator.next();
if (match(item, deleteChop)) {
iterator.remove();
//SaveTheChops.addChop(getActivity());
return;
}
}
}
private boolean match(Chops item, Chops deleteChop) {
if (item.getmAlbum().equals(deleteChop.getmAlbum()) &
item.getmArtist().equals(deleteChop.getmArtist()) &
item.getmSong().equals(deleteChop.getmSong()) &
item.getmAudio().equals(deleteChop.getmAudio()) &
item.getmPic().equals(deleteChop.getmPic()) &
item.getmSection().equals(deleteChop.getmSection()))
{ Log.e(TAG, "MATCH");
return true;
}
Log.e(TAG, " NO MATCH");
return false;
}
private void refreshFragment() {
Log.e(TAG, "REFRESHED");
Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("ListFragmenttag");
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
If it helps here is my ListAdapter
public static class ListViewDemoAdapter extends ArrayAdapter<Chops> implements MediaPlayer.OnCompletionListener {
final String TAG = "MyChopActivty";
private boolean isPlaying;
private boolean isRecording;
private List<Chops> mItems;
MediaPlayer mPlayer;
public Chops item;
File audiofile = null;
private int length;
Intent intent, fileIntent;
String mAudio;
public ListViewDemoAdapter(Context context, List<Chops> items) {
super(context, R.layout.each_item, items);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.each_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.cover_photo);
viewHolder.tvAlbum = (TextView) convertView.findViewById(R.id.tvAlbum);
viewHolder.tvPlay = (Button) convertView.findViewById(R.id.listPly);
viewHolder.tvSong = (TextView) convertView.findViewById(R.id.tvSong);
convertView.setTag(viewHolder);
final Button PIL = (Button) convertView.findViewById(R.id.listPly);
final Button PAUSIL = (Button) convertView.findViewById(R.id.listPause);
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setTag(position);
PIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
Chops item = getItem(position);
Toast.makeText(getContext(), "PLAY FROM LIST?", Toast.LENGTH_SHORT).show();
if (item.getmAudio() != null) {
mAudio = item.getmAudio();
Log.d(TAG, " from LISTPLAY " + mAudio);
try {
playAudio(mAudio);
if (isPlaying) {
PAUSIL.setEnabled(true);
PAUSIL.setVisibility(View.VISIBLE);
PIL.setEnabled(false);
PIL.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
PAUSIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "PAUSING", Toast.LENGTH_SHORT).show();
stopPlaying();
isPlaying = false;
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setEnabled(true);
PIL.setVisibility(View.VISIBLE);
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Chops item = getItem(position);
viewHolder.ivIcon.setImageBitmap(StringToBitMap(item.getmPic()));
viewHolder.tvAlbum.setText(item.getmAlbum());
viewHolder.tvSong.setText(item.getmSong());
return convertView;
}
Instead, Add a method to remove an item from your dataset inside your Adapter class. Something along the lines of:
public void remove(int position){
mItems.remove(position);
notifyDataSetChanged();
}
Then call yourAdapter.remove(positionToRemove); from the onClick of the Activity with the button.
I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.
I use https://github.com/bulletnoid/StaggeredGridView this library for make a pinterest style layout and use pulltorefresh on this layout. Also ı have a slide menu for choose different category and according to category which is user choose, refresh and refill the staggred again.
Pulltorefresh is work fine.
if user top of the layout and choose a category on slide menu it's work correctly. But if user bottom of the layout and choose a category on slide menu it's work not correctly .
the scenario, top of layout and select category on slidemenu and refill staggered layout. it's work correctly
the scenario, bottom of layout and select category on slidemenu and refill staggered layout. it's not work correctly
-->listviewAdapter
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3) {
// TODO Auto-generated method stub
switch (parent.getId()) {
case R.id.listView_sliding_menu:
smenu.toggle();
slidingMenuControl = true;
String categoryId = ((TextView) view.findViewById(R.id.categoryID))
.getText().toString();
parameters[0] = categoryId;
Toast.makeText(getApplicationContext(), categoryId,
Toast.LENGTH_LONG).show();
new PARSEJSONCATEGORYCONTENT().execute(parameters);
break;
default:
break;
}
}
-->parser
private class PARSEJSONCATEGORYCONTENT extends
AsyncTask<String[], Void, ArrayList<Utils>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
processDialoge();
}
protected ArrayList<Utils> doInBackground(String[]... params) {
String catId = params[0][0];
String startCount = params[0][5];
String count = params[0][6];
String urlCatContent = "http://212.58.8.109/webservice/api/content/cat/";
jArray = jsonParser.getJSONFromUrltoCategoryContent(urlCatContent,
Token, tokenValue, catId, startCount, count);
if (utilsArray == null) {
utilsArray = new ArrayList<Utils>();
} else if (slidingMenuControl == true) {
utilsArray.clear();
} else if (contentItemSelection != null) {
utilsArray.clear();
}
try {
// looping through All Contacts
for (int i = 0; i < jArray.length(); i++) {
JSONObject k = jArray.getJSONObject(i);
utils = new Utils();
// Storing each json item in variable
utils.imageUrl = k.getString("ipad_URL");
utils.imageWidth = k.getInt("ipad_width");
utils.imageHeight = k.getInt("ipad_height");
utils.categoryHeader = k.getString("contentHeader");
utils.contentDesc = k.getString("contentDesc");
utils.categoryContentId = k.getInt("id");
utils.contentTxt = k.getString("contentTxt");
Log.d("ipad_URL", utils.imageUrl);
utilsArray.add(utils);
}
String arrayLenght = Integer.toString(utilsArray.size());
Log.d("arrayLenght", arrayLenght);
} catch (JSONException e) {
e.printStackTrace();
}
return utilsArray;
}
protected void onPostExecute(ArrayList<Utils> utilsArray) {
staggeredAdapter.getMoreItemm(utilsArray);
// staggeredAdapter.setRefreshListener(false);
super.onPostExecute(utilsArray);
slidingMenuControl = false;
dialog.cancel();
}
}
-->BaseAdapter.java
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("NewApi")
public class StaggeredAdapter extends BaseAdapter implements OnClickListener {
Typeface tf;
boolean refreshListener = false;
Utils utils;
private Context mContext;
private Application mAppContext;
private ArrayList<Utils> mUtilsArraylist = new ArrayList<Utils>();
public StaggeredAdapter(Context context, Application application) {
mContext = context;
mAppContext = application;
tf = Typeface.createFromAsset(mContext.getAssets(),
"font/Klavika-Medium.otf");
notifyDataSetChanged();
}
public void getMoreItemm(ArrayList<Utils> arrayList) {
mUtilsArraylist.clear();
mUtilsArraylist.addAll(arrayList);
this.notifyDataSetChanged();
}
public int getCount() {
return mUtilsArraylist == null ? 0 : mUtilsArraylist.size();
}
#Override
public Object getItem(int position) {
return mUtilsArraylist.get(position);
}
#Override
public long getItemId(int position) {
return mUtilsArraylist.indexOf(getItem(position));
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
utils = mUtilsArraylist.get(position);
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.staggered_item, null);
holder.imgUrl_content = (STGVImageView) view
.findViewById(R.id.imgUrl_content);
holder.tv_info = (TextView) view.findViewById(R.id.contentHeader);
holder.tv_info.setTypeface(tf);
holder.tv_info2 = (TextView) view.findViewById(R.id.contentDesc);
holder.tv_info2.setTypeface(tf);
view.setTag(holder);
} else {
return convertView;
}
final Holder holder = (Holder) view.getTag();
holder.imgUrl_content.mHeight = utils.imageHeight;
holder.imgUrl_content.mWidth = utils.imageWidth;
holder.imgUrl_content.setOnClickListener(this);
ImageLoader imgLoader = new ImageLoader(mAppContext);
imgLoader.DisplayImage(utils.imageUrl, holder.imgUrl_content);
holder.tv_info.setText(utils.categoryHeader);
holder.tv_info.setOnClickListener(this);
holder.tv_info2.setText(utils.contentDesc);
holder.tv_info2.setOnClickListener(this);
return view;
}
class Holder {
public STGVImageView imgUrl_content;
public TextView tv_info;
public TextView tv_info2;
}
public boolean isRefreshListener() {
return refreshListener;
}
public void setRefreshListener(boolean refreshListener) {
this.refreshListener = refreshListener;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.imgUrl_content:
sendDataItemContentActivity();
break;
case R.id.contentHeader:
sendDataItemContentActivity();
break;
case R.id.contentDesc:
sendDataItemContentActivity();
break;
default:
break;
}
}
public void sendDataItemContentActivity() {
Intent intent = new Intent(mContext, ItemContent.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("contentTxt", utils.contentTxt);
intent.putExtra("contentHeader", utils.categoryHeader);
intent.putExtra("contentİmageUrl", utils.imageUrl);
intent.putExtra("contentCategoryName", utils.categoryName);
Bundle animBundle = ActivityOptions.makeCustomAnimation(mContext,
R.anim.anim, R.anim.anim2).toBundle();
mContext.startActivity(intent, animBundle);
}
}
I guess i had a same problem with using the same pinterest style library with you. i solve my problem by put this
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter = new SearchSTGVAdapter(getActivity(), adsList, (Fragment)this);
ptrstgv.setAdapter(mAdapter);
}
which previously I put it in the onCreate method
For your information, I am implement this pinterest style in a view pager not a sliding menu
I am using a listview in my Android program.
I have row. 1) i have custom row in button and i want to when click button then open the alert box and this row clicked then open the new activity but Only one button clicked not row clicked . how to possible in this case. my code in below.
Thank you.
public class AlMessagesAdapter extends ArrayAdapter<DtoAllMessages> {
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
and list click event in below::
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
msg = userLIstArray.get(position).getMessage();
token = userLIstArray.get(position).getToken();
type = userLIstArray.get(position).getType();
int msgId = userLIstArray.get(position).getMessageid();
token = token.substring(0,token.length()-3);
int token_value = Integer.parseInt(token) * 1000;
if(type.equals("text"))
{
Log.v("log", " if in text to Display " + msg + " token "+token);
Intent i = new Intent(MessagesList.this,DisplayPopupActivity.class);
i.putExtra("msg", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
}
else if(type.equals("photo"))
{
Log.v("log", " else in IMage to Display " + msg + " token "+token);
Log.v("log","token "+token+" type "+type + " position "+position + "msgId "+ msgId);
Intent i = new Intent(MessagesList.this,DisplayImageActivity.class);
i.putExtra("imgData", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
//Log.v("log"," Message" +message);
//Toast.makeText(AllMessageActivity.this, "Message "+message, Toast.LENGTH_LONG).show();
}
return false;
}
});
}
Try this,
Instead of button use TextView. and the write onclickListerner to TextView. i had face same issue in ListView Button click using textview now its working fine. just try it.
You can add the row click event using:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
//go to new activity
});
And the button event, as you are doing..
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
//show alert
}
});
call your clickevent inside if condition
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener(click);
}
create clicklistner outside.
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do your stuff here
}
};
In your Adapter class set an OnclickListner
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
private Context context; //added
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.context=context; //added
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener((OnClickListener)context); //added portion
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
/*holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});*/
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
And into your Main class
public Main extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.casual_layout);
Button tokenBtn=(Button)findViewById(R.id.tokenBtn);
tokenBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.tokenBtn:
//Write a code here to execute alertdialog
Log.d("ALERT HERE","ALERT HERE");
break;
}
}
If you want to use a Button instead of a TextView set
android:focusable="false"
to your Button
For Eg :
Follow #SoccerBible, RT this & if Ronaldo scores
https://bit.ly/133/com tonight we'll give away a pair of Nike Clash
Vapor 8's to one lucky winner! #RonaldoComp
In my listview component. Where i am showing list of tweets. I have colored the #,# and urls in the tweet text. The all are dynamically clickable.
My question is how can i make the non-colored text as clickable. I have used Linkify.addLinks and Pattern API to make them clickable. But i wanted the non #,# and url text to be clicakble without adding any color to it.
Thanks,
dominic
For twitter app, I had also the same requirement to click on handles of tweets and also click on the text of tweet to get Tweet detail.
For that I have used this LinkEnabledTextView and that become easy for me to do the task.
I just added the class in my project and then in List Item instead simple TextView I used object/instance of the LinkEnabledTextView.
There is a complete demo in above link, Please check that.
EDIT: Adapter Code Specially check onTextLinkClick() and then holder.twtdata.setOnClickListener()
private static class EfficientAdapter extends BaseAdapter implements TextLinkClickListener {
private LayoutInflater mInflater;
static int pos =0;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return timelines.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listtimerow, null);
holder = new ViewHolder();
holder.twtdata = (LinkEnabledTextView) convertView
.findViewById(R.id.twtdata);
holder.twtnm = (TextView) convertView
.findViewById(R.id.twthandle);
holder.twtimg = (ImageView) convertView
.findViewById(R.id.avatar);
holder.twtdt = (TextView) convertView
.findViewById(R.id.created);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.twtdata.setOnTextLinkClickListener(this);
holder.twtdata.gatherLinksForText(timelines[position]);
holder.twtdata.setTextColor(Color.BLACK);
holder.twtdata.setLinkTextColor(Color.BLUE);
MovementMethod m = holder.twtdata.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (holder.twtdata.getLinksClickable()) {
holder.twtdata.setMovementMethod(LinkMovementMethod.getInstance());
}
}
if (bmpimg1[position] != null)
holder.twtimg.setImageBitmap(bmpimg1[position]);
holder.twtnm.setText(twitterhandles[position]);
Date credate = new Date(created[position]);
String dt = credate.getDate() + " "
+ getMonthName(credate.getMonth());
holder.twtdt.setText(dt);
holder.twtdata.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pos = position;
if(linkselected==true)
return;
childSelected = true;
Log.i("mention data", timelines[position]);
Intent textintent = new Intent(ctx, TimelineRe.class);
textintent.putExtra("userid", userid[position]);
textintent.putExtra("nm", twitterhandles[position]);
textintent.putExtra("msg", timelines[position]);
textintent.putExtra("pos", position);
textintent.putExtra("frm", "t");
textintent.putExtra("img", bmpimg1[position]);
if (urlentities[position] != null
&& dpurlentities[position] != null) {
textintent.putExtra("urlentity", urlentities[position]);
textintent.putExtra("dpurlentity", dpurlentities[position]);
}
textintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(textintent);
}
});
holder.twtnm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
childSelected = true;
Intent iconintent = new Intent(ctx, TweetRe.class);
iconintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
iconintent.putExtra("userid", userid[position]);
iconintent.putExtra("pos", position);
iconintent.putExtra("frm", "t");
iconintent.putExtra("img", bmpimg1[position]);
ctx.startActivity(iconintent);
}
});
holder.twtimg.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
childSelected = true;
Intent iconintent = new Intent(ctx, TweetRe.class);
iconintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
iconintent.putExtra("userid", userid[position]);
iconintent.putExtra("pos", position);
iconintent.putExtra("frm", "t");
iconintent.putExtra("img", bmpimg1[position]);
ctx.startActivity(iconintent);
}
});
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return timelines.length;
}
static class ViewHolder {
TextView twtdt;
LinkEnabledTextView twtdata;
ImageView twtimg;
TextView twtnm;
}
public void onTextLinkClick(View textView, String clickedString)
{
if (isWiFiConnected == false) {
Toast.makeText(ctx,
"No Internet Connection \nPlease Check and Retry",
Toast.LENGTH_SHORT).show();
return;
}
android.util.Log.v("Hyperlink clicked is :: " + clickedString, "Hyperlink clicked is :: " + clickedString);
if(clickedString.charAt(0)=='#')
{
linkselected=true;
childSelected=true;
Intent reintent = new Intent(ctx,
Search.class);
reintent.putExtra("frm", "l");
reintent.putExtra("keyword",clickedString.substring(1, clickedString.length()) );
reintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(reintent);
}
else if(clickedString.charAt(0)=='#')
{
linkselected=true;
childSelected=true;
Intent iconintent = new Intent(ctx, TweetRe.class);
iconintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
iconintent.putExtra("snm", clickedString.substring(1,clickedString.length()));
iconintent.putExtra("frm", "l");
// iconintent.putExtra("userid", userid[pos]);
// iconintent.putExtra("pos", pos);
// iconintent.putExtra("img", bmpimg2[pos]);
ctx.startActivity(iconintent);
}
else if(clickedString.charAt(0)=='h')
{
linkselected=true;
childSelected=true;
Intent iconintent = new Intent(ctx, ShowLink.class);
iconintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
iconintent.putExtra("url","http://www."+dpurlentities[pos]);
ctx.startActivity(iconintent);
}
}
}