Hello i try to use my own adapter on Gridview.
My problem is that the position in getView is not increasing.
This is my code:
public class WorkourLogBuilder {
String[] values = new String[11];
Context mContext;
Map<Integer, String[]> valuesArray;
int rowsCount = 0;
int mode;
int adappterRowsCount = 0;
static final int AEROBIC = 1;
static final int ANAEROBIC = 0;
public WorkourLogBuilder(Context context, int modeChoosed)
{
mContext = context;
mode = modeChoosed;
valuesArray = new HashMap<Integer, String[]>();
}
public void commintRow()
{
valuesArray.put(rowsCount, values);
rowsCount++;
Log.i("rowsCount", rowsCount+"");
values = new String[11];
}
public void setWorkoutWeight(String value)
{
values[0] = value;
}
public void setSets(String value)
{
values[1] = value;
}
public void setReps(String value)
{
values[2] = value;
}
public void setWorkTime(String value)
{
values[3] = value;
}
public void setWDayTime(String value)
{
values[4] = value;
}
public void setDistance(String value)
{
values[5] = value;
}
public void setSpeed(String value)
{
values[6] = value;
}
public void setRestTime(String value)
{
values[7] = value;
}
public void setCaloires(String value)
{
values[8] = value;
}
public void setHeartBeat(String value)
{
values[9] = value;
}
public void setComment(String value)
{
values[10] = value;
}
public View build()
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
View v = inflater.inflate(R.layout.workout_log_row, null, false);
GridView grid = (GridView) v.findViewById(R.id.table);
Log.i("count", valuesArray.size()+"");
grid.setAdapter(new ImageAdapter());
return v;
}
public class ImageAdapter extends BaseAdapter {
public int getCount() {
return (valuesArray.size()+6);
}
public Object getItem(int position) {
return valuesArray.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("position", position+"");
if(position < 6)
{
ImageView image = new ImageView(mContext);
if(position < 3)
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.small_green_apple));
else
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.anonymous));
image.setScaleType(ImageView.ScaleType.FIT_XY);
return image;
}
TextView textValue = new TextView(mContext);
textValue.setTextColor(Color.BLACK);
GridView.LayoutParams lp = new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.MATCH_PARENT);
textValue.setLayoutParams(lp);
String[] currecntRow = valuesArray.get(adappterRowsCount);
switch(position % 6)
{
case 0:
{
if(adappterRowsCount != 6)
adappterRowsCount++;
if(mode == AEROBIC)
textValue.setText(currecntRow[5]);
else
textValue.setText(currecntRow[0]);
break;
}
case 1:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[3]);
else
textValue.setText(currecntRow[2]);
break;
}
case 2:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[6]);
else
textValue.setText(currecntRow[1]);
break;
}
case 3:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[1]);
else
textValue.setText(currecntRow[7]);
break;
}
case 4:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[7]);
else
textValue.setText(currecntRow[3]);
break;
}
case 5:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[10]);
else
textValue.setText(currecntRow[10]);
break;
}
}
return textValue;
}
}`enter code h
The XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:numColumns="6" >
</GridView>
</RelativeLayout>
This is where i use WorkourLogBuilder class
public void setTheLogViewTest(String date)
{
String[][] values = data.dayLog(date);
ArrayList<ExpandListGroup> listAll = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> listChilds = new ArrayList<ExpandListChild>();
ExpandListGroup group = new ExpandListGroup();
ExpandListChild child = new ExpandListChild();
int length = values[0].length;
WorkourLogBuilder builder = null;
for(int i = 0; i < length; i++)
{
String exrcise = values[3][i];
String restTime;
String setTime;
String weight;
String reps;
String comment;
String sets;
String speed;
String distance;
if (values[9][i] == null || values[9][i].equals(""))
speed = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
speed = values[9][i] + " " + mResources.getString(R.string.km_hour);
else
speed = values[9][i] + " " + mResources.getString(R.string.miles_hour);
}
if (values[10][i] == null || values[10][i].equals(""))
restTime = mResources.getString(R.string.Undefined);
else
restTime = getTimesPharsed(values[10][i]);
if (values[6][i] == null || values[6][i].equals(""))
setTime = mResources.getString(R.string.Undefined);
else
setTime = getTimesPharsed(values[6][i]);
if (values[4][i] == null || values[4][i].equals(""))
weight = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
weight = values[4][i] + " " + mResources.getString(R.string.kg);
else
weight = values[4][i] + " " + mResources.getString(R.string.lbs);
}
if (values[5][i] == null || values[5][i].equals(""))
reps = mResources.getString(R.string.Undefined);
else
reps = values[5][i];
if (values[11][i] == null || values[11][i].equals(""))
comment = mResources.getString(R.string.Undefined);
else
comment = values[11][i];
if (values[12][i] == null || values[12][i].equals(""))
sets = mResources.getString(R.string.Undefined);
else
sets = values[12][i] + checkForFailedSets(values[1][i]);
if (values[8][i] == null || values[8][i].equals(""))
distance = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
distance = values[8][i] + " " + mResources.getString(R.string.km);
else
distance = values[8][i] + " " + mResources.getString(R.string.miles);
}
if(i == 0)
{
group = new ExpandListGroup();
group.setName(exrcise, this);
Log.i("test", "1");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i > 0 && exrcise.equals(values[3][i - 1]) == false && i == length - 1 == false)
{
Log.i("test", "2");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == false)
{
Log.i("test", "3");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == true)
{
Log.i("test", "4");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else
{
Log.i("test", "5");
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
}
ExpAdapter = new ExpandListAdapter(DatePage.this, listAll);
ExpandList.setAdapter(ExpAdapter);
}
When i look at the logcat i that the position log is always 0.
Why position is not increasing?
You are not returning from getItem() correctly:
public Object getItem(int position) {
return position;
}
It should be:
public Object getItem(int position) {
return valuesArray.get(position);
}
you have wrong in getItem()
public Object getItem(int position) {
return valuesArray.get(position);
}
it should return an Object not an the position, so basically it is always returning 0
Related
In one of my applications I am trying to use recyclerview to display content. My content would be like chat history(it may be a single line text or multiple lines text).To implement this I have used recyclerview with Textview height as wrap_content to adjust the height based on the content. For the first time it is loading fine. But when I do scroll up and down I am getting some extra white space for some of the items. (I strongly suspect this extra space is for earlier item height).
Ex: I have a recyclerview list having 1,2,3,4,5.. lines text in each row. When I do scroll up down continuously I am getting row/item height is changing like 1 line text item got 5 lines text space and 5 lines text item got 1 line text.
Please find my adapter code below.
public class ConversationMessagesAdapterNew extends RecyclerView.Adapter {
private ConversationDetailActivityNew context;
private LayoutInflater layoutInflater;
private Utils utils;
private List<Message> messages = null;
private SessionManagement mSessionManage;
private int loginId = 0, attachmentsCount = 0, gifCount = 0;
private String mProfilePicId, mFname, mLname, fname = "", lname = "";
private ComposeDetails composeDetails;
private JSONArray attachmentArrayObj = new JSONArray();
public ConversationMessagesAdapterNew(ConversationDetailActivityNew context) {
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.utils = new Utils(context);
setHasStableIds(true);
this.mSessionManage = new SessionManagement(context, Utils.SHARED_PREF);
loginId = Integer.parseInt(mSessionManage.getString("userId"));
this.mProfilePicId = mSessionManage.getString("profilePicId");
this.mFname = mSessionManage.getString("firstName");
this.mLname = mSessionManage.getString("lastName");
}
public void setMessages(List<Message> messagesList) {
this.messages = messagesList;
/*if (messagesList == null) {
if (this.messages != null) {
this.messages.clear();
this.messages = null;
}
} else {
if (this.messages != null && this.messages.size() > 0)
this.messages.addAll(messagesList);
else
this.messages = messagesList;
}*/
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.conversation_messages_list_row_item_longpress, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final ViewHolder messagesListViewHolder = (ViewHolder) holder;
Message message = messages.get(position);
messagesListViewHolder.mMainLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
(context).loadMoreButtonlayout(message);
return true;
}
});
try {
String picId = "";
composeDetails = (context).getProfilePicId(String.valueOf(message.getSenderId()));
if (composeDetails != null) {
fname = composeDetails.getFristName();
lname = composeDetails.getLastName();
}
if (message.getSenderId() == loginId) {
picId = mProfilePicId;
} else {
//picId = ((ConversationDetailActivity)context).getProfilePicId(String.valueOf(message.getSenderId()));
if (composeDetails != null) {
picId = composeDetails.getProfilePicture();
fname = composeDetails.getFristName();
lname = composeDetails.getLastName();
}
mFname = fname;
mLname = lname;
}
if (!picId.equals("null")) {
messagesListViewHolder.iv_user_profile.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_lettersText.setVisibility(View.GONE);
messagesListViewHolder.mCardView.setCardBackgroundColor(Color.parseColor("#EFEFEF"));
String url = String.format("%s%s", Constants.mDisplayProfilePicUrl, picId);
Picasso.with(context).load(url).placeholder(R.drawable.user_default).into(messagesListViewHolder.iv_user_profile);
} else {
messagesListViewHolder.iv_user_profile.setVisibility(View.GONE);
messagesListViewHolder.tv_lettersText.setVisibility(View.VISIBLE);
messagesListViewHolder.mCardView.setCardBackgroundColor(Color.parseColor("#77B633"));
String name = getName(mFname, mLname);
messagesListViewHolder.tv_lettersText.setText(name);
}
if (message.getMessageType().equals("OFFNETEMAIL")) {
messagesListViewHolder.tv_sender_name.setTextColor(Color.parseColor("#2C303E"));
} else {
messagesListViewHolder.tv_sender_name.setTextColor(Color.parseColor("#276eb6"));
}
String sendName = message.getSenderName();
if (message.getMetric().getFlags().getCount() > 0 ||
message.getMetric().getLikes().getCount() > 0) {
if (sendName.length() > 15) {
sendName = sendName.substring(0, 15) + "..";
}
} else {
if (sendName.length() > 18) {
sendName = sendName.substring(0, 18) + "..";
}
}
messagesListViewHolder.tv_sender_name.setText(sendName);
messagesListViewHolder.tv_created_time.setText(utils.getTimeStampByString(message.getCreatedOn()));
String content = message.getContent();
// Attachment parsing
String prtnAttachment = "\\<attachment:(.*?)\\>";
Pattern ptr = Pattern.compile(prtnAttachment);
Matcher m = ptr.matcher(content);
while (m.find()) {
String[] fileStr = m.group(0).toString().split(":");
if (fileStr.length > 0) {
JSONObject file = new JSONObject();
file.put("fileId", fileStr[1].toString());
file.put("fileName", fileStr[2].toString());
file.put("fileType", fileStr[3].toString());
file.put("randomFileName", fileStr[4].toString());
file.put("fileSize", fileStr[5].toString());
attachmentArrayObj.put(file);
attachmentsCount++;
} else {
//attachmentsFlag = false;
// imageFlag = false;
attachmentsCount = 0;
}
}
// Emoji / Mentions parsing
String ptrsEmoji = "\\<:(.*?)\\>";
Pattern ptrEmoji = Pattern.compile(ptrsEmoji);
Matcher em = ptrEmoji.matcher(content);
while (em.find()) {
String[] emojiStr = em.group(0).split(":");
if (emojiStr.length > 0) {
if (emojiStr[1].contains("mention-everyone")) {
String parsedStr = "<font color='#1F6EB7'>" + "#everyone" + "</font>";
content = content.replaceAll(em.group(0), parsedStr);
} else if (emojiStr[1].contains("mention-")) {
String[] ms = emojiStr[1].split("-");
String parsedStr = "<font color='#1F6EB7'>" + "#" + ms[1] + "</font>";
content = content.replaceAll(em.group(0), parsedStr);
} else {
String parsedStr = "&#x" + emojiStr[1];
content = content.replaceAll(em.group(0), parsedStr);
}
}
}
if (content.length() > 0) {
messagesListViewHolder.tv_message.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_message.setText(Html.fromHtml(content));
} else {
messagesListViewHolder.tv_message.setVisibility(View.GONE);
}
if (attachmentsCount > 0) {
messagesListViewHolder.tv_message.setVisibility(View.GONE);
messagesListViewHolder.mAttachLayout.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_attachments.setText(String.valueOf(attachmentsCount + gifCount) + " Attachments.");
attachmentsCount = 0;
} else {
attachmentsCount = 0;
messagesListViewHolder.tv_message.setVisibility(View.VISIBLE);
messagesListViewHolder.mAttachLayout.setVisibility(View.GONE);
}
// Likes and Flag sectin
if (message.getMetric().getLikes().getCount() > 0) {
messagesListViewHolder.iv_likes_icon.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_likes_count.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_likes_count.setText(String.valueOf(message.getMetric().getLikes().getCount()));
} else {
messagesListViewHolder.iv_likes_icon.setVisibility(View.GONE);
messagesListViewHolder.tv_likes_count.setVisibility(View.GONE);
}
if (message.getMetric().getFlags().getCount() > 0) {
messagesListViewHolder.iv_flag_icon.setVisibility(View.VISIBLE);
} else {
messagesListViewHolder.iv_flag_icon.setVisibility(View.GONE);
}
messagesListViewHolder.mAttachLayout.setOnClickListener(v -> {
Intent attachmentIntent = new Intent(context, AttachmentsView.class);
attachmentIntent.putExtra("contentAttachment", message.getContent());
context.startActivity(attachmentIntent);
});
messagesListViewHolder.mAttachLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
(context).loadMoreButtonlayout(message);
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
if (messages != null && messages.size() > 0)
return messages.size();
else
return 0;
}
#Override
public long getItemId(int position) {
Message message = messages.get(position);
return message.getId();
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout mMainLayout;
ImageView iv_user_profile, iv_likes_icon, iv_flag_icon;
TextView tv_sender_name, tv_created_time, tv_message, tv_lettersText, tv_attachments, tv_likes_count;
CardView mCardView;
FrameLayout mMoreLayout;
RelativeLayout mAttachLayout;
View mDummyLongPressLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mMainLayout = itemView.findViewById(R.id.longpress_layout_detailpage);
mDummyLongPressLayout = itemView.findViewById(R.id.DummyLongPressLayout);
mMoreLayout = itemView.findViewById(R.id.delete_layout);
iv_user_profile = itemView.findViewById(R.id.iv_user_profile);
tv_sender_name = itemView.findViewById(R.id.tv_sender_name);
tv_sender_name.setTypeface(utils.mRobotoBold);
tv_created_time = itemView.findViewById(R.id.tv_created_time);
tv_created_time.setTypeface(utils.mRobotoRegular);
tv_message = itemView.findViewById(R.id.tv_message);
tv_message.setTypeface(utils.mRobotoRegular);
tv_lettersText = itemView.findViewById(R.id.tv_lettersText);
tv_lettersText.setTypeface(utils.mRobotoRegular);
mCardView = itemView.findViewById(R.id.card_view);
mAttachLayout = itemView.findViewById(R.id.AttachmentsLayout);
mAttachLayout.setVisibility(View.GONE);
tv_attachments = itemView.findViewById(R.id.tv_attachments);
tv_likes_count = itemView.findViewById(R.id.tv_likes_count);
iv_likes_icon = itemView.findViewById(R.id.iv_like_icon);
iv_flag_icon = itemView.findViewById(R.id.iv_flag_icon);
}
}
private String getName(String fname, String lname) {
if (fname.length() > 0) {
if (!fname.equals("null")) {
fname = fname.substring(0, 1).toUpperCase();
} else {
fname = "";
}
} else {
fname = "";
}
if (lname.length() > 0) {
if (!lname.equals("null")) {
lname = lname.substring(0, 1).toUpperCase();
} else {
lname = "";
}
} else {
lname = "";
}
return fname + lname;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
Above is the code of getview, I was in the use of staggeredgridview Etsy ,when I scroll the screen,this problem is occurs, a time when the position is out of confusion, as if the location of the position did not be remembered.
The following is a screenshot of position getview:
This issue comes only if you are not controlling getCount() and getItem() methods. Make sure that you are returning your list size as in getCount() like this :
#Override
public int getCount() {
return list.size();
}
and getItem() as :
#Override
public SetterGetterClassName getItem(int position) {
return list.get(position);
}
This is my complete code :
enter code here
public class UserDetailsAdapter2 extends BaseAdapter {
//private HashMap<Integer, View> viewMap;
private DisplayImageOptions mDisplayOption = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
.showStubImage(R.drawable.empty_activity_icon).showImageForEmptyUri(R.drawable.empty)
.showImageOnFail(R.drawable.empty_activity_icon).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(400)).considerExifParams(true)
.build();
private Context mContext;
private List<CellQzones> mUserInfors;
private UserInfor mUser;
private String TAG = "UserDetailsAdapter2";
private final Random mRandom;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
//private ImageLoader2 mImageLoader2;
public UserDetailsAdapter2(Context context, List<CellQzones> mDatas, UserInfor user) {
mContext = context;
mUserInfors = mDatas;
mUser = user;
mRandom = new Random();
//viewMap=new HashMap<Integer, View>();
}
#Override
public int getCount() {
return mUserInfors.size();
}
#Override
public Object getItem(int position) {
return mUserInfors.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
// if(!viewMap.containsKey(position) || viewMap.get(position) == null){
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
//convertView = viewMap.get(position);
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
//mImageLoader2.loadImage(imgeurl,helper.iv_show, true);
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
public class ViewHolder {
EmojiconTextView tv_content;
TextView tv_time;
TextView tv_zannum;
TextView tv_plnum;
DynamicHeightImageView iv_show;
ImageView img_zan;
RelativeLayout rel_photo;
}
private double getPositionRatio(final int position) {
double ratio = sPositionHeightRatios.get(position, 0.0);
// if not yet done generate and stash the columns height
// in our real world scenario this will be determined by
// some match based on the known height and width of the image
// and maybe a helpful way to get the column height!
if (ratio == 0) {
ratio = getRandomHeightRatio();
sPositionHeightRatios.append(position, ratio);
Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
}
return ratio;
}
private double getRandomHeightRatio() {
return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5
// the width
}
/** 得到checkbox的赞的状态 **/
private boolean getCheckstate(List<Map<String, String>> diggerlist) {
for (int i = 0; i < diggerlist.size(); i++) {
Map<String, String> mp = diggerlist.get(i);
String uid = mUser.getUid();
String mUid = mp.get("uid");
// 如果有就设置true。
if (uid.equals(mUid)) {
return true;
}
}
return false;
}
}
I am having this error while scrolling list view with items.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available
Can anyone help please?
EDIT
public class ItemsListAdapter2 extends BaseAdapter {
private final float NUMBER_OF_ITEMS_PER_GRID = 2;
private final int AD_POSITION = 4;
private Context context;
private ArrayList<ArrayList<ItemResponse>> allData = new ArrayList<ArrayList<ItemResponse>>();
public class ViewHolder {
// for Item1
LinearLayout itemLayout1;
ImageView itemImage1;
TextView itemDate1;
ImageView itemTagImage1;
TextView normalItemPrice1;
TextView pinnedItemPrice1;
TextView itemTitle1;
TextView itemDescription1;
// for Item2
LinearLayout itemLayout2;
ImageView itemImage2;
TextView itemDate2;
ImageView itemTagImage2;
TextView normalItemPrice2;
TextView pinnedItemPrice2;
TextView itemTitle2;
TextView itemDescription2;
RelativeLayout adLayout;
ImageView adUnit;
}
public ItemsListAdapter2(Context context, ArrayList<ItemResponse> data) {
this.context = context;
setData(data);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_listings2, null);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemLayout1 = (LinearLayout) convertView.findViewById(R.id.item1_layout);
holder.itemImage1 = (ImageView) convertView.findViewById(R.id.item_image1);
holder.itemDate1 = (TextView) convertView.findViewById(R.id.item_date1);
holder.itemTagImage1 = (ImageView) convertView.findViewById(R.id.tag_image1);
holder.normalItemPrice1 = (TextView) convertView.findViewById(R.id.normal_item_price1);
holder.pinnedItemPrice1 = (TextView) convertView.findViewById(R.id.pinned_item_price1);
holder.itemTitle1 = (TextView) convertView.findViewById(R.id.item_title1);
holder.itemDescription1 = (TextView) convertView.findViewById(R.id.item_description1);
holder.itemLayout2 = (LinearLayout) convertView.findViewById(R.id.item2_layout);
holder.itemImage2 = (ImageView) convertView.findViewById(R.id.item_image2);
holder.itemDate2 = (TextView) convertView.findViewById(R.id.item_date2);
holder.itemTagImage2 = (ImageView) convertView.findViewById(R.id.tag_image2);
holder.normalItemPrice2 = (TextView) convertView.findViewById(R.id.normal_item_price2);
holder.pinnedItemPrice2 = (TextView) convertView.findViewById(R.id.pinned_item_price2);
holder.itemTitle2 = (TextView) convertView.findViewById(R.id.item_title2);
holder.itemDescription2 = (TextView) convertView.findViewById(R.id.item_description2);
holder.adLayout = (RelativeLayout) convertView.findViewById(R.id.banner_ad);
holder.adUnit = (ImageView) convertView.findViewById(R.id.ad_view_image);
if (allData.get(position) != null && allData.get(position).size() > 0) {
setItem1Data(holder, position);
setItem2Data(holder, position);
}
if ((position + 1) % AD_POSITION == 0) {
// show ad
holder.adLayout .setVisibility(View.VISIBLE);
//initializeBannerAd(convertView, holder.adUnit);
} else {
holder.adLayout .setVisibility(View.GONE);
}
return convertView;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
try {
return allData.get(position);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
#Override
public long getItemId(int position) {
try {
return allData.indexOf(getItem(position));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return -1;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
private void initData (ArrayList<ItemResponse> data) {
int numberOfItems = (int) Math.ceil(data.size() / NUMBER_OF_ITEMS_PER_GRID);
ArrayList<ArrayList<ItemResponse>> tempData = new ArrayList<ArrayList<ItemResponse>>(numberOfItems);
for (int i = 0; i < numberOfItems; i++) {
ArrayList<ItemResponse> items = new ArrayList<ItemResponse>();
for (int j = 0; j < NUMBER_OF_ITEMS_PER_GRID; j++) {
try {
items.add(data.get(j));
} catch (Exception e) {
e.printStackTrace();
}
}
tempData.add(i, items);
// clear
data.removeAll(items);
}
for (int n = 0; n < tempData.size(); n++) {
allData.add(tempData.get(n));
}
}
public void setData (ArrayList<ItemResponse> data) {
allData.clear();
ArrayList<ItemResponse> mData = new ArrayList<ItemResponse>();
for (int i = 0; i < data.size(); i++) {
mData.add(data.get(i));
}
initData(mData);
}
public void setItem1Data (ViewHolder holder , int position) {
try {
holder.itemLayout1.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(0);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage1, postAdPlaceholder);
}
holder.itemDate1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTitle1.setVisibility(View.GONE);
holder.itemDescription1.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
holder.itemTitle1.setVisibility(View.VISIBLE);
holder.itemDescription1.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage1, current.getImages().get(0));
}
holder.itemDate1.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage1.setImageResource(R.drawable.tag_pinned);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.VISIBLE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
}
holder.itemTitle1.setText(current.getTitle());
holder.itemDescription1.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage1.setOnClickListener(clickListener);
holder.itemTitle1.setOnClickListener(clickListener);
holder.itemDescription1.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout1.setVisibility(View.INVISIBLE);
}
}
public void setItem2Data (ViewHolder holder , int position) {
try {
holder.itemLayout2.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(1);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage2, postAdPlaceholder);
} else {
PhoneUtils.setImage(context, holder.itemImage2, null, R.drawable.placeholder_squre);
}
holder.itemDate2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTitle2.setVisibility(View.GONE);
holder.itemDescription2.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
holder.itemTitle2.setVisibility(View.VISIBLE);
holder.itemDescription2.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage2, current.getImages().get(0));
}
holder.itemDate2.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage2.setImageResource(R.drawable.tag_pinned);
} else {
holder.itemTagImage2.setImageResource(R.drawable.tag);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.VISIBLE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
}
holder.itemTitle2.setText(current.getTitle());
holder.itemDescription2.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage2.setOnClickListener(clickListener);
holder.itemTitle2.setOnClickListener(clickListener);
holder.itemDescription2.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout2.setVisibility(View.INVISIBLE);
}
}
}
and also find the loading method, I am implementing on scroll load more items
private void loadData (boolean inBackground) {
int categoryId = -1;
if (mParentCategory != null)
categoryId = mParentCategory.getId();
mIsInBackground = inBackground;
if (mIsInBackground == false)
showProgressDialog();
else
disableBackButton();
// TODO districts.
ForSaleServerManager.getInstance().getListings(this, mSearchQuery,
categoryId, -1, mSellingTypeId, mPageNumber, this);
}
and in the following is setting data in the adapter
if (mPageNumber == 1) {
// add all pinning items.
if (items.getPinnedItems() != null && items.getPinnedItems().size() > 0)
allItems.addAll(items.getPinnedItems());
if (mMode == MODE_SEARCH) {
// handle post ad listing item.
if ((allItems.size() % 2) != 0)
allItems.add(new ItemResponse(ForSaleConstants.POST_AD_LISTING_ID));
}
}
// add all normal items.
if (items.getNormalItems() != null && items.getNormalItems().size() > 0)
for (int i = 0; i < items.getNormalItems().size(); i++) {
if (allItems.contains(items.getNormalItems().get(i)) == false)
allItems.add(items.getNormalItems().get(i));
}
if (allItems != null && allItems.size() > 0) {
if (mAdapter == null) {
mAdapter = new ItemsListAdapter2(ItemsActivity.this, allItems);
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
} else {
mAdapter.setData(allItems);
mAdapter.notifyDataSetChanged();
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
}
} else {
mListView.setVisibility(View.GONE);
mNoDataFound.setVisibility(View.VISIBLE);
showNoData(R.drawable.icon_listing_unselected, R.string.error_categories_found);
}
I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}
I have 10 spinner and 10 edit text (user are able to let several spinner and edit text blank), and I also have 2 button to sum value from the selected spinner object and edit text. It's successful to sum the value, but when I use my reset button to get back to the initial state when the app is first launched, I got the problem. The result is wrong, I got the value from the first operation even though I have set it back to the default. This is my code for the reset button
hapus.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
qty1.setText(null);
qty2.setText(null);
qty3.setText(null);
qty4.setText(null);
qty5.setText(null);
qty6.setText(null);
qty7.setText(null);
qty8.setText(null);
qty9.setText(null);
qty10.setText(null);
spin1.setSelection(0);
spin2.setSelection(0);
spin3.setSelection(0);
spin4.setSelection(0);
spin5.setSelection(0);
spin6.setSelection(0);
spin7.setSelection(0);
spin8.setSelection(0);
spin9.setSelection(0);
spin10.setSelection(0);
sum.setText(null);
hasil = 0;
}
});
And this is a part of my code for the spinner and sum operation
spin8.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value8 = item.toString();
if (item.equals("null"))
{
hrg8 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg8 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg8 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg8 = 4000;
}
else if (item.equals("Emping"))
{
hrg8 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg8 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg8 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg8 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg8 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg8 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg8 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg8 = 7000;
}
else if (item.equals("Aqua"))
{
hrg8 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
spin9.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value9 = item.toString();
if (item.equals("null"))
{
hrg9 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg9 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg9 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg9 = 4000;
}
else if (item.equals("Emping"))
{
hrg9 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg9 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg9 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg9 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg9 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg9 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg9 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg9 = 7000;
}
else if (item.equals("Aqua"))
{
hrg9 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
spin10.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value10 = item.toString();
if (item.equals("null"))
{
hrg10 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg10 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg10 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg10 = 4000;
}
else if (item.equals("Emping"))
{
hrg10 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg10 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg10 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg10 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg10 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg10 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg10 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg10 = 7000;
}
else if (item.equals("Aqua"))
{
hrg10 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
hitung.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
if (qty1.getText().toString() != null && !(qty1.getText().toString().equals("")))
{
jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
jml1 = 0;
}
if (qty2.getText().toString() != null && !(qty2.getText().toString().equals("")))
{
jml2 = Integer.parseInt(qty2.getText().toString());
item2 = hrg2 * jml2;
}
else
{
jml2 = 0;
}
if (qty3.getText().toString() != null && !(qty3.getText().toString().equals("")))
{
jml3 = Integer.parseInt(qty3.getText().toString());
item3 = hrg3 * jml3;
}
else
{
jml3 = 0;
}
if (qty4.getText().toString() != null && !(qty4.getText().toString().equals("")))
{
jml4 = Integer.parseInt(qty4.getText().toString());
item4 = hrg4 * jml4;
}
else
{
jml4 = 0;
}
if (qty5.getText().toString() != null && !(qty5.getText().toString().equals("")))
{
jml5 = Integer.parseInt(qty5.getText().toString());
item5 = hrg5 * jml5;
}
else
{
jml5 = 0;
}
if (qty6.getText().toString() != null && !(qty6.getText().toString().equals("")))
{
jml6 = Integer.parseInt(qty6.getText().toString());
item6 = hrg6 * jml6;
}
else
{
jml6 = 0;
}
if (qty7.getText().toString() != null && !(qty7.getText().toString().equals("")))
{
jml7 = Integer.parseInt(qty7.getText().toString());
item7 = hrg7 * jml7;
}
else
{
jml7 = 0;
}
if (qty8.getText().toString() != null && !(qty8.getText().toString().equals("")))
{
jml8 = Integer.parseInt(qty8.getText().toString());
item8 = hrg8 * jml8;
}
else
{
jml8 = 0;
}
if (qty9.getText().toString() != null && !(qty9.getText().toString().equals("")))
{
jml9 = Integer.parseInt(qty9.getText().toString());
item9 = hrg9 * jml9;
}
else
{
jml9 = 0;
}
if (qty10.getText().toString() != null && !(qty10.getText().toString().equals("")))
{
jml10 = Integer.parseInt(qty10.getText().toString());
item10 = hrg10 * jml10;
}
else
{
jml10 = 0;
}
hasil = item1 + item2 + item3 + item4 + item5 + item6 + item7 + item8 + item9 + item10;
Toast.makeText(getApplicationContext(), "Rp. " + hasil, Toast.LENGTH_LONG).show();
sum.setText("Rp. " + Integer.toString(hasil));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Quantity can't be empty. Please type item quantity", Toast.LENGTH_LONG).show();
}
}
});
Any help will be appreciate, thanks
You are trying to use null as a String:
if (item.equals("null"))
It should be:
if (item == null)
Also the default value of an Spinner or EditText is an empty String (i.e. "") not null. I believe you should use .setText(""); when you reset the values, so really that first if statement should be:
if (item.isEmpty()) // or item.equals("")
Lastly do you have 10 OnItemSelectedListeners that contains 80-90% of the same code? If so your should write one generic listener and use parent.getId() to determine which value to set.