Circular imageview dissappears in listview after fling - android

Im generating a feed full of images (similar to instagram post) using Glide for loading images and user's profile picture. After i get the data from server, i load the Url's of images inside the listitem. Initally All items are being loaded properly.
The issue is that when i fast scroll the listview, user profile picture dissappears and that view doesnt respond to onClick Events. Please explain why this happens and how can i resolve this?
XML layout of each list Item.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:orientation="vertical" >
<RelativeLayout android:id="#+id/userheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/realdp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/nodp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/realdp"
android:text="handle"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:layout_alignTop="#+id/realdp"
android:layout_alignBottom="#+id/realdp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/uploadtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/handle"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:text="time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RelativeLayout android:id="#+id/rlimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/handle">
<ImageView
android:id="#+id/imgpost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:background="#ffffff"/>
</RelativeLayout>
<RelativeLayout android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rlimg"
android:layout_marginTop="5dp">
<com.sivaram.fishograph.FlipImageView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_marginLeft="20dp"
android:src="#drawable/hook_unlike"/>
<ImageButton
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_toRightOf="#+id/likesnum"
android:layout_marginLeft="20dp"
android:src="#drawable/comment" />
<ImageButton
android:id="#+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/more" />
<TextView
android:id="#+id/likesnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/like"
android:layout_alignTop="#+id/like"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/like"
android:text="likes"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
<TextView
android:id="#+id/comnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/comment"
android:layout_alignTop="#+id/comment"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/comment"
android:gravity="center_vertical"
android:text="comments"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/userheader"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="Caption"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/caption"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Java Code for generating feed:
public class Feed extends Fragment implements OnScrollListener
{
String handle;
ListView lvposts;
Jsparser jp;
int width,height;
int maxMemory;
int currentFirstVisibleItem ;
int currentVisibleItemCount;
PostAdapter pa;
ArrayList<eachpost> posts;
int value = 1;
boolean isLoading = false;
int photoid;
private List<String> myData;
Boolean tapped = false, Loading= false;
SharedPreferences spf;
ArrayList<String> likes;
public Feed()
{
super();
}
Feed(String handle)
{
super();
photoid = 99999999;
this.handle = handle;
}
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
spf = getActivity().getSharedPreferences("prefs",Context.MODE_PRIVATE);
likes = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup vg, Bundle b)
{
View v = inflater.inflate(R.layout.allposts, vg, false);
ActionBar ab = ((ActionBarActivity) getActivity()).getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.RED));
ab.hide();
lvposts = (ListView) v.findViewById(R.id.lvposts);
jp = new Jsparser();
Display d = getActivity().getWindowManager().getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
lvposts.setOnScrollListener(this);
posts = new ArrayList<eachpost>();
pa = new PostAdapter(getActivity(),R.layout.postcontent,posts,inflater);
Loading = true;
lvposts.setAdapter(pa);
new GetData(photoid).execute();
return v;
}
class GetData extends AsyncTask<String,String,String>
{
String msg;
Integer limit,success=0;
ProgressDialog pd;
Bitmap dpbm;
GetData(int l)
{
limit = l;
}
#Override
public void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> lp = new ArrayList<NameValuePair>();
lp.add(new BasicNameValuePair("handle",handle));
lp.add(new BasicNameValuePair("photoid",limit.toString()));
JSONObject job = jp.makeHttpRequest("server/getfeed.php", "POST", lp);
try
{
Log.d("json", job.toString());
success = job.getInt("success");
msg = job.getString("message");
if(success==1)
{
JSONArray ja = job.getJSONArray("posts");
for(int c = 0; c<ja.length(); c++)
{
JSONObject jb = ja.getJSONObject(c);
posts.add(new eachpost(jb.getString("handle"),jb.getString("url"), jb.getString("caption"),
jb.getString("uldatetime"), jb.getInt("likescount"), jb.getInt("comcount"), jb.getString("dpurl"), jb.getInt("isliked"),jb.getInt("photoid") ));
}
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
#Override
public void onPostExecute(String url)
{
Loading = false;
if(success==1)
{
photoid = posts.get(posts.size()-1).getPhotoid();
Log.d("last id",photoid+"");
Log.d("Length of posts",""+posts.size());
pa.notifyDataSetChanged();
}
}
}
class PostAdapter extends ArrayAdapter<eachpost>
{
ViewHolder vholder;
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File (root + ".feed");
Map<Integer,View> myViews;
public PostAdapter(Context context, int resource, ArrayList<eachpost> list, LayoutInflater li) {
super(context, R.layout.postcontent, list);
myViews = new HashMap<Integer,View>();
}
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
row.setTag(vholder);
myViews.put(pos, row);
}
return row;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
} //end of adapter class
static class ViewHolder {
TextView handle;
TextView caption;
TextView likesnum;
TextView comnum;
TextView uploadtime;
ImageView photo;
CircularImageView feeddp;
FlipImageView like;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.currentVisibleItemCount > 0 && scrollState == SCROLL_STATE_FLING) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(currentFirstVisibleItem > (currentVisibleItemCount - 2) && Loading!=true)
{
new GetData(photoid).execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
}

When loading multiple images there is always caching problem when using Async Tasks. I recommend an open source library Picasso. It will load the images and cache it. After that most probably, your fast scroll problem will solve.
The cause can also be the size of the images being received. Picasso has methods by which you can resize the image before putting it onto the image view

try with this modified getView
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
row.setTag(vholder); //changed here setTag()
}else{
vholder=(ViewHolder)row.getTag(); //changed here getTag()
}
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
myViews.put(pos, row);
}
return row;
}

Related

How to update imageview from the parent recyclerview after click on nested recyclerview's imageview

Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}

EditText textIsSelectable="false" not working in listview

