Recycler view onBindViewHolder is repeating a weird pattern - android

I am working on a messaging app which has swipe option to mute or lock conversations, when we press the mute or lock button, small icons are displayed on Recycler view item, but when I try to mute or even lock a certain message it shows the icons on that item but the icons also appears on elements after every 10 counts.
For Example, If I lock the message at position 1, element at position 12 also shows the same icons, if I removed the icon from the first position, icons from the later position is also removed. Any help would be highly appreciated as I am new to android development and still trying to learn.
Picture:
Recycler view items xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp"
android:id="#+id/sample1"
>
<!-- Bottom View Start-->
<LinearLayout
android:id="#+id/leftWrapper"
android:layout_width="120dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:background="#365cf5"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:id="#+id/panelArchieve"
android:orientation="horizontal">
<ImageView
android:id="#+id/archieve"
android:src="#drawable/archieve"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
<LinearLayout
android:background="#d20909"
android:id="#+id/bottom_wrapper"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/trash"
android:src="#drawable/trash"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_wrapper_2"
android:layout_width="120dp"
android:weightSum="1"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:background="#365dea"
android:layout_width="60dp"
android:weightSum="1"
android:layout_height="match_parent"
android:id="#+id/panelLock"
android:orientation="horizontal">
<ImageView
android:id="#+id/lock"
android:src="#drawable/lock"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
<LinearLayout
android:background="#0e9b04"
android:layout_width="60dp"
android:weightSum="1"
android:id="#+id/panelMute"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/mute"
android:src="#drawable/mute"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="27dp"/>
</LinearLayout>
</LinearLayout>
<!-- Bottom View End-->
<!-- Surface View Start -->
<LinearLayout
android:padding="10dp"
android:background="#303030"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/rv_img_name"
android:src="#drawable/logo"
android:padding="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:layout_marginLeft="10dp"
android:layout_marginTop="9dp"
android:layout_marginRight="2dp"
android:id="#+id/rv_title"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/rv_img_name"
android:layout_toEndOf="#+id/rv_img_name"
android:maxLines="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/rv_content"
android:textColor="#ffffff"
android:layout_below="#+id/rv_title"
android:layout_alignLeft="#+id/rv_title"
android:layout_alignStart="#+id/rv_title"
android:maxLines="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=""
android:id="#+id/txtTime"
android:textColor="#ffffff"
android:maxLines="1"
android:layout_alignTop="#+id/rv_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="18dp"
android:layout_height="18dp"
android:id="#+id/imgMute"
android:src="#drawable/mute"
android:padding="2dp"
android:layout_marginTop="11dp"
android:layout_toRightOf="#+id/rv_title"
/>
<ImageView
android:layout_width="18dp"
android:layout_height="18dp"
android:id="#+id/imgLock"
android:src="#drawable/lock"
android:padding="2dp"
android:layout_marginTop="11dp"
android:layout_toRightOf="#+id/imgMute" />
</RelativeLayout>
</LinearLayout>
<!-- Surface View End -->
</com.daimajia.swipe.SwipeLayout>
RecyclerViewAdapter
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
//final int position = Texty.position;
final tblMsgs name = mDataset.get(position);
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
#Override
public void onClose(SwipeLayout layout) {
viewHolder.btnDel.setTag("trash");
viewHolder.btnDel.setImageResource(R.drawable.trash);
}
});
//Double click
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
//Toast.makeText(mContext, "Position: " + position, Toast.LENGTH_SHORT).show();
}
});
//Open conversation.
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewHolder.swipeLayout.getOpenStatus() == SwipeLayout.Status.Open) {
mItemManger.closeAllItems();
viewHolder.btnDel.setTag("trash");
viewHolder.btnDel.setImageResource(R.drawable.trash);
}
else{ //Open conversation
mItemManger.closeAllItems();
Toast.makeText(mContext, " onClick : " + position, Toast.LENGTH_SHORT).show();
}
}
});
//Delete
viewHolder.panelDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (viewHolder.btnDel.getTag().equals("trash")){
viewHolder.btnDel.setTag("del");
viewHolder.btnDel.setImageResource(R.drawable.delete);
YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.trash));
}
else if (viewHolder.btnDel.getTag().equals("del")){
viewHolder.btnDel.setTag("trash");
//viewHolder.btnDel.setImageResource(R.drawable.trash);
ds.deleteChat(viewHolder.textViewPos.getTag().toString());
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataset.size());
mItemManger.closeAllItems();
}
}
});
//Mute/Unmute
viewHolder.panelMute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Mute unmute pos: " + position, Toast.LENGTH_SHORT).show();
if (viewHolder.btnMute.getTag().equals("bell")){
mItemManger.closeAllItems();
viewHolder.imgMute.setVisibility(View.GONE);
viewHolder.btnMute.setTag("mute");
viewHolder.btnMute.setImageResource(R.drawable.mute);
ds.unMute(name.getrNumber());
}
else{
//Save Sender Settings
ds.open();
if(ds.selectCount_tblSender(name.getrNumber()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(name.getrNumber());
ds.create_tblSender(sndr);
}
mItemManger.closeAllItems();
viewHolder.imgMute.setImageResource(R.drawable.mute);
viewHolder.imgMute.setVisibility(View.VISIBLE);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgMute));
viewHolder.btnMute.setTag("bell");
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.mute));
ds.mute(name.getrNumber());
viewHolder.btnMute.setImageResource(R.drawable.bell);
}
//mItemManger.closeAllItems();
//Toast.makeText(view.getContext(), "Deleted " + viewHolder.textViewPos.getText().toString() + "!", Toast.LENGTH_SHORT).show();
}
});
//Lock / Unlock
viewHolder.panelLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (viewHolder.btnLock.getTag().equals("locked")){
//Save Sender Settings
ds.open();
if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(viewHolder.textViewPos.getTag().toString());
ds.create_tblSender(sndr);
}
mItemManger.closeAllItems();
viewHolder.imgLock.setImageResource(R.drawable.lock);
viewHolder.imgLock.setVisibility(View.VISIBLE);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgLock));
viewHolder.btnLock.setTag("unlocked");
viewHolder.btnLock.setImageResource(R.drawable.unlock);
//YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.lock));
ds.Lock(viewHolder.textViewPos.getTag().toString());
}
else{
mItemManger.closeAllItems();
viewHolder.imgLock.setVisibility(View.GONE);
viewHolder.btnLock.setTag("locked");
viewHolder.btnLock.setImageResource(R.drawable.lock);
ds.unLock(viewHolder.textViewPos.getTag().toString());
}
//mItemManger.closeAllItems();
}
});
//Archieve
viewHolder.panelArchieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataset.size());
mItemManger.closeAllItems();
ds.open();
if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) == 0){
//Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
tblSender sndr = new tblSender();
sndr.setNumber(viewHolder.textViewPos.getTag().toString());
ds.create_tblSender(sndr);
}
ds.archieve(viewHolder.textViewPos.getTag().toString());
}
});
viewHolder.textViewPos.setText(name.getSenderName());
viewHolder.textViewPos.setTag(name.getrNumber());
viewHolder.textViewData.setText(name.getMessage().trim());
//Log.i(Log_tag, "Msg: " + name.getMessage().trim());
//viewHolder.txtTime.setText(name.getTime());
//Time Text
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String dateNowStr = formatter.format(date);
Date dateNow = null;
dateNow = formatter.parse(dateNowStr);
String dateSmsStr = name.getTime().substring(0,10);
Date dateSMS = formatter.parse(dateSmsStr);
if (dateSMS.compareTo(dateNow)<0)
{
viewHolder.txtTime.setText(dateSmsStr.substring(0,10)); // + " " + name.getTime().substring(11,name.getTime().length()));
}
else {
viewHolder.txtTime.setText(name.getTime().substring(11,name.getTime().length()));
}
} catch (ParseException e) {
e.printStackTrace();
}
//ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
//int colorRandom = generator.getRandomColor(); // generate random color
//int colorAlpha = generator.getColor(mDataset.get(position).getrName().substring(0,1));//(same key returns the same color)
// declare the builder object once.
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(0)
.toUpperCase()
.endConfig()
.round();
int greenColorValue = Color.parseColor("#FF457BDF");
TextDrawable ic1 = builder.build(mDataset.get(position).getrName().substring(0,1), greenColorValue);
viewHolder.imgName.setImageDrawable(ic1);
if(ds.select_tblSender(name.getrNumber()).getIsMute() == 1){ //Mute sign
Log.i(Log_tag, name.getrNumber() + " was muted at position " + position);
viewHolder.btnMute.setTag("bell");
viewHolder.btnMute.setImageResource(R.drawable.bell);
viewHolder.imgMute.setVisibility(View.VISIBLE);
}
if(ds.select_tblSender(name.getrNumber()).getIsProtected() == 1){ //Mute sign
viewHolder.btnLock.setTag("unlocked");
viewHolder.btnLock.setImageResource(R.drawable.unlock);
viewHolder.imgLock.setVisibility(View.VISIBLE);
}
mItemManger.bindView(viewHolder.itemView, position);
}
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
updateBarHandler = new Handler();
//Fill Inbox
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Layout Managers:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ds = new dataSource(this);
activity = this;
mAdapter = new RecyclerViewAdapter(activity, listInboxAll);
((RecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
recyclerView.setAdapter(mAdapter);
recyclerView.setOnScrollListener(onScrollListener);
//All conversations
GetAllMsgs task = new GetAllMsgs();
task.execute();
}
GetAllMsgs()
private class GetAllMsgs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
ContentResolver contentResolver = getContentResolver();
final String[] projection = new String[]{"*"};
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations/");
Cursor cur = contentResolver.query(uriSMSURI, projection, null, null, "date DESC");
int i = 0;
while (cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
final String body = cur.getString(cur.getColumnIndexOrThrow("body"));
final String date = cur.getString(cur.getColumnIndex("date"));
final Long timestamp = Long.parseLong(date);
//Log.i(Log_tag, "Msg: " + body + " from: " + address);
address = address.trim();
if(address.toString().startsWith("92"))
{
address = address.toString().replace("92", "0");
}
else if(address.toString().startsWith("3")){
address = "0" + address;
}
else if(address.toString().startsWith("+92"))
{
address = address.toString().replace("+92", "0");
}
final String nAdd = address;
time = DateFormat.is24HourFormat(activity);
if(time){
dateFormat = new SimpleDateFormat("dd/MM/yyyy k:mm");
}
else{
dateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm a");
}
String usr = getContactName(activity, nAdd);
tblMsgs msg = new tblMsgs();
msg.setMessage(body);
msg.setSenderName(usr); //Fuzool hai for now
msg.setIsSent(1);
msg.setIsReply(0);
msg.setIsUploaded(0);
msg.setIsLocked(0);
msg.setTime(dateFormat.format(timestamp));
msg.setrName(usr); //Name from phone book
msg.setrNumber(nAdd);
msg.setTimeStamp(timestamp);
//listInboxAll.add(msg);
Texty.position = i;
((RecyclerViewAdapter) mAdapter).addnewItem(msg);
i++;
final int j = i;
if(i % 5 == 0){
updateBarHandler.post(new Runnable() {
#Override
public void run () {
((RecyclerViewAdapter) mAdapter).Update(j);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
}
});
}
//listInboxAll.add(msg);
//ds.create(msg);
}
return "done";
}
catch(Exception ex){
Log.e(Log_tag, ex.getMessage());
return "failed";
}
}
#Override
protected void onPostExecute(String result) {
}
}