In my android app I have listView with editTexts in it. I'm setting textIsSelectable for editTexts to false but text still stay selectable. For textViews everything work fine. Same result when I'm doing it programmatically in adapter.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/back"
android:clipToPadding="true"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginStart="10dp"
android:elevation="1dp"
android:layout_marginEnd="10dp"
android:padding="10dp"
android:weightSum="10">
<TextView
android:id="#+id/key"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:layout_weight="7"
/>
<EditText
android:id="#+id/value"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#aaaaaa"
android:textIsSelectable="false"
android:inputType="none"
android:padding="2dip"
android:textSize="16sp"
android:background="#ffffff"
android:layout_weight="3"/>
<TextView
android:id="#+id/text_value"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textIsSelectable="true"
android:autoLink="all"
android:padding="2dip"
android:textSize="16sp"
android:layout_weight="3"
android:visibility="gone"/>
<ImageView
android:id="#+id/img"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_weight="3"
android:adjustViewBounds="true"
android:clickable="true"/>
</LinearLayout>
</RelativeLayout>
My custom adapter.
class MyListViewAdapter extends ArrayAdapter<KeyValueList>
{
private int layoutResource;
private String rowId = "-", string = "-";
private String pos = "0";
private String vallue;
private int i = 0;
MyListViewAdapter(Context context, int layoutResource, List<KeyValueList> keyValueList)
{
super(context, layoutResource, keyValueList);
this.layoutResource = layoutResource;
setDefaultsInt("first", 1, getContext());
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#NonNull
#Override
public View getView(final int position, final View convertView, #NonNull ViewGroup parent)
{
KeyValueList keyValuelist = getItem(position);
View view = convertView;
if (view == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(layoutResource, null);
ViewHolder holder = new ViewHolder();
holder.textView = (TextView) view.findViewById(R.id.key);
holder.editText = (EditText) view.findViewById(R.id.value);
holder.text_value = (TextView) view.findViewById(R.id.text_value);
holder.imageView = (ImageView) view.findViewById(R.id.img);
view.setTag(holder);
}
final ViewHolder holder = (ViewHolder) view.getTag();
if(openEntry.isEditable)
{
holder.text_value.setVisibility(View.GONE);
holder.editText.setVisibility(View.VISIBLE);
}
if(!openEntry.isEditable)
{
holder.text_value.setVisibility(View.VISIBLE);
holder.editText.setVisibility(View.GONE);
}
if (holder.textWatcher != null)
holder.editText.removeTextChangedListener(holder.textWatcher);
holder.textWatcher = new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
if(!s.toString().equals(vallue))
{
if(getDefaultsInt("first",getContext()) == 1)
{
openEntry.edit_list.add(null);
setDefaultsInt("p", position, getContext());
setDefaultsInt("first", 0, getContext());
}
if(getDefaultsInt("p", getContext()) != position)
{
openEntry.edit_list.add(null);
i++;
setDefaultsInt("p", position, getContext());
}
try
{
rowId = getRowID(position);
string = s.toString();
pos = String.valueOf(position);
} catch (JSONException e)
{
e.printStackTrace();
}
HashMap<String, String> edit = new HashMap<>();
edit.put("rowID", rowId);
edit.put("string", string);
edit.put("position", pos);
openEntry.edit_list.set(i, edit);
}
}
};
holder.editText.addTextChangedListener(holder.textWatcher);
assert keyValuelist != null;
holder.textView.setText(keyValuelist.getKey());
vallue = keyValuelist.getValue();
if (vallue.length() != 0 && vallue.contains("printFile"))
{
final String durl = vallue.replace("printFile","file");
new DownloadImageTask(holder.imageView).execute(vallue);
holder.editText.setVisibility(View.GONE);
holder.text_value.setVisibility(View.GONE);
holder.imageView.setVisibility(View.VISIBLE);
holder.imageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Uri uriUrl = Uri.parse(durl);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
getContext().startActivity(launchBrowser);
}
});
}
else
{
holder.editText.setText(vallue);
holder.text_value.setText(vallue);
}
return view;
}
et.setFocusable(false);
et.setTextIsSelectable(false);
//if clickble then true otherwise false
et.setClickable(true);

Gridview scrolling images not working smoothly in android