#Gabe Sechan solved my problem, I had to change the visibility of icons initially.

Related

RecyclerView setting a image in the wrong place

I have a recycle view, 2 differents adapter and I have a default Image. The problem is that when a user doesn't have an image, sometimes it loads an other user image instead of the default image.
(I also check if user doesn't have imagelink, it reset the default image programatically... so it should work => no problem for the text etc, only the image!)
Here is the xml code for one adapter (pretty much the same for the other):
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rella_rc_item_friend"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="8dp"
card_view:cardBackgroundColor="#color/colorCardView"
card_view:cardCornerRadius="5dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
card_view:cardBackgroundColor="#color/grey_200"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/icon_avata"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:src="#drawable/default_avata"
android:layout_weight="1"
app:civ_border_color="#color/colorPrimary"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_weight="5"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity=""
android:layout_weight="1"
android:orientation="horizontal"
android:paddingTop="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:layout_toLeftOf="#id/txtTime"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity=""
android:layout_weight="1">
<TextView
android:id="#+id/txtMessage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="center_vertical"
android:lines="1"
android:paddingBottom="10dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
class ListContactAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<MessageInfo> ListContacts;
private Context context;
FirebaseAuth mAuth;
String currentuserid;
SimpleDateFormat DateFormat = new SimpleDateFormat("dd MMMM, yyyy");
SimpleDateFormat TimeFormat = new SimpleDateFormat("hh:mm a");
SimpleDateFormat YearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat DayFormat = new SimpleDateFormat("MMMM dd, hh:mm a");
FusionProject Fobj = new FusionProject();
DatabaseReference VuRef;
CommunActivit obj = new CommunActivit();
public ListContactAdapter(Context context,List<MessageInfo> listGroup){
this.context = context;
this.ListContacts = listGroup;
mAuth = FirebaseAuth.getInstance();
currentuserid = mAuth.getUid();
VuRef = FirebaseDatabase.getInstance().getReference().child("Seen");
}
public ListContactAdapter ()
{
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_contact_me, parent, false);
return new ItemForMe(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_friend, parent, false);
return new ItemForMyFriend(view);
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)
{
String username = ListContacts.get(position).getFriendUsername();
String last_message = ListContacts.get(position).getLastMessage();
String time = ListContacts.get(position).getTime() ;
String image = ListContacts.get(position).getFriendPicture();
String FriendID = ListContacts.get(position).getFriendID();
Date Today = new Date(System.currentTimeMillis());
long yourmilliseconds = (Long.parseLong(time));
Date resultdate = new Date(yourmilliseconds);
String test = DateFormat.format(resultdate).toString(); /**DATE**/
String test2 = TimeFormat.format(resultdate).toString(); /**TIME**/
String test3 = YearFormat.format(resultdate);
String test4 = DayFormat.format(resultdate);
if (holder instanceof ItemForMe)
{
((ItemForMe) holder).username_friend.setText(username);
((ItemForMe) holder).last_message.setText("Me : " +last_message);
if (DateFormat.format(Today).equals(test))
{
((ItemForMe) holder).time.setText(test2);
}
else
{
if (YearFormat.format(Today).equals(test3))
{
String cap = test4.substring(0, 1).toUpperCase() + test4.substring(1);
((ItemForMe) holder).time.setText(cap);
}
else {
((ItemForMe) holder).time.setText(test);
}
}
if (!image.equals("")) {
Picasso.get().load(image).into(((ItemForMe) holder).Profil_friend);
}
else
{
((ItemForMe) holder).Profil_friend.setImageResource(R.drawable.default_avata);
}
VuRef.child(ListContacts.get(position).getIDMessage()).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.getValue().toString().equals("Vu"))
{
((ItemForMe) holder).imageView_vu.setImageDrawable(holder.itemView.getContext().getResources().getDrawable(R.drawable.icons8_seen));
}
else
{
((ItemForMe) holder).imageView_vu.setImageDrawable(holder.itemView.getContext().getResources().getDrawable(R.drawable.icons8_not_vu));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else
{
((ItemForMyFriend) holder).username_friend.setText(username);
((ItemForMyFriend) holder).last_message.setText(last_message);
if (DateFormat.format(Today).equals(test))
{
((ItemForMyFriend) holder).time.setText(test2);
}
else
{
if (YearFormat.format(Today).equals(test3))
{
String cap = test4.substring(0, 1).toUpperCase() + test4.substring(1);
((ItemForMyFriend) holder).time.setText(cap);
}
else {
((ItemForMyFriend) holder).time.setText(test);
}
}
if (!image.equals("")) {
Picasso.get().load(image).into(((ItemForMyFriend) holder).Profil_friend);
}
else
{
((ItemForMyFriend) holder).Profil_friend.setImageResource(R.drawable.default_avata);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent groupeIntent = new Intent(v.getContext(), ChatActivity.class);
Fobj.writefile("FriendID",ListContacts.get(position).getFriendID(), context);
Fobj.writefile("MessageID",ListContacts.get(position).getIDMessage(), context);
Fobj.writefile("FriendName",ListContacts.get(position).getFriendUsername(), context);
Fobj.writefile("FriendPicture",ListContacts.get(position).getFriendPicture(), context);
obj.setsIDFRIEND(ListContacts.get(position).getFriendID());
obj.setsIDMESSAGE(ListContacts.get(position).getIDMessage());
obj.setsFRIENDName(ListContacts.get(position).getFriendUsername());
context.startActivity(groupeIntent);
}
});
}
#Override
public int getItemViewType(int position) {
String test = ListContacts.get(position).getSenderID();
if (test.equals(currentuserid))
{
return 1;
}
else
{
return 2;
}
}
#Override
public int getItemCount() {
return ListContacts.size();
}
}
Retrieve data :
List_of_friends.add(0,new MessageInfo(ID, newgroup, profilepicture,MessageID, Date, Message, Time, SenderID));
adapter.notifyDataSetChanged();
So as you can see on this image, the first message wasn't loaded correctly. The user doesn't have an image but get the image user of one other user...
If anyone can help, would be nice !
I have debugged and it seems that it sometimes go more times in the holder than in the listsize.
You can try with Glide like this.
Add this in app.gradle file
implementation "com.github.bumptech.glide:glide:4.8.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.8.0"
Replace Picasso with glide like this
if (!image.trim().isEmpty())
Glide.with(context).load(image).into(((ItemForMyFriend) holder).Profil_friend);
Try loading image like this in your recyclerview
if (!image.trim().isEmpty())
Picasso.with(context).load(image)
.error(R.drawable.default_avata)
.placeholder(R.drawable.default_avata)
.into(((ItemForMyFriend) holder).Profil_friend);

I can't see change on Android Coordinator Layout

I can't see correct data on my Coordinator Layout: I mean, my layout seems correctly set and my java class is correct too.
But when I launch my application I don't see error but my activity have TextView, Image and WebView not initialized with passed data.
I tried to inflate all content with traditional
(TextView) findViewById(R.id.my_id) and with butterknife.ButterKnife library, same result.
Here my activity
public class EventDetailsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener {
private long eventID;
private String eventTitle;
private String eventDesc;
private String eventDate;
private String eventTime;
private String eventImageUrl;
private String eventAddress;
private Double lat;
private Double lng;
private int maxBookings;
#InjectView(R.id.event_title) TextView eventTitleTv;
#InjectView(R.id.event_address) TextView eventAddressTv;
#InjectView(R.id.event_start_date) TextView eventDateTv;
#InjectView(R.id.event_start_time) TextView eventTimeTv;
#InjectView(R.id.event_image) ImageView imageEventView;
#InjectView(R.id.map_address) TextView evetMapAddress;
#InjectView(R.id.event_desc) WebView mWebView;
#InjectView(R.id.toolbar) Toolbar toolbar;
#InjectView(R.id.collapsing_toolbar) CollapsingToolbarLayout collapsingToolbarLayout;
#InjectView(R.id.btnJoin) AppCompatButton btnJoin;
#InjectView(R.id.open_map_button) FloatingActionButton openMapButton;
private MapFragment googleMap;
private GoogleMap map;
private Event event;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActivityTransitions();
setContentView(R.layout.event_details_activity);
ButterKnife.inject(this);
btnJoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialogPlus();
}
});
openMapButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openMapDetail();
}
});
try {
inizializeToolbar();
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
event = extras == null ? null : (Event) extras.getSerializable(Const.EVENT_OBJECT);
} else {
event = (Event) savedInstanceState.getSerializable(Const.EVENT_OBJECT);
}
eventTitle = event.getEventName();
eventDesc = event.getEventContent();
eventDate = event.getEventStartDate();
eventTime = event.getEventStartTime();
eventImageUrl = event.getEventImageUrl();
lat = event.getLocationLatitude();
lng = event.getLocationLongitude();
eventAddress = event.getLocationAddress();
eventID = event.getEventId();
maxBookings = 10;
Log.d("EVENT", "__event title " + eventTitle);
Log.d("EVENT", "__event eventDesc " + eventDesc);
Log.d("EVENT", "__event eventDate " + eventDate);
Log.d("EVENT", "__event eventTime " + eventTime);
Log.d("EVENT", "__event eventImageUrl " + eventImageUrl);
Log.d("EVENT", "__event lat " + lat);
Log.d("EVENT", "__event lng " + lng);
Log.d("EVENT", "__event eventAddress " + eventAddress);
Log.d("EVENT", "__event eventTitle " + eventTitle);
Log.d("EVENT", "__event evv name " + event.getEventName());
initializeMap();
loadImage();
loadTextViews();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initActivityTransitions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Slide transition = new Slide();
transition.excludeTarget(android.R.id.statusBarBackground, true);
getWindow().setEnterTransition(transition);
getWindow().setReturnTransition(transition);
}
}
private void inizializeToolbar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbarLayout.setTitle(eventTitle);
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void loadTextViews(){
eventTitleTv.setText("TITOLO DELL'EVENTO");
eventAddressTv.setText(eventAddress);
evetMapAddress.setText(eventAddress + " -> ");
setEventDesc();
eventDateTv.setText(Utils.getDateFromString(eventDate));
eventTimeTv.setText(Utils.getTimeFromString(eventTime));
}
private void loadImage(){
final ProgressBar progressView = (ProgressBar) findViewById(R.id.loader);
progressView.getIndeterminateDrawable().setColorFilter(getApplicationContext().getResources().getColor(R.color.ColorPrimary), android.graphics.PorterDuff.Mode.MULTIPLY);
Picasso.with(getApplicationContext())
.load(eventImageUrl)
.fit().centerCrop()
.placeholder(R.drawable.event_placeholder_grey_2)
.into(imageEventView, new Callback() {
#Override
public void onSuccess() {
progressView.setVisibility(View.GONE);
}
#Override
public void onError() {
progressView.setVisibility(View.GONE);
}
});
}
private void showDialogPlus() {
Holder holder = new ViewHolder(R.layout.event_prenotation);
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(DialogPlus dialog, View view) {
Spinner mySpinner=(Spinner) dialog.getHolderView().findViewById(R.id.spinner);
String bookValue = mySpinner.getSelectedItem().toString();;
int numberPerson = Integer.parseInt(bookValue);
switch (view.getId()) {
case R.id.btnJoin:
Intent intent = new Intent(getApplicationContext(), ConfirmPrenotationActivity.class);
Bundle bun = new Bundle();
bun.putInt(Const.NUMBER_PRENOT, numberPerson);
bun.putString(Const.EVENT_TITLE, eventTitle);
bun.putLong(Const.EVENT_ID, eventID);
bun.putSerializable(Const.EVENT_OBJECT, event);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(bun);
getApplicationContext().startActivity(intent);
break;
}
//dialog.dismiss();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
//TextView textView = (TextView) view.findViewById(R.id.text_view);
//String clickedAppName = textView.getText().toString();
// dialog.dismiss();
// Toast.makeText(MainActivity.this, clickedAppName + " clicked", Toast.LENGTH_LONG).show();
}
};
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogPlus dialog) {
// Toast.makeText(MainActivity.this, "dismiss listener invoked!", Toast.LENGTH_SHORT).show();
}
};
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogPlus dialog) {
// Toast.makeText(MainActivity.this, "cancel listener invoked!", Toast.LENGTH_SHORT).show();
}
};
final DialogPlus dialog = DialogPlus.newDialog(this)
.setContentHolder(holder)
.setCancelable(true)
.setGravity(Gravity.BOTTOM)
.setOnClickListener(clickListener)
.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
Log.d("DialogPlus", "onItemClick() called with: " + "item = [" +
item + "], position = [" + position + "]");
}
})
.setOnDismissListener(dismissListener)
//.setExpanded(expanded)
//.setContentWidth(800)
.setContentHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
.setOnCancelListener(cancelListener)
.setOverlayBackgroundResource(android.R.color.transparent)
//.setContentBackgroundResource(R.drawable.corner_background)
//.setOutMostMargin(0, 100, 0, 0)
.create();
Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
initializeSpinner(spinner);
dialog.show();
}
public void initializeSpinner(Spinner spin){
ArrayList<String> options = new ArrayList<String>();
for(int i=1; i<= maxBookings; i++){
options.add(""+i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_style, options) {
public View getView(int position, View convertView,ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(18);
return v;
}
public View getDropDownView(int position, View convertView,ViewGroup parent) {
View v = super.getDropDownView(position, convertView,parent);
//((TextView) v).setGravity(Gravity.CENTER);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
}
public void setEventDesc(){
mWebView.setBackgroundColor(Color.TRANSPARENT);
StringBuilder sb = new StringBuilder();
sb.append("<html><body>");
sb.append("<p align=\"justify\">");
sb.append(eventDesc);
sb.append("</p>");
sb.append("</body></html>");
//mWebView.loadData(sb.toString(), "text/html", "utf-8");
mWebView.loadData(sb.toString(), "text/html; charset=utf-8", "utf-8");
}
#TargetApi(Build.VERSION_CODES.M)
public void initializeMap() {
if (googleMap == null) {
googleMap = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
googleMap.getMapAsync(this);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_event_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.share_button:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, getEventInfoToShare());
startActivity(Intent.createChooser(shareIntent, "Share link using"));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
private String getEventInfoToShare(){
StringBuilder infoEvent = new StringBuilder();
infoEvent.append("Ciao, vorrei consigliarti un evento :-)");
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(eventTitle);
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(eventAddress);
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(eventDesc.substring(0, Math.min(eventDesc.length(), 200)));
infoEvent.append("...continua");
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append(System.getProperty("line.separator"));
infoEvent.append("Visita -> www.dayroma.it");
return infoEvent.toString();
}
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setOnMapClickListener(this);
googleMap.getUiSettings().setScrollGesturesEnabled(false);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
map.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(eventTitle));
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
openMapDetail();
return true;
}
});
}
public void openMapDetail(){
Intent i = new Intent(getApplicationContext(), MapsDetailActivity.class);
Bundle bun = new Bundle();
bun.putDouble(Const.EVENT_LAT, lat);
bun.putDouble(Const.EVENT_LONG, lng);
bun.putString(Const.EVENT_TITLE, eventTitle);
bun.putString(Const.EVENT_ADDRESS, eventAddress);
bun.putString(Const.EVENT_IMG_LINK, eventImageUrl);
bun.putSerializable(Const.EVENT_OBJECT, event);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtras(bun);
getApplicationContext().startActivity(i);
}
#Override
public void onMapClick(LatLng latLng) {
openMapDetail();
}
}
And here the layout:
<android.support.design.widget.CoordinatorLayout
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="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="#dimen/image_event_detail_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/ColorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="64dp"
android:fitsSystemWindows="true"
>
<util.SquareImageView
android:id="#+id/event_image"
android:layout_width="match_parent"
android:layout_height="#dimen/image_event_detail_height"
android:maxHeight="#dimen/image_event_detail_height"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<!--<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ProgressBar
android:id="#+id/loader"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:indeterminate="true"
android:layout_centerInParent="true"
/>
</RelativeLayout>-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#drawable/google_cards_background_bottom"
android:gravity="left"
android:orientation="vertical" >
<!-- Titolo Evento -->
<TextView
android:id="#+id/event_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginRight="16dp"
android:layout_marginTop="20dp"
android:text="Eat at Joe"
android:textColor="#color/ColorPrimary"
android:textSize="18sp"
/>
<!-- indirizzo -->
<TextView
android:id="#+id/event_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="9dp"
android:layout_marginBottom="1dp"
android:background="#android:color/transparent"
android:text="data inizio"
android:textColor="#color/material_grey_500"
android:textSize="14sp"
android:drawableLeft="#drawable/ic_position_black_18dp"
android:drawablePadding="2dip"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="left"
android:orientation="horizontal" >
<!-- data inizio evento-->
<TextView
android:id="#+id/event_start_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:background="#android:color/transparent"
android:text="data inizio"
android:textColor="#color/material_grey_500"
android:textSize="14sp"
android:drawableLeft="#drawable/calendar_black_18dp"
android:drawablePadding="2dip"
/>
<!-- ora inizio evento-->
<TextView
android:id="#+id/event_start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="3dp"
android:layout_marginBottom="20dp"
android:background="#android:color/transparent"
android:text="data inizio"
android:textColor="#color/material_grey_500"
android:textSize="14sp"
android:drawableLeft="#drawable/clock_18dp"
android:drawablePadding="2dip"
/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
</LinearLayout>
<!-- DETTAGLI -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#drawable/rounded_shape"
>
<TextView
android:id="#+id/event_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="15dp"
android:layout_marginBottom="3dp"
android:background="#android:color/transparent"
android:text="Dettagli"
android:textColor="#color/black"
android:textStyle="bold"
android:textSize="17sp"
android:gravity="center"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >
<WebView
android:id="#+id/event_desc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hardwareAccelerated="true"
/>
</ScrollView>
</LinearLayout>
<!-- FINE DETTAGLI -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:foreground="#color/dark_trasparent"
>
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="#dimen/map_height"
map:cameraTargetLat="41.890122"
map:cameraTargetLng="12.494248"
map:cameraTilt="30"
map:cameraZoom="15"
tools:ignore="MissingPrefix"
android:clickable="false"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- Maps Address -->
<TextView
android:id="#+id/map_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="22dp"
android:layout_gravity="center_vertical|center_horizontal"
android:background="#android:color/transparent"
android:text="via Cristoforo Colombo 24"
android:textColor="#color/white"
android:textSize="18sp"
android:drawableLeft="#drawable/ic_position_white_18dp"
/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/open_map_button"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#color/ColorPrimary"
android:tint="#color/cpb_grey"
android:src="#drawable/navigation_black_24dp"
style="#style/floatButtonStyle"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/buttons"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentBottom="true"
android:background="#00ffffff"
>
<android.support.v7.widget.AppCompatButton
android:id="#+id/btnJoin"
android:background="#drawable/rounded_button_red"
android:layout_width="fill_parent"
android:textSize="17dp"
android:textStyle="bold"
android:textColor="#color/white"
android:layout_height="#dimen/fixed_bottom_button_height"
android:layout_margin="10dp"
android:layout_centerHorizontal="true"
android:text="#string/join_event"
/>
</LinearLayout>
</RelativeLayout>
It seems a simple problem but I've never had like this before: here a screenshot of my activity, it should be visualize an event details.
Screenshot Activity
This activity is opened when a user click on an event and is fill with event data: data are correctly set because I can see all from log.
I really don't understand why TextViews, ImageView and other element are not filled with data.
Thank you for help
I can't see any closing tag for Coordinator layout in your xml file. If you haven't missed it in question then probably that is the reason for this strange behavior.
Add this at the end of your xml code and things should work better.
</android.support.design.widget.CoordinatorLayout>
Or, if that is just the mistake in question then please update your question. Whatever it is do let me know.