Hi in the below displaying all the images into gridview.gridview images displaying correctly.default gridview will give scroll option,Now Scrolling images it's not scrolling smoothly.
Can any one help me .how to scroll smoothly all the images like normal scrolling.this is my below code any where i did mistake please help me
java
public class GridFragment2 extends Fragment {
private static final String TAG = GridFragment.class.getSimpleName();
public static boolean isSelectedGrid2;
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter2 mGridAdapter;
private ArrayList<GridItem> mGridData;
private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45", searchKey;
String vv;
LinearLayout top;
View hr;
String catid;
SharedPreferences imgSh;
SharedPreferences p, got;
public GridFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview2, container, false);
mGridView = (GridView)rootView.findViewById(R.id.gridView);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
top = (LinearLayout)rootView.findViewById(R.id.top);
hr = rootView.findViewById(R.id.hr);
top.setVisibility(View.GONE);
hr.setVisibility(View.GONE);
imgSh = this.getActivity().getSharedPreferences("data", Context.MODE_APPEND);
p = this.getActivity().getSharedPreferences("gridData", Context.MODE_APPEND);
got = this.getActivity().getSharedPreferences("gotData", Context.MODE_APPEND);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter2(rootView.getContext(), R.layout.grid_item_layout2, mGridData);
mGridView.setAdapter(mGridAdapter);
//Grid view click event
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Get item at position
isSelectedGrid2=true;
String catalogueID = p.getString("SelectedCatalogueIdFromGrid1", "");
GridItem item = (GridItem) parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ImageGallery.class);
ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
SharedPreferences prefPosition=getActivity().getSharedPreferences("positionPref", Context.MODE_PRIVATE);
SharedPreferences.Editor positionEditor=prefPosition.edit();
positionEditor.putInt("position", position);
positionEditor.commit();
//Pass the image title and url to DetailsActivity
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("title", item.getTitle()).
putExtra("image", item.getImage()).
putExtra("catid", catalogueID).putExtra("position",position);
// Log.d("image", (item.getImage()).toString());
//Start details activity
getActivity().finish();
startActivity(intent);
}
});
//Start download
new AsyncHttpTask().execute(FEED_URL);
mProgressBar.setVisibility(View.VISIBLE);
return rootView;
}
//Downloading data asynchronously
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 1;
parseResult();
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Lets update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(getActivity().getBaseContext(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult() {
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedPosn = p.getInt("clickedPosition", 0);
int count = p.getInt("numOfImagesInside"+catid+clickedPosn, 0);
Log.d("counterman-id", String.valueOf(count));
GridItem item;
for (int i = 0; i < count; i++) {
item = new GridItem();
item.setTitle("");
// item.setImage("file://" + Environment.getExternalStorageDirectory() + "/" + "thumbImage" + catid + i + ".jpg");
item.setImage("/data/data/com.example.adaptiz.tanishq/"+"thumbImage" + catid + i+".jpg");
// item.setImage(imgSh.getString("thumb" + i, ""));
mGridData.add(item);
}
}
Adapter
public class GridViewAdapter2 extends ArrayAdapter<GridItem> {
//private final ColorMatrixColorFilter grayscaleFilter;
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter2(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
*
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
Typeface type_normal = Typeface.createFromAsset(getContext().getAssets(), "HelveticaNeue-Light.otf");
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.titleTextView.setTypeface(type_normal);
holder.download=(ImageView)row.findViewById(R.id.img);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getTitle()));
File image = new File(item.getImage(), "");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, 230, 230, true);
Log.d("the bitmap size", String.valueOf(bitmap.getWidth() + " " + bitmap.getHeight()));
holder.imageView.setImageBitmap(bitmap);
//bitmap=null;
// Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
ImageView download;
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/toprel"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/top"
android:orientation="horizontal"
android:layout_alignParentTop="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/searchTitle"
android:layout_centerVertical="true"
android:text="Search"
android:textSize="15sp"
android:gravity="left"
android:layout_toRightOf="#+id/leftTitle"
android:layout_toEndOf="#+id/leftTitle" />
<EditText
android:inputType="text"
android:layout_centerVertical="true"
android:layout_width="200dp"
android:layout_height="30dp"
android:id="#+id/searchBox"
android:background="#drawable/searchbg2x"
android:layout_toRightOf="#+id/searchTitle"
android:layout_toEndOf="#+id/searchTitle"
android:layout_marginLeft="15dp"
android:singleLine="true"
android:imeOptions="actionSearch"
/>
</LinearLayout>
<View
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:id="#+id/hr"
android:background="#000000"
android:layout_below="#id/top"
/>
<GridView
android:layout_below="#+id/hr"
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="200dp"
android:gravity="center"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:listSelector="#android:color/transparent"
android:clickable="true"
android:fastScrollEnabled="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="20dp"
android:orientation="horizontal"
android:id="#+id/userlayout"
android:layout_alignParentTop="true"
android:visibility="gone"
android:layout_alignRight="#+id/gridView"
android:layout_alignEnd="#+id/gridView"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="18sp"
android:id="#+id/userView"
android:text="username"
/>
<ImageView
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_width="20dp"
android:layout_height="10dp"
android:background="#drawable/icon"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/gridView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
For that you have to use Image Loader to load image.
Refer below link for that.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

listview issue from android version 4.4(kitkat) and above android version

I am developing chat application.i am facing issue in listview odd behavior. My code is working perfectly below android OS 4.4. but when running my application in 4.4 kitkat then i am facing issue.
please check below Screenshots.
Suppose my First message length is large then my Second message height get same.
In Second Screenshot it will show proper view of last message. Because i have close my keyboard and adapter get refresh at the same time first visible view height gets increase automatically.
public class ChatAdapter extends BaseAdapter {
LayoutInflater mInflater;
ChatActivity chatActivity;
private DatabaseHandler DatabaseHandler;
private DatabaseHandler dbHelper;
private List<HBMessage> mList = new ArrayList<HBMessage>();
private Context mContext;
public ChatAdapter(ChatActivity chatActivity) {
this.chatActivity = chatActivity;
mContext = chatActivity;
DatabaseHandler = new DatabaseHandler(mContext);
dbHelper = new DatabaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public HBMessage getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder {
private RelativeLayout mSimpleRecieveLayout, mSimpleSenderLayout, rlImageSendLayout, rlImageReceiveLayout, mRecieveImageLayout;
private LinearLayout mSentImageLayout;
private TextView simpleFriendMessage, simpleFriendMessageTime, simpleMyMessage, simpleMyMessageTime, mtxtImageSentTime,
mtxtImageRecieveTime;
private ImageView mimgSent, mimgRecieve, mplayordownload, mplayorupload;
private TextView mMsgStatus, mtxtImageStatus;
private ProgressBar mSentProgress, mDownloadProgress;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Holder mHolder;
if (convertView == null) {
mHolder = new Holder();
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.single_chat_item, null);
mHolder.mSimpleRecieveLayout = (RelativeLayout) convertView.findViewById(R.id.recive_layout);
mHolder.mSimpleSenderLayout = (RelativeLayout) convertView.findViewById(R.id.sender_layout);
mHolder.mSentImageLayout = (LinearLayout) convertView.findViewById(R.id.sentImageLayout);
mHolder.mRecieveImageLayout = (RelativeLayout) convertView.findViewById(R.id.recieveImageLayout);
mHolder.simpleFriendMessage = (TextView) convertView.findViewById(R.id.txtMesssageSender);
mHolder.simpleFriendMessageTime = (TextView) convertView.findViewById(R.id.txtTimeSender);
mHolder.mtxtImageRecieveTime = (TextView) convertView.findViewById(R.id.txtImageRecieveTime);
mHolder.simpleMyMessage = (TextView) convertView.findViewById(R.id.txtMesssageRecieve);
mHolder.simpleMyMessageTime = (TextView) convertView.findViewById(R.id.txtTimeRecieve);
mHolder.mtxtImageSentTime = (TextView) convertView.findViewById(R.id.txtImageSentTime);
mHolder.mMsgStatus = (TextView) convertView.findViewById(R.id.txtStatusSender);
mHolder.mtxtImageStatus = (TextView) convertView.findViewById(R.id.txtImageSentStatus);
mHolder.mimgSent = (ImageView) convertView.findViewById(R.id.imgSent);
mHolder.mimgRecieve = (ImageView) convertView.findViewById(R.id.imgRecieve);
mHolder.mSentProgress = (ProgressBar) convertView.findViewById(R.id.sentProgress);
mHolder.mplayordownload = (ImageView) convertView.findViewById(R.id.playordownload);
mHolder.mplayorupload = (ImageView) convertView.findViewById(R.id.playorupload);
mHolder.mDownloadProgress = (ProgressBar) convertView.findViewById(R.id.downloadProgress);
mHolder.rlImageSendLayout = (RelativeLayout) convertView.findViewById(R.id.chat_rlSendImage);
mHolder.rlImageReceiveLayout = (RelativeLayout) convertView.findViewById(R.id.chat_rlReceiveImage);
int tempWidth = (int) (BaseApplication.SCREEN_WIDTH * 0.28);
int tempHeight = (int) (BaseApplication.SCREEN_WIDTH * 0.26);
int imageSize = (int) (tempHeight * 0.84);
LinearLayout.LayoutParams param1 = (LayoutParams) mHolder.rlImageSendLayout.getLayoutParams();
param1.width = tempWidth;
param1.height = tempHeight;
mHolder.rlImageSendLayout.setLayoutParams(param1);
RelativeLayout.LayoutParams param2 = (android.widget.RelativeLayout.LayoutParams) mHolder.rlImageReceiveLayout
.getLayoutParams();
param2.width = tempWidth;
param2.height = tempHeight;
mHolder.rlImageReceiveLayout.setLayoutParams(param2);
RelativeLayout.LayoutParams param3 = (android.widget.RelativeLayout.LayoutParams) mHolder.mimgSent.getLayoutParams();
param3.width = imageSize;
param3.height = imageSize;
mHolder.mimgSent.setLayoutParams(param3);
RelativeLayout.LayoutParams param4 = (android.widget.RelativeLayout.LayoutParams) mHolder.mimgRecieve.getLayoutParams();
param4.width = imageSize;
param4.height = imageSize;
mHolder.mimgRecieve.setLayoutParams(param4);
convertView.setTag(mHolder);
} else {
mHolder = (Holder) convertView.getTag();
}
if ((mList.get(position).getFromJID().equalsIgnoreCase(UserDetails.getInstance(mContext).getJabberId() + WSUtils.CHAT_DOMAIN))) {
setMyLayout(mList.get(position), mHolder, position, convertView);
} else {
setOtherLayout(mList.get(position), mHolder, position);
}
return convertView;
}
XML inflater Layout
<RelativeLayout
android:id="#+id/sender_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:clickable="false"
android:visibility="visible" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:background="#drawable/chat_sender"
android:orientation="vertical" >
<com.hb.utils.CustomTextView
android:id="#+id/txtMesssageSender"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="#dimen/chatpadding"
android:layout_marginRight="#dimen/chatpadding"
android:layout_weight="1"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/color_text"
android:textSize="#dimen/chattext"
app:type="common" />
<com.hb.utils.CustomTextView
android:id="#+id/txtTimeSender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginBottom="#dimen/chat_nagetive_pad"
android:layout_marginRight="#dimen/chatpadding"
android:layout_marginEnd="#dimen/chatpadding"
android:layout_marginTop="2dp"
android:textColor="#color/graychars"
android:textSize="#dimen/chattime"
app:type="common" />
<com.hb.utils.CustomTextView
android:id="#+id/txtStatusSender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginRight="#dimen/chatpadding"
android:layout_marginEnd="#dimen/chatpadding"
android:requiresFadingEdge="vertical"
android:textColor="#color/color_regular_green"
android:textSize="#dimen/chattime"
app:type="common" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/recive_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/chat_receiver"
android:orientation="vertical" >
<com.hb.utils.CustomTextView
android:id="#+id/txtMesssageRecieve"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="#dimen/chatpadding"
android:layout_marginRight="#dimen/chatpadding"
android:layout_weight="1"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/color_text"
android:textSize="#dimen/chattext"
app:type="common" />
<com.hb.utils.CustomTextView
android:id="#+id/txtTimeRecieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginRight="#dimen/chatpadding"
android:layout_marginEnd="#dimen/chatpadding"
android:layout_marginTop="2dp"
android:requiresFadingEdge="vertical"
android:textColor="#color/graychars"
android:textSize="#dimen/chattime"
app:type="common" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/sentImageLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/chat_rlSendImage"
android:layout_width="210px"
android:layout_height="210px"
android:layout_gravity="end"
android:background="#drawable/chat_sender"
android:gravity="end|center_vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/chatpadding" >
<ImageView
android:id="#+id/imgSent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/noimage" />
<ProgressBar
android:id="#+id/sentProgress"
style="?android:attr/progressBarStyleInverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
<ImageView
android:id="#+id/playorupload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/upload"
android:visibility="gone" />
</RelativeLayout>
</RelativeLayout>
<com.hb.utils.CustomTextView
android:id="#+id/txtImageSentTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginBottom="#dimen/chat_nagetive_pad"
android:layout_marginRight="#dimen/chatimagetext"
android:layout_marginEnd="#dimen/chatimagetext"
android:layout_marginTop="2dp"
android:textColor="#color/graychars"
android:textSize="#dimen/chattime"
app:type="common" />
<com.hb.utils.CustomTextView
android:id="#+id/txtImageSentStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginRight="#dimen/chatimagetext"
android:layout_marginEnd="#dimen/chatimagetext"
android:textColor="#color/color_regular_green"
android:textSize="#dimen/chattime"
app:type="common" />
</LinearLayout>
<RelativeLayout
android:id="#+id/recieveImageLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/chat_rlReceiveImage"
android:layout_width="210px"
android:layout_height="210px"
android:background="#drawable/chat_receiver"
android:gravity="center_vertical" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/chatpadding" >
<ImageView
android:id="#+id/imgRecieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/noimage" />
<ProgressBar
android:id="#+id/downloadProgress"
style="?android:attr/progressBarStyleInverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<ImageView
android:id="#+id/playordownload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/download" />
</RelativeLayout>
</RelativeLayout>
<com.hb.utils.CustomTextView
android:id="#+id/txtImageRecieveTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#id/chat_rlReceiveImage"
android:layout_alignEnd="#id/chat_rlReceiveImage"
android:layout_below="#id/chat_rlReceiveImage"
android:textColor="#color/graychars"
android:textSize="#dimen/chattime"
app:type="common" />
</RelativeLayout>
private synchronized void setOtherLayout(HBMessage hbMessage, final Holder mHolder, final int position) {
if (hbMessage.getMsgType().equalsIgnoreCase(HBMessage.IMAGE)) {
mHolder.mSimpleRecieveLayout.setVisibility(View.GONE);
mHolder.mSimpleSenderLayout.setVisibility(View.GONE);
mHolder.mSentImageLayout.setVisibility(View.GONE);
mHolder.mRecieveImageLayout.setVisibility(View.VISIBLE);
mHolder.mplayordownload.setTag(position);
mHolder.mimgRecieve.setTag(position);
String str = hbMessage.getMessage();
final String seperatedString[] = str.split("###!###");
if (hbMessage.getMediaStatus().equals(HBMessage.NOTDOWNLOADED)) {
mHolder.mplayordownload.setVisibility(View.VISIBLE);
mHolder.mDownloadProgress.setVisibility(View.GONE);
} else if (hbMessage.getMediaStatus().equals(HBMessage.DOWNLOADING)) {
mHolder.mplayordownload.setVisibility(View.GONE);
mHolder.mDownloadProgress.setVisibility(View.VISIBLE);
} else {
mHolder.mplayordownload.setVisibility(View.GONE);
mHolder.mDownloadProgress.setVisibility(View.GONE);
}
mHolder.mtxtImageRecieveTime.setText(StaticUtils.getChatHistoryDateTime(hbMessage.getMessageTime()));
chatActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mHolder.mimgRecieve.setImageBitmap(getImageFromBase64StringWithTimeStamp(seperatedString[0]));
}
});
mHolder.mplayordownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View paramView) {
paramView.setVisibility(View.GONE);
int pos = (Integer) paramView.getTag();
HBMessage message = getItem(pos);
final String name[] = message.getMessage().split("###!###");
if (dbHelper.isImageAvaialble(name[1])) {
DatabaseHandler.updateImageStatus(mContext, message.getMessageId(), HBMessage.DOWNLOADED, HBMessage.CHAT_SINGLE);
message.setMediaStatus(HBMessage.DOWNLOADED);
setItem(message, pos);
} else {
((ViewGroup) paramView.getParent()).findViewById(R.id.downloadProgress).setVisibility(View.VISIBLE);
message.setMediaStatus(HBMessage.DOWNLOADING);
setItem(message, position);
chatActivity.callDownloadfileProcess(pos, ((ViewGroup) paramView.getParent()));
}
}
});
} else {
mHolder.mSimpleRecieveLayout.setVisibility(View.VISIBLE);
mHolder.mSimpleSenderLayout.setVisibility(View.GONE);
mHolder.mSentImageLayout.setVisibility(View.GONE);
mHolder.mRecieveImageLayout.setVisibility(View.GONE);
mHolder.simpleMyMessageTime.setText(StaticUtils.getChatHistoryDateTime(hbMessage.getMessageTime()));
mHolder.simpleMyMessage.setText(hbMessage.getMessage());
}
}
private synchronized void setMyLayout(HBMessage hbMessage, final Holder mHolder, int position, View view) {
if (hbMessage.getMsgType().equalsIgnoreCase(HBMessage.IMAGE)) {
mHolder.mSimpleRecieveLayout.setVisibility(View.GONE);
mHolder.mSimpleSenderLayout.setVisibility(View.GONE);
mHolder.mRecieveImageLayout.setVisibility(View.GONE);
mHolder.mSentImageLayout.setVisibility(View.VISIBLE);
String str = hbMessage.getMessage();
final String seperatedString[] = str.split("###!###");
mHolder.mimgSent.setTag(position);
mHolder.mplayorupload.setTag(position);
if (hbMessage.getMediaStatus().equals(HBMessage.NOTUPLOADED)) {
mHolder.mplayorupload.setVisibility(View.VISIBLE);
mHolder.mSentProgress.setVisibility(View.GONE);
} else if (hbMessage.getMediaStatus().equals(HBMessage.UPLOADING)) {
mHolder.mplayorupload.setVisibility(View.GONE);
mHolder.mSentProgress.setVisibility(View.VISIBLE);
} else {
mHolder.mplayorupload.setVisibility(View.GONE);
mHolder.mSentProgress.setVisibility(View.GONE);
}
mHolder.mSentProgress.setTag(view);
mHolder.mtxtImageSentTime.setText(StaticUtils.getChatHistoryDateTime(hbMessage.getMessageTime()));
chatActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mHolder.mimgSent.setImageBitmap(getImageFromBase64StringWithTimeStamp(seperatedString[0]));
}
});
mHolder.mtxtImageStatus.setText(hbMessage.getMessageStatus());
if (hbMessage.getMessageStatus().equals(HBMessage.STATUS_PENDDING)
|| hbMessage.getMessageStatus().equals(HBMessage.STATUS_FAILED)) {
mHolder.mtxtImageStatus.setTextColor(mContext.getResources().getColor(R.color.color_pending_red));
} else if (hbMessage.getMessageStatus().equals(HBMessage.STATUS_DELIVERED)) {
mHolder.mtxtImageStatus.setTextColor(mContext.getResources().getColor(R.color.color_black));
} else
mHolder.mtxtImageStatus.setTextColor(mContext.getResources().getColor(R.color.color_green));
if (hbMessage.isAutoUpload()) {
ImageHolder mImageHolder = dbHelper.getImageHolder(seperatedString[1]);
File mFile = StaticUtils.bitmapToFile(mImageHolder.getBitmap(), mImageHolder.getFileName(), false);
if (mFile != null) {
hbMessage.setAutoUpload(false);
mList.set(position, hbMessage);
chatActivity.uploadToserver(mFile, mImageHolder.getFileName(), hbMessage, position, view);
} else {
CommonUtils.showSingleBtnDialog("Image Not Available", mContext, null);
}
}
mHolder.mplayorupload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View paramView) {
int pos = (Integer) paramView.getTag();
HBMessage message = getItem(pos);
final String seperatedString[] = message.getMessage().split("###!###");
ImageHolder mImageHolder = dbHelper.getImageHolder(seperatedString[1]);
File mFile = StaticUtils.bitmapToFile(mImageHolder.getBitmap(), mImageHolder.getFileName(), false);
if (mFile != null) {
paramView.setVisibility(View.GONE);
ProgressBar pb = (ProgressBar) ((ViewGroup) paramView.getParent()).findViewById(R.id.sentProgress);
pb.setVisibility(View.VISIBLE);
View view = (View) pb.getTag();
((TextView) view.findViewById(R.id.txtImageSentStatus)).setText(HBMessage.STATUS_PENDDING);
message.setMediaStatus(HBMessage.UPLOADING);
message.setMessageStatus(HBMessage.STATUS_PENDDING);
setItem(message, pos);
chatActivity.uploadToserver(mFile, mFile.getName(), message, pos, view);
DatabaseHandler.updateImageStatus(mContext, message.getMessageId(), HBMessage.UPLOADING, HBMessage.CHAT_SINGLE);
} else {
CommonUtils.showSingleBtnDialog("Image Not Available", mContext, null);
}
}
});
} else {
mHolder.mSimpleRecieveLayout.setVisibility(View.GONE);
mHolder.mSimpleSenderLayout.setVisibility(View.VISIBLE);
mHolder.mSentImageLayout.setVisibility(View.GONE);
mHolder.mRecieveImageLayout.setVisibility(View.GONE);
mHolder.simpleFriendMessageTime.setText(StaticUtils.getChatHistoryDateTime(hbMessage.getMessageTime()));
mHolder.simpleFriendMessage.setText(hbMessage.getMessage());
mHolder.mMsgStatus.setText(hbMessage.getMessageStatus());
if (hbMessage.getMessageStatus().equals(HBMessage.STATUS_PENDDING)
|| hbMessage.getMessageStatus().equals(HBMessage.STATUS_FAILED)) {
mHolder.mMsgStatus.setTextColor(mContext.getResources().getColor(R.color.color_pending_red));
} else if (hbMessage.getMessageStatus().equals(HBMessage.STATUS_DELIVERED)) {
mHolder.mMsgStatus.setTextColor(mContext.getResources().getColor(R.color.color_black));
} else
mHolder.mMsgStatus.setTextColor(mContext.getResources().getColor(R.color.color_green));
}
}
Because of the behaviour of view recycling, everything that has to do with content has to be set and un-set regardless if convertView is null or not. You should start by moving the code that has nothing to do with viewHolder binding to after the if-else.
Another option would be to start using RecyclerView which is esentially like ListView that has the recycling mechanism improved (and a lot more). Here is a guide for that.
There are pieces of code you need to execute for all the views, regardless of them being new or recycled. Only the viewholder init part is to be executed only for new views.
if (convertView == null) {
mHolder = new Holder();
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.single_chat_item, null);
mHolder.mSimpleRecieveLayout = (RelativeLayout) convertView.findViewById(R.id.recive_layout);
mHolder.mSimpleSenderLayout = (RelativeLayout) convertView.findViewById(R.id.sender_layout);
mHolder.mSentImageLayout = (LinearLayout) convertView.findViewById(R.id.sentImageLayout);
mHolder.mRecieveImageLayout = (RelativeLayout) convertView.findViewById(R.id.recieveImageLayout);
mHolder.simpleFriendMessage = (TextView) convertView.findViewById(R.id.txtMesssageSender);
mHolder.simpleFriendMessageTime = (TextView) convertView.findViewById(R.id.txtTimeSender);
mHolder.mtxtImageRecieveTime = (TextView) convertView.findViewById(R.id.txtImageRecieveTime);
mHolder.simpleMyMessage = (TextView) convertView.findViewById(R.id.txtMesssageRecieve);
mHolder.simpleMyMessageTime = (TextView) convertView.findViewById(R.id.txtTimeRecieve);
mHolder.mtxtImageSentTime = (TextView) convertView.findViewById(R.id.txtImageSentTime);
mHolder.mMsgStatus = (TextView) convertView.findViewById(R.id.txtStatusSender);
mHolder.mtxtImageStatus = (TextView) convertView.findViewById(R.id.txtImageSentStatus);
mHolder.mimgSent = (ImageView) convertView.findViewById(R.id.imgSent);
mHolder.mimgRecieve = (ImageView) convertView.findViewById(R.id.imgRecieve);
mHolder.mSentProgress = (ProgressBar) convertView.findViewById(R.id.sentProgress);
mHolder.mplayordownload = (ImageView) convertView.findViewById(R.id.playordownload);
mHolder.mplayorupload = (ImageView) convertView.findViewById(R.id.playorupload);
mHolder.mDownloadProgress = (ProgressBar) convertView.findViewById(R.id.downloadProgress);
mHolder.rlImageSendLayout = (RelativeLayout) convertView.findViewById(R.id.chat_rlSendImage);
mHolder.rlImageReceiveLayout = (RelativeLayout) convertView.findViewById(R.id.chat_rlReceiveImage);
convertView.setTag(mHolder);
} else {
mHolder = (Holder) convertView.getTag();
}
// This is now executed for all your views.
int tempWidth = (int) (BaseApplication.SCREEN_WIDTH * 0.28);
int tempHeight = (int) (BaseApplication.SCREEN_WIDTH * 0.26);
int imageSize = (int) (tempHeight * 0.84);
LinearLayout.LayoutParams param1 = (LayoutParams) mHolder.rlImageSendLayout.getLayoutParams();
param1.width = tempWidth;
param1.height = tempHeight;
mHolder.rlImageSendLayout.setLayoutParams(param1);
RelativeLayout.LayoutParams param2 = (android.widget.RelativeLayout.LayoutParams) mHolder.rlImageReceiveLayout
.getLayoutParams();
param2.width = tempWidth;
param2.height = tempHeight;
mHolder.rlImageReceiveLayout.setLayoutParams(param2);
RelativeLayout.LayoutParams param3 = (android.widget.RelativeLayout.LayoutParams) mHolder.mimgSent.getLayoutParams();
param3.width = imageSize;
param3.height = imageSize;
mHolder.mimgSent.setLayoutParams(param3);
RelativeLayout.LayoutParams param4 = (android.widget.RelativeLayout.LayoutParams) mHolder.mimgRecieve.getLayoutParams();
param4.width = imageSize;
param4.height = imageSize;
mHolder.mimgRecieve.setLayoutParams(param4);
Also, you should really consider reading more about having different view types in an adaptor (myLayout and otherLayout in your case). A starting point would be this.
Finally I have solved this issue by applying stupid thing.Why i am facing issue,that i really don't know and Why its get solved after applying patch that i really don't know.
**My Solution:**
setMyLayout()
{
mHolder.mSentMessageLayout
.setBackgroundResource(R.drawable.chat_sender);
}
setOtherLayout()
{
mHolder.mRecieveMessageLayout
.setBackgroundResource(R.drawable.chat_receiver);
}