Listview update another raw on update of selected raw

I working on one Shopping Cart application.
In which i show list of products and in that every raw there is "Add to Cart" button,
Whenever user clicks on it then that button goes to disable and another view which holds add and subtract quantity should be display.
But when i clicks on any single product "Add to Cart" button then that view is going to be update, But when i scroll listview then another view gets update automatically (Not all).
Adapter
public class CategoryProductListAdapter extends BaseAdapter {
Context context;
ArrayList<ProductDetailsModel> productDetailsModels;
FragmentManager fragmentManager;
LayoutInflater inflater;
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels) {
this.context = context;
this.productDetailsModels = productDetailsModels;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CategoryProductListAdapter(Context context, ArrayList<ProductDetailsModel> productDetailsModels,FragmentManager fragmentManager) {
this.context = context;
this.productDetailsModels = productDetailsModels;
this.fragmentManager = fragmentManager;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productDetailsModels.size();
}
#Override
public Object getItem(int i) {
return productDetailsModels.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public class Holder {
LinearLayout llProductRawMain, llProductQty;
ImageView imgProduct;
TextView txtProductTitle, txtProductUnit;
Spinner spProductUnits;
Button btnAddProduct, btnSubProduct;
EditText etNoOfProduct;
TextView txtProductPrice;
Button btnAddToCart;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final Holder holder;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.category_product_list_raw, viewGroup, false);
holder.llProductRawMain = (LinearLayout) view.findViewById(R.id.llProductRawMain);
holder.llProductQty = (LinearLayout) view.findViewById(R.id.llProductQty);
holder.imgProduct = (ImageView) view.findViewById(R.id.imgProduct);
holder.txtProductTitle = (TextView) view.findViewById(R.id.txtProductTitle);
holder.txtProductUnit = (TextView) view.findViewById(R.id.txtProductUnit);
holder.spProductUnits = (Spinner) view.findViewById(R.id.spProductUnits);
holder.btnAddProduct = (Button) view.findViewById(R.id.btnAddProduct);
holder.btnSubProduct = (Button) view.findViewById(R.id.btnSubProduct);
holder.etNoOfProduct = (EditText) view.findViewById(R.id.etNoOfProduct);
holder.txtProductPrice = (TextView) view.findViewById(R.id.txtProductPrice);
holder.btnAddToCart = (Button) view.findViewById(R.id.btnAddToCart);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txtProductTitle.setText(Html.fromHtml(productDetailsModels.get(i).getName()));
if (productDetailsModels.get(i).getUnits().size() > 0) {
holder.txtProductUnit.setVisibility(View.GONE);
holder.spProductUnits.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(0).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(0).getPrice());
ArrayList<ProductUnitModel> units = new ArrayList<>();
units.clear();
units.addAll(productDetailsModels.get(i).getUnits());
ProductUnitsListAdapter productUnitsListAdapter = new ProductUnitsListAdapter(context, units);
holder.spProductUnits.setAdapter(productUnitsListAdapter);
holder.spProductUnits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int j, long l) {
holder.etNoOfProduct.setText("1");
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getUnits().get(j).getThumb(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getUnits().get(j).getPrice());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
holder.spProductUnits.setVisibility(View.GONE);
holder.txtProductUnit.setVisibility(View.VISIBLE);
holder.txtProductUnit.setText(productDetailsModels.get(i).getUnit());
ImageLoader.getInstance().displayImage(productDetailsModels.get(i).getImage(), holder.imgProduct, DisplayImageOption.getDisplayImage(), new AnimateFirstDisplayListener());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + productDetailsModels.get(i).getPrice());
}
holder.llProductRawMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (productDetailsModels.get(i).getUnits().size() > 0) {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", true);
intent.putExtra("productUnitPos", holder.spProductUnits.getSelectedItemPosition());
context.startActivity(intent);*/
//FragmentManager fragmentManager = fra;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = true;
int productUnitPos = holder.spProductUnits.getSelectedItemPosition();
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
} else {
/*Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("productDetailModel", productDetailsModels.get(i));
intent.putExtra("productUnits", false);
intent.putExtra("productUnitPos", 0);
context.startActivity(intent);*/
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProductDetailFragment productDetailFragment = new ProductDetailFragment();
Bundle bundles = new Bundle();
ProductDetailsModel productInfoModel = productDetailsModels.get(i);
boolean productUnits = false;
int productUnitPos = 0;
bundles.putSerializable("productDetailModel", productInfoModel);
bundles.putBoolean("productUnits",productUnits);
bundles.putInt("productUnitPos",productUnitPos);
productDetailFragment.setArguments(bundles);
fragmentTransaction.replace(R.id.frameContainer, productDetailFragment);
fragmentTransaction.addToBackStack(productDetailFragment.getClass().getName());
fragmentTransaction.commit();
}
}
});
holder.btnAddProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty++;
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
}
});
holder.btnSubProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_id;
String variation_id;
int qty = Integer.parseInt(holder.etNoOfProduct.getText().toString());
qty--;
if (qty > 0) {
holder.etNoOfProduct.setText(String.valueOf(qty));
double qtyWisePrice = qty * Double.parseDouble(productDetailsModels.get(i).getPrice());
holder.txtProductPrice.setText(context.getString(R.string.rupee) + " " + String.valueOf(qtyWisePrice));
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, qty);
} else {
Toast.makeText(context, "Quntity can not be zero!", Toast.LENGTH_SHORT).show();
}
}
});
holder.btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final boolean isUserLogin = AppMethod.getBooleanPreference((Activity) context, AppConstant.PREF_IS_LOGGED_IN);
if (isUserLogin) {
holder.llProductQty.setVisibility(View.VISIBLE);
holder.btnAddToCart.setVisibility(View.GONE);
String product_id;
String variation_id;
if (productDetailsModels.get(i).getUnits().size() > 0) {
product_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getProduct_id();
variation_id = productDetailsModels.get(i).getUnits().get(holder.spProductUnits.getSelectedItemPosition()).getVariation_id();
} else {
product_id = productDetailsModels.get(i).getProduct_id();
variation_id = productDetailsModels.get(i).getVariation_id();
}
updateCart(product_id, variation_id, 1);
} else {
Toast.makeText(context, "Please Login for Add to Cart !", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void updateCart(String product_id, String variation_id, int qty) {
String customer_id = AppMethod.getStringPreference((Activity) context, AppConstant.PREF_USER_ID);
if (AppMethod.isNetworkConnected((Activity) context)) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("product_id", product_id);
jsonObject.put("variation_id", variation_id);
jsonObject.put("qty", qty);
jsonObject.put("customer_id", customer_id);
WsHttpPostJson wsHttpPostJson = new WsHttpPostJson(context, AppConstant.ADD_CART_WS, jsonObject.toString());
wsHttpPostJson.execute(AppConstant.ADD_CART_WS_URL);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
}
XML of Adapter
<?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:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductRawMain"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="#drawable/product_grid_item_bg"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgProduct"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:padding="#dimen/_5sdp"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="#dimen/view_margin">
<TextView
android:id="#+id/txtProductTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:minLines="2"
android:textSize="#dimen/_11sdp"
android:text="Product Title"
android:textColor="#000000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtProductUnit"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center_vertical"
android:padding="5dp"
android:textSize="#dimen/_11sdp"
android:text="Product Unit" />
<Spinner
android:id="#+id/spProductUnits"
android:layout_width="match_parent"
android:layout_height="#dimen/_25sdp"
android:gravity="center"
android:background="#drawable/icon_dropdown"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/txtProductPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="\u20B9 200"
android:textStyle="bold"
android:textSize="#dimen/_13sdp"
android:textColor="#185401" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llProductQty"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/app_color"
android:orientation="horizontal"
android:visibility="gone">
<Button
android:id="#+id/btnSubProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_minus"
android:gravity="center" />
<EditText
android:id="#+id/etNoOfProduct"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:background="#null"
android:ems="10"
android:enabled="false"
android:textSize="#dimen/_10sdp"
android:gravity="center"
android:inputType="number"
android:text="1"
android:textColor="#color/white" />
<Button
android:id="#+id/btnAddProduct"
android:layout_width="#dimen/_25sdp"
android:layout_height="#dimen/_25sdp"
android:layout_gravity="center_vertical"
android:background="#drawable/icon_plus"
android:gravity="center" />
</LinearLayout>
<Button
android:id="#+id/btnAddToCart"
android:layout_width="match_parent"
android:layout_height="#dimen/_30sdp"
android:background="#color/add_to_cart_btn_bg"
android:text="ADD TO CART"
android:textSize="#dimen/_12sdp"
android:textColor="#color/app_color" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I suffer from this also and realize that i think this links are help you.
Answer-1
Answer-2
Thanks

Can't click on Custom ListView

I was stuck all day. Couldn't find my mistake.
I created a Custom ListView, and I just want to be able to click on it to launch a new intent in HourListView.
public class CustomList extends ArrayAdapter<String> {
private final ArrayList<String> hourList;
private final Activity context;
public CustomList(Activity context,
ArrayList<String> hourList) {
super(context, R.layout.hour_list_adapter, hourList);
this.context = context;
this.hourList = hourList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View rowView = view;
ViewHolder viewHolder = null;
// LayoutInflater inflater = context.getLayoutInflater();
// View rowView= inflater.inflate(R.layout.hour_list_adapter, parent, false);
if(rowView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.hour_list_adapter, parent, false);
viewHolder = new ViewHolder();
viewHolder.type_frequenceTV = (TextView) rowView.findViewById(R.id.type_frequence);
viewHolder.dateTV = (TextView) rowView.findViewById(R.id.date);
viewHolder.dureeTV = (TextView) rowView.findViewById(R.id.duree);
viewHolder.commentaireTV = (TextView) rowView.findViewById(R.id.commentaire);
viewHolder.simuIV = (ImageView) rowView.findViewById(R.id.simulateur);
viewHolder.doubleIV = (ImageView) rowView.findViewById(R.id.doubleFrequence);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)rowView.getTag();
}
viewHolder.type_frequenceTV.setText(HourListActivity.hourObjects.get(position).get("type_frequence").toString());
viewHolder.dureeTV.setText(HourListActivity.hourObjects.get(position).get("duree").toString());
viewHolder.commentaireTV.setText(HourListActivity.hourObjects.get(position).get("comment").toString());
Date dateAndTime = (Date) HourListActivity.hourObjects.get(position).get("date");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yy à HH:mm");
String formatted = format1.format(dateAndTime.getTime());
viewHolder.dateTV.setText("Le " + formatted);
if ((Boolean) HourListActivity.hourObjects.get(position).get("double"))
{
viewHolder.doubleIV.setVisibility(View.VISIBLE);
}
else
{
viewHolder.doubleIV.setVisibility(View.GONE);
}
if ((Boolean) HourListActivity.hourObjects.get(position).get("simulateur"))
{
viewHolder.simuIV.setVisibility(View.VISIBLE);
}
else
{
viewHolder.simuIV.setVisibility(View.GONE);
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rowView;
}
static class ViewHolder
{
TextView type_frequenceTV;
TextView dateTV ;
TextView dureeTV ;
TextView commentaireTV ;
ImageView simuIV ;
ImageView doubleIV ;
}
}
Then this is the HourListActivity where I want to be able to click.
public class HourListActivity extends AppCompatActivity {
//ArrayAdapter<String> arrayAdapter;
CustomList adapter;
ListView hourListView;
static ArrayList<String> hourList;
static ArrayList<String> hourListID;
static ArrayList<ParseObject> hourObjects = new ArrayList<ParseObject>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hour_list);
hourList = new ArrayList<>();
hourListID = new ArrayList<>();
hourListView = (ListView) findViewById(R.id.listView);
adapter = new CustomList(HourListActivity.this,hourList);
//arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hourList);
hourListView.setAdapter(adapter);
hourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("CLIC !!!!!!!!!!!!!!!!!!!!!");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Frequence");
query.getInBackground(hourListID.get(position), new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), ModifyHourActivity.class);
intent.putExtra("objectID", object.getObjectId());
startActivity(intent);
} else {
// something went wrong
}
}
});
}
});
ParseQuery<ParseObject> query = ParseQuery.getQuery("Frequence");
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
System.out.println("username: " + ParseUser.getCurrentUser().getUsername() );
query.orderByDescending("date");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null)
{
if (objects.size() > 0)
{
hourObjects.clear();
for (ParseObject frequence : objects)
{
String result = "";
result += frequence.get("date") + " - "
+ frequence.get("type_frequence") + " - "
+ frequence.get("duree") + " - "
+ frequence.get("comment") + " - "
+ frequence.get("double") + " - "
+ frequence.get("simulateur") + " - ";
System.out.println("Résultat : " + result);
hourList.add(result.toString());
hourListID.add(frequence.getObjectId());
ParseObject newHour = new ParseObject("Temp");
newHour.put("username", frequence.get("username"));
// newHour.put("id", frequence.get("objectId"));
newHour.put("type_frequence", frequence.get("type_frequence"));
newHour.put("date", frequence.get("date"));
newHour.put("duree", frequence.get("duree"));
newHour.put("comment", frequence.get("comment"));
newHour.put("double", frequence.get("double"));
newHour.put("simulateur", frequence.get("simulateur"));
hourObjects.add(newHour);
}
Toast.makeText(HourListActivity.this, "Liste des heures récupérée !",
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
else
{
}
}
});
A lastly my xml file for the Custom View:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:layout_margin="5dp"
>
<TextView
android:id="#+id/type_frequence"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:gravity="center"
android:text="DEP S"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/buttonTextColor"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:textSize="15dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="12 avril 2016 - 08:00"
android:layout_marginLeft="5dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:id="#+id/duree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="1.00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/buttonTextColor"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp"
android:paddingRight="10dp"
/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="horizontal">
<TextView
android:id="#+id/commentaire"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:text="Commentaire"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true">
<ImageView
android:id="#+id/doubleFrequence"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_column="1"
android:src="#drawable/double_96" />
<ImageView
android:id="#+id/simulateur"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_column="1"
android:src="#drawable/simu_96"
android:layout_toStartOf="#+id/doubleFrequence" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Thanks in advance for any help ! :)
What happens when you delete this part in your adapter ?
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
I guess what happens is that the view are created after you have defined the ItemClickListener in your activity, resulting in the ClickListener being overriden at run time by the one in your adapter.
As far as I am concerned if you are facing an error with setOnClickListener you can try this
Go to Tools--> sync with Gradle.
It helped me when I was stucked with the intent problem!

Android ListView: Custom ListItem not displayed correctly

based on an example i tried to create a ListView that displays custom ListItems. I define the ListItem in XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/icon" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:singleLine="true"
android:text="Example application"
android:textSize="16sp" />
</RelativeLayout>
I created a class to hold the data shown in a ListItem:
public class UserRecord {
public String username;
public String email;
public UserRecord(String username, String email) {
this.username = username;
this.email = email;
}
}
I also have a custom ArrayAdapter:
public class UserItemAdapter extends ArrayAdapter<UserRecord> {
private ArrayList<UserRecord> users;
public LayoutInflater vi;
private Context context;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<UserRecord> users) {
super(context, textViewResourceId, users);
this.users = users;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
UserRecord user = users.get(position);
if (user != null) {
TextView username = (TextView) v.findViewById(R.id.firstLine);
TextView email = (TextView) v.findViewById(R.id.secondLine);
Log.v(TAG, "user " + user.username);
Log.v(TAG, "mail " + user.email);
if (username != null) {
Log.v(TAG, "username NOT null");
username.setText("user " + user.username);
}
if (email != null) {
Log.v(TAG, "email NOT null");
email.setText("Email: " + user.email);
}
}
return v;
}
}
Initialisation:
ArrayList<UserRecord> appointment;
UserItemAdapter aa;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
appointment = new ArrayList<UserRecord>();
aa = new UserItemAdapter(this, android.R.layout.simple_list_item_1, appointment);
lv.setAdapter(aa);
}
And finally, when i push a button:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
aa.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
Problem is that "email" is displayed, but "username" not, though it is handled the same way, i see no difference. Also, the if() where it should be set is taken.
Has anybody got a hint on what is wrong?
Best regards
Torsten
Change this
aa = new UserItemAdapter(this, android.R.layout.simple_list_item_1, appointment);
To this;
aa = new UserItemAdapter(this, R.layout.listitem, appointment);
And try this:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
appointment.add(ur);
aa.notifyDataSetChanged();
} else {
Log.v(TAG, "unknown");
}
}
I could be mistaken, but I am almost sure you should be doing this:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
users.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
Instead of:
public void onClick(View v) {
if (v == b1) {
UserRecord ur = new UserRecord("User " + i, "mail#mail.net");
Log.v(TAG, "button 1 " + i);
aa.add(ur);
} else {
Log.v(TAG, "unknown");
}
}
I have never added an item to my ADAPTER class, but always to the LIST of objects. In this case "users" rather than "aa".
The problem is in your listitem.xml file. Try to change to this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/icon" />
<TextView
android:id="#+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:text="Description"
android:layout_below="#id/firstLine"
android:textSize="12sp" />
</RelativeLayout>

Categories

Resources