Updating ListView items with AsyncTask

I have the follow scenario:
One activity that consults values from internet and fills an object below:
public class LPBean {
private Lin lin;
private Posted posted;
public Lin getLin() {
return lin;
}
public void setLin(Lin lin) {
this.lin = lin;
}
public Posted getPosted() {
return posted;
}
public void setEstimativa(Posted p) {
this.posted = p;
}
}
My activity fill the lin information in LPBean from internet and pass the object to CustomAdapter
But the posted value from LPBean is populated with information from the internet and the search key is lin.id (form LPBean),so tho do this, I'm using a AsynkTask.
Thus, the listView is showing to user and the posted values (from LpBean) are displayed dynamically with listView opened.
To do this, I make like below:
public class ListaLinsAdapter extends BaseAdapter {
private Context context;
private List<LinPostedBean> lins;
private LayoutInflater inflater;
private ViewHolder holder;
private String idLin;
public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
this.context = context;
this.lins = listaLins;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lins.size();
}
#Override
public Object getItem(int position) {
return lins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// Recupera o estado da posição atual
LinPostedBean lpBean = lins.get(position);
Lin lin = lpBean.getLin();
do somthing.....
and at the end of the getView method from adapter, is verified if has value to posted attribute to show the information
if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
{
if(lpBean.getPosted().getPonto().size() > 0)
holder.fillPosted(lpBean.getPosted());
else
holder.showMsg(context.getResources().getString(R.string.msgEmptyPosted));
}
return view;
}
In my activity I have implemented the AsyncTask inner class like below:
private class ConsultaPostedBackGround extends AsyncTask<Object, Void, Object[]> {
#Override
protected Object[] doInBackground(Object... objs) {
try {
LinPostedBean lpBean = (LinPostedBean)objs[0];
Context context = (Context)objs[3];
String linId = lpBean.getLin().getLin();
int indice = linId.indexOf("-");
linId = linId.substring(0,indice).trim();
//GET INFORMATION FROM INTERNET
PostedUtil pUtil = new PostedUtil(pontoId.trim(), linId,
context);
//PUT INTERNET RESULT IN Posted ATTRUBUTE IN ADAPTER
Integer position = (Integer)objs[1];
((LinPostedBean)((ListaLinsAdapter)objs[2]).getItem(position)).setEstimativa(pUtil.getPosted());
} catch (Exception e) {
objs[3] = null;
}
return objs;
}
#Override
protected void onPostExecute(Object[] result) {
//REFRESH LISTVIEW
if(result[3] != null)
((ListaLinsAdapter)result[2]).notifyDataSetChanged();
}
In the activity I'm call the AsyncTask one time to each lin, like below:
ListView lista = (ListView) findViewById(R.id.listView);
lista.setAdapter(listaLinsAdapter);
lista.setOnItemClickListener(this);
int cont = 0;
for (LinPostedBean lpBean : listaLPBean) {
Object[] params = new Object[4];
params[0] = lpBean;
params[1] = new Integer(cont);
params[2] = listaLinsAdapter;
params[3] = this;
//CALL TO AsyncTask
new ConsultaPrevisaoBackGround().execute(params);
cont++;
}
I think that this strategy are correct, but not working. The values of posted is not
showing in listview.
What is wrong??
UPDATED
My class Adapter:
public class ListaLinsAdapter extends BaseAdapter {
private Context context;
private List<LinPostedBean> lins;
private LayoutInflater inflater;
private ViewHolder holder;
private String idLin;
public ListaLinsAdapter(Context context, List<LinPostedBean> listaLins) {
this.context = context;
this.lins = listaLins;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lins.size();
}
#Override
public Object getItem(int position) {
return lins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// Recupera o estado da posição atual
LinPostedBean lpBean = lins.get(position);
Lin lin = lpBean.getLin();
if (view == null) {
view = inflater.inflate(R.layout.listadadoslins, null);
holder = new ViewHolder(context);
// Número da lin
holder.txtIdLin = (TextView) view.findViewById(R.id.txtIdLin);
// Nome da lin
holder.txtNomeLin = (TextView) view
.findViewById(R.id.txtNomeLin);
// Seta campo de informação sem parada
holder.txtMsgSemParada = (TextView) view
.findViewById(R.id.msgSemParada);
// seta layouts de previsão
holder.llLin1 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes1);
holder.llLin2 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes2);
holder.llLin3 = (LinearLayout) view
.findViewById(R.id.linearPrevisoes3);
// Seta campos de previsão
holder.txtPrev1 = (TextView) view.findViewById(R.id.txtPrev1);
holder.txtPrev2 = (TextView) view.findViewById(R.id.txtPrev2);
holder.txtPrev3 = (TextView) view.findViewById(R.id.txtPrev3);
holder.txtPrev4 = (TextView) view.findViewById(R.id.txtPrev4);
holder.txtPrev5 = (TextView) view.findViewById(R.id.txtPrev5);
holder.txtPrev6 = (TextView) view.findViewById(R.id.txtPrev5);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.reset();
}
String lin = lin.getLin().trim();
StringTokenizer stk = new StringTokenizer(lin, "-");
// Número da lin
idLin = stk.nextToken();
holder.txtIdLin.setText(idLin);
// Nome da lin
holder.txtNomeLin.setText(stk.nextToken());
//new ConsultaPostedBackGround().execute("");
if((lpBean.getPosted() != null) && (lpBean.getPosted().getPonto() != null))
{
if(lpBean.getPosted().getPonto().size() > 0)
holder.fillPosted(lpBean.getPosted());
else
holder.showMsg(context.getResources().getString(R.string.msgSemPosted));
}
return view;
}
static class ViewHolder {
Context context;
TextView txtIdLin;
TextView txtNomeLin;
TextView txtMsgSemParada;
LinearLayout llLin1;
LinearLayout llLin2;
LinearLayout llLin3;
TextView txtPrev1;
TextView txtPrev2;
TextView txtPrev3;
TextView txtPrev4;
TextView txtPrev5;
TextView txtPrev6;
public ViewHolder(Context cont) {
this.context = cont;
}
public void reset() {
txtIdLin.setText(null);
txtNomeLin.setText(null);
limpaPrevisoes();
}
private void limpaPrevisoes() {
llLin1.setVisibility(View.GONE);
llLin2.setVisibility(View.GONE);
llLin3.setVisibility(View.GONE);
txtMsgSemParada.setVisibility(View.GONE);
txtPrev1.setText(null);
txtPrev2.setText(null);
txtPrev3.setText(null);
txtPrev4.setText(null);
txtPrev5.setText(null);
txtPrev6.setText(null);
}
public void showError() {
showMsg(context.getResources().getString(R.string.msgErroPosted));
}
public void showMsg(String msg) {
limpaPrevisoes();
txtMsgSemParada.setText(msg);
}
public void fillPosted(Posted p) {
Collections.sort(p.getPonto());
if (p.getPonto().size() > 6) {
for (int i = 6; i < p.getPonto().size(); i++)
p.getPonto().remove(i);
}
int cont = 1;
for (Estimativa estimativa : p.getPonto()) {
setPosted(cont, estimativa, p);
cont++;
}
if (p.getPonto().size() <= 2) {
llLin2.setVisibility(View.GONE);
llLin3.setVisibility(View.GONE);
}
if ((p.getPonto().size() > 2) && (p.getPonto().size() <= 4))
llLin3.setVisibility(View.GONE);
}
// Preenche o campo referente à estimativa
private void setPosted(int id, Estimativa estimativa,
Posted posted) {
switch (id) {
case 1:
txtPrev1.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev1);
break;
case 2:
txtPrev2.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev2);
break;
case 3:
txtPrev3.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev3);
break;
case 4:
txtPrev4.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev4);
break;
case 5:
txtPrev5.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev5);
break;
case 6:
txtPrev6.setText(getgetPostedFormatedPosted(posted, estimativa));
setBackGroundColor(estimativa, txtPrev6);
break;
default:
break;
}
}
private String getgetPostedFormatedPosted(Posted posted,
Estimativa estimativa) {
String hourStr;
String minutoStr;
long hourAtual = Long.parseLong(posted.getHorarioAtual());
long seconds = (estimativa.getHorarioPacote() - hourAtual) / 1000;
int week = (int) Math.floor(seconds / 604800);
seconds -= week * 604800;
int dias = (int) Math.floor(seconds / 86400);
seconds -= dias * 86400;
int hours = (int) Math.floor(seconds / 3600);
seconds -= hours * 3600;
int minutes = (int) Math.floor(seconds / 60);
seconds -= minutes * 60;
minutes += 1;
if (hours < 10)
hourStr = "0" + hours;
else
hourStr = String.valueOf(hours);
if (minutes < 10)
minutoStr = "0" + minutes;
else
minutoStr = String.valueOf(minutes);
String tempo;
if (hours > 0)
tempo = hourStr + "h " + minutoStr + "min";
else
tempo = minutoStr + "min";
SimpleDateFormat spf = new SimpleDateFormat("HH:mm:ss");
tempo = tempo + " às "
+ spf.format(estimativa.getHorarioEstimado());
return tempo;
}
private void setBackGroundColor(Estimativa estimativa, TextView txtView) {
// Imagem a ser exibida
switch (estimativa.getStatus()) {
case 0:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedVerde));
break;
case 1:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedLaranja));
break;
case 2:
txtView.setBackgroundColor(context.getResources().getColor(
R.color.postedVermelha));
break;
default:
break;
}
}
}
}
My xml of a item in listView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtIdLinha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="6dp"
android:paddingRight="4dp"
android:paddingTop="4dp"
android:text="184"
android:textColor="#color/blue_nightsky"
android:textSize="20sp"
android:textStyle="bold" />
<LinearLayout
android:id="#+id/llPrevisoes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearTit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/txtNomeLinha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="7dp"
android:text="FFFFFF"
android:textColor="#drawable/dialog_itemtextlist_selector"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/msgSemParada"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="7dp"
android:text="#string/msgSemPrevisao"
android:textColor="#drawable/dialog_itemtextlist_selector"
android:textSize="12sp"
android:textStyle="bold"
android:visibility="gone" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp">
<TextView
android:id="#+id/txtPrev1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp" >
<TextView
android:id="#+id/txtPrev3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearPrevisoes3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp">
<TextView
android:id="#+id/txtPrev5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
<TextView
android:id="#+id/txtPrev6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text=""
android:textColor="#color/white"
android:textSize="12dp" >
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
UPDATED
Solved, the problem was in my adapter.
Try adding the following to your ListaLinsAdapter.
public void add(LinPostedBean lpb){
lins.add(lpb);
notifyDataSetChanged();
}
Then call that in doInBackground and you don't need to use onPostExecute in this case.

Categories

Resources