I have a problem in Android, and Ive tried a couple of solutions, but nothing work.
When I scroll the list I get the exception:
java.lang.ClassCastException: com.example.restaurante.SmartMercadoriasAdapter$FirstViewHolder cannot be cast to com.example.restaurante.SmartMercadoriasAdapter$SecondViewHolder
This my code:
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if (tipo.equals("1"))
return 0;
else
return 1;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
MyListSmartMercadoria mercadoria = null;
if(mercadorias.size() > 1){
mercadoria = mercadorias.get(position);
}else{
mercadoria = mercadorias.get(0);
}
tipo = "";
tipo = mercadoria.getTipo();
int viewType = getItemViewType(position);
switch (viewType) {
case 0: {
FirstViewHolder firstViewHolder = null;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_lista_smart_adp, parent, false);
firstViewHolder = new FirstViewHolder(view);
view.setTag(firstViewHolder);
}
else {
firstViewHolder = (FirstViewHolder)view.getTag();
}
firstViewHolder.mTipo.setText(tipo);
String codigo = mercadoria.getCod();
if(codigo.matches("[0-9]+")){
int codI = Integer.parseInt(mercadoria.getCod());
codigo = "[";
codigo += String.format("%06d", codI);
codigo += "]";
}else{
codigo = "[";
codigo += codigo;
int cont = 6 - codigo.length();
for(int i = 0; i < cont; i++){
codigo = codigo + " ";
}
codigo += "]";
}
firstViewHolder.mCodigo.setText(codigo);
firstViewHolder.mDescricao.setText(mercadoria.getNome());
firstViewHolder.mPreco.setText(mercadoria.getPreco());
break;
}
case 1: {
SecondViewHolder holder = null;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_sub_lista_smart_adp, parent, false);
holder = new SecondViewHolder(view);
view.setTag(holder);
}
else holder = (SecondViewHolder)view.getTag();
holder.mTipo.setText(tipo);
String codigo = mercadoria.getCod();
if(codigo.matches("[0-9]+")){
int codI = Integer.parseInt(mercadoria.getCod());
codigo = "[";
codigo += String.format("%06d", codI);
codigo += "]";
}else{
codigo = "[";
codigo += codigo;
int cont = 6 - codigo.length();
for(int i = 0; i < cont; i++){
codigo = codigo + " ";
}
codigo += "]";
}
holder.mCodigo.setText(codigo);
holder.mDescricao.setText(mercadoria.getNome());
holder.mQuant.setText(mercadoria.getPreco());
break;
}
}
return view;
}
protected class SecondViewHolder {
TextView mTipo;
TextView mCodigo;
TextView mDescricao;
EditText mQuant;
public SecondViewHolder(View view) {
mCodigo = (TextView) view.findViewById(R.id.text_view_cod_merc);
mTipo = (TextView) view.findViewById(R.id.text_view_tipo_merc);
mDescricao = (TextView) view.findViewById(R.id.text_view_nome_merc);
mQuant = (EditText) view.findViewById(R.id.text_view_preco_merc);
}
}
protected class FirstViewHolder {
TextView mTipo;
TextView mCodigo;
TextView mDescricao;
TextView mPreco;
public FirstViewHolder(View view) {
mCodigo = (TextView) view.findViewById(R.id.text_view_cod_merc);
mTipo = (TextView) view.findViewById(R.id.text_view_tipo_merc);
mDescricao = (TextView) view.findViewById(R.id.text_view_nome_merc);
mPreco = (TextView) view.findViewById(R.id.text_view_preco_merc);
}
}
EDIT1: The exception occurs in this stretch:
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.merc_sub_lista_smart_adp, parent, false);
holder = new SecondViewHolder(view);
view.setTag(holder);
}
else holder = (SecondViewHolder)view.getTag();
Specifically in view.getTag()
Don't store fields while views are recycled
Try this
#Override
public int getItemViewType(int position) {
String tipo = mercadorias.get(position).getTipo();
if (tipo.equals("1"))
return 0;
else
return 1;
}
Also, this doesn't make sense
if(mercadorias.size() > 1){
mercadoria = mercadorias.get(position);
}else{
mercadoria = mercadorias.get(0);
}
If the Arraylist is empty, this will throw an exception, but if the size is equal to one, then the position should already be the first element
Related
I'm using ExpandapbeListView its work perfect all expand and collapse but I just want to update only particular child item here when I click on plus value should be update in EditText and I don't want to use notifyDatasetChanged() Just want to update only particular field and also i should able to update EditText directly. It can have multiple child item.
Ex: Colgate may have multiple child Item like 100gm,200gm,300gm
So when I click on Plus It should able to get Id of EditText and Update Quantity
#Override
public View getChildView(int productPos, int weightPos, boolean b, View plusMinusView, ViewGroup viewGroup) {
if (plusMinusView == null) {
csHolder = new ChildHolder();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
plusMinusView = inflater.inflate(R.layout.orders_products_plus_minus_design, null);
}
csHolder.minQty = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitMinQtyTxt);
csHolder.totalPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalPriceTxt);
csHolder.weightTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitWeightTxt);
csHolder.unitPrice = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitUnitPriceTxt);
csHolder.totalTaxTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitTotalTaxTxt);
csHolder.netPriceTxt = (TextView) plusMinusView.findViewById(R.id.orderProducts_submitNetPriceTxt);
csHolder.orderQtyEdit = (CustomEditText) plusMinusView.findViewById(R.id.orderProducts_orderQtyTxt);
csHolder.plusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_plusTxtLay);
csHolder.minusTxt = (RelativeLayout) plusMinusView.findViewById(R.id.orderProducts_minusTxtLay);
plusMinusView.setTag(productPos + "_" + weightPos);
String tag = "weight_" + productPos + "_" + weightPos;
csHolder.orderQtyEdit.setTag(tag);
csHolder.plusTxt.setTag(tag);
csHolder.minusTxt.setTag(tag);
//csHolder.plusTxt.setOnClickListener(weightClick);
//csHolder.minusTxt.setOnClickListener(weightClick);
final View finalPlusMinusView = plusMinusView;
csHolder.plusTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
csHolder.orderQtyEdit.setText("5");
}
});
if(!csStatus.equalsIgnoreCase("DRAFT")) {
csHolder.plusTxt.setVisibility(View.GONE);
csHolder.minusTxt.setVisibility(View.GONE);
csHolder.orderQtyEdit.setEnabled(false);
}
else
{
csHolder.plusTxt.setVisibility(View.VISIBLE);
csHolder.minusTxt.setVisibility(View.VISIBLE);
csHolder.orderQtyEdit.setEnabled(true);
}
try
{
csHolder.orderQtyEdit.addTextChangedListener(new MyTextWatcher(csHolder.orderQtyEdit));
JSONObject weighObj = csMainArr.getJSONObject(productPos).getJSONArray("weights").getJSONObject(weightPos);
if(weighObj.has("unit"))
{
csHolder.weightTxt.setText(weighObj.getString("unit"));
}
if (weighObj.has("order_qty") == false)
weighObj.put("order_qty", "0");
if (weighObj.has("sell_price") == false)
weighObj.put("sell_price", "0");
if (weighObj.has("order_qty") == false)
{
csHolder.totalPriceTxt.setText("0.00");
csHolder.totalTaxTxt.setText("0.00");
csHolder.netPriceTxt.setText("0.00");
}
else {
int qty = 0;
double sellPrice = 0.00;
float tax = 0f;
double totalPrice = 0.00;
double totalTax = 0.00;
double netPrice = 0.00;
if(csStatus.equals("DRAFT")) {
qty = Integer.parseInt(weighObj.getString("order_qty"));
sellPrice = weighObj.getDouble("sell_price");
}
else
{
qty = Integer.parseInt(weighObj.has("qty") ? weighObj.getString("qty"):"0");
sellPrice = weighObj.getDouble("unit_price");
}
tax = Float.parseFloat(csMainArr.getJSONObject(productPos).has("tax") ? csMainArr.getJSONObject(productPos).getString("tax") : "0");
totalPrice = qty*sellPrice;
totalTax = (totalPrice*tax)/100;
netPrice = totalPrice + totalTax;
csHolder.totalPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalPrice));
csHolder.totalTaxTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",totalTax));
csHolder.netPriceTxt.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",netPrice));
}
csHolder.orderQtyEdit.isValueChangeMySelf = true;
if(csStatus.equals("DRAFT"))
csHolder.orderQtyEdit.setText(weighObj.getString("order_qty"));
else
csHolder.orderQtyEdit.setText(weighObj.has("qty")?weighObj.getString("qty"):"0");
/*if(weightPos == iClickedItem) {
csHolder.orderQtyEdit.requestFocus();
}
else {
csHolder.orderQtyEdit.clearFocus();
}*/
if(csStatus.equals("DRAFT"))
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("sell_price")?weighObj.getDouble("sell_price") : 0.00));
else
csHolder.unitPrice.setText(getResources().getString(R.string.Rs)+" "+String.format("%.2f",weighObj.has("unit_price")?weighObj.getDouble("unit_price") : 0.00));
csHolder.minQty.setText(weighObj.has("min_order_qty")?weighObj.getString("min_order_qty"):"0");
//View line = (View) plusMinusView.findViewById(R.id.orderProducts_submitDividerLine);
//if(isLast)
// line.setVisibility(View.GONE);
}
catch(Exception e)
{
}
return plusMinusView;
}
I'm using it for grid view, the count of object displayed is correct and it's returning in log is correct but for example 6 object display and the rest repeat them
1,2,3,4,5,6, 1,2,3,4,5,6,.....
my code
public class CustomAdapter extends ArrayAdapter<ItemObject> {
private static float textViewWidth;
public CustomAdapter(ArrayList<ItemObject> array, float textViewWidth) {
super(G.context, R.layout.sample_album_item, array);
CustomAdapter.textViewWidth = textViewWidth;
}
private static class ViewHolder {
ImageView imgScreenShot;
TextView txtAlbumName;
TextView txtAlbumAuthor;
public ViewHolder(View view) {
imgScreenShot = (ImageView) view.findViewById(R.id.screen_shot);
txtAlbumName = (TextView) view.findViewById(R.id.album_name);
txtAlbumAuthor = (TextView) view.findViewById(R.id.album_author);
}
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ItemObject item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.sample_album_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
private static float widthSizeViaParent(TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return textViewWidth - (textWidth * G.displayMetrics.density);
}
}
if getView method without this (convertView == null) condition, everything is correct but scrolling is slowly
My guess is that this block of code makes it run slow:
public void fill(final ArrayAdapter<ItemObject> adapter, final ItemObject item, final int position) {
imgScreenShot.setImageResource(item.getScreenShot());
String albumName = item.getAlbumName();
String albumAuthor = item.getAlbumAuthor();
float musicNameWidthSizeViaParent = widthSizeViaParent(txtAlbumName, albumName);
float musicAuthorWidthSizeViaParent = widthSizeViaParent(txtAlbumAuthor, albumAuthor);
if (musicNameWidthSizeViaParent < 0) {
for (int i = 1; i < albumName.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumName.substring(0, i).trim() + "...") < 0) {
albumName = albumName.substring(0, i - 1).trim() + "...";
break;
}
}
}
if (musicAuthorWidthSizeViaParent < 0) {
for (int i = 1; i < albumAuthor.length() - 1; i++) {
if (widthSizeViaParent(txtAlbumName, albumAuthor.substring(0, i).trim() + "...") < 0) {
albumAuthor = albumAuthor.substring(0, i - 1).trim() + "...";
break;
}
}
}
txtAlbumName.setText(albumName);
txtAlbumAuthor.setText(albumAuthor);
}
Two loops runs for every single item. You probably want to have that logic in the models instead. So when rendering the items, albumName and albumAuthor is already set.
#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 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();
}
}
}
Let's say, I have two textviews, TextView A and B.
when I click on A, I need to change both textviews;
When I click on B, I need it to do something else.
I used the setTag(key,A); and setTag(key,B); The textView A changed correctly but the textView B is null. And when I click on B it works.
Here is my code :
public class CustomeAdapterHowComment extends ArrayAdapter<ItemsHowComment> {
Context context;
ItemsHowComment items;
List<LikersComment> likeItems;
List<ItemsHowComment> Items1;
Bitmap bitmap;
String imageUser = "";
String filePath_Image = "/Pictures/jehad/joj/";
String user_id = "1510";
String secret_id = "789654120";
View v;
String onclick = " ";
int x;
String table = "10";
String target = "";
String type = "";
DataBaseHandler dbobj;
public static String server_List_of_Comments = "https://www.ashabe.comt";
public static String server_Comment_like = "https://www.ashabe.com/";
public static String server_Comment_like_remove = "https://www.ashabe.com/";
public static String server_Comment_Delte = "https://www.ashabe.com/";
public static String server_Comment_likers = "https://www.ashabe.com/";
String response;
public CustomeAdapterHowComment(Context context, int textViewResourceId,
List<ItemsHowComment> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("View ", "View>>>>>>>>");
commentholder h = null;
v = convertView;
items = getItem(position);
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
v = vi.inflate(R.layout.how_comment_list, null);
h = new commentholder();
h.img = (ImageView) v.findViewById(R.id.CommentImg);
h.name = (TextView) v.findViewById(R.id.CommentName);
h.commentBody = (TextView) v.findViewById(R.id.CommentBody);
h.like = (TextView) v.findViewById(R.id.CommentLike);
h.numoflike = (TextView) v.findViewById(R.id.CommentNumOfLike);
v.setTag(h);
} else {
h = (commentholder) v.getTag();
}
imageUser = items.getUserId() + items.getRand();
boolean flag_ImagePath = Methods.checkIfImage_DirExists(filePath_Image
+ imageUser);
if (flag_ImagePath == true) {
Log.v("flag_ImagePath", String.valueOf(flag_ImagePath));
bitmap = Methods.displayBitmapImage(imageUser);
h.img.setImageBitmap(bitmap);
}
h.commentBody.setText(items.getCommentBody());
h.name.setText(items.getName());
if (items.getiLike().equals("0")) {
h.like.setText("Like");
}
if (items.getiLike().equals("1")) {
h.like.setText("Unlike");
}
if (items.getNumOfLike().equals("0")) {
h.numoflike.setText("0");
} else {
h.numoflike.setText(items.getNumOfLike());
}
h.name.setOnClickListener(listener);
h.name.setTag(R.id.CommentName, h.name);
h.name.setTag(position);
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(R.id.CommentNumOfLike, h.numoflike);
h.numoflike.setTag(position);
h.like.setOnClickListener(listener);
h.like.setTag(R.id.CommentLike, h.like);
h.like.setTag(position);
h.img.setOnClickListener(listener);
h.img.setTag(R.id.CommentImg, h.img);
h.img.setTag(position);
return v;
}
private OnClickListener listener = new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View view) {
final int id = view.getId();
type = " ";
CommentEvents t = new CommentEvents();
t.execute();
switch (id) {
case R.id.CommentImg:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
break;
case R.id.CommentName:
// ///profile
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
TextView tv = (TextView) view.getTag(R.id.CommentName);
Log.v("value", x + Items1.get(x).getName());
Toast.makeText(getContext(), Items1.get(x).getName(),
Toast.LENGTH_SHORT).show();
// String user = Items1.get(x).getUserId();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
break;
case R.id.CommentLike:
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
TextView like = (TextView) view.getTag(R.id.CommentLike);
target = Items1.get(x).getCommentId().toString();
type = "like";
CommentEvents s = new CommentEvents();
s.execute(user_id, secret_id, table, target);
if (Items1.get(x).getiLike().equals("0")) {
like.setText("Unlike");
onclick = "true";
} else if (Items1.get(x).getiLike().equals("1")) {
like.setText("Like");
onclick = "true";
}
case R.id.CommentNumOfLike:
// ////howlike
if (onclick.equals("true")) {
x = (Integer) view.getTag();
TextView numofLike = (TextView) view
.getTag(R.id.CommentNumOfLike);
if (numofLike != null) {
if (Items1.get(x).getiLike().equals("0")) {
Log.e("getNumOfLike____unlike", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num + 1;
Log.e("numberunlike", num + "");
numofLike.setText(num + "");
} else if (Items1.get(x).getiLike().equals("1")) {
Log.e("getNumOfLike_______like", Items1.get(x)
.getNumOfLike());
int num = Integer.parseInt(Items1.get(x)
.getNumOfLike().toString());
num = num - 1;
Log.e("numberlike", num + "");
numofLike.setText(num + "");
}
onclick=" "; }
} else {
try {
dbobj = new DataBaseHandler(getContext());
Items1 = dbobj.select_HowComment();
dbobj.CloseDataBase();
Collections.reverse(Items1);
x = (Integer) view.getTag();
Log.v("value", x + "");
target = Items1.get(x).getCommentId().toString();
type = "numoflike";
CommentEvents r = new CommentEvents();
r.execute(user_id, secret_id, table, target);
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
}
}
}
};
Use
View view = v.getParent();
and then try to initialize views with view in onClick
You can set Tag
h.name.setOnClickListener(listener);
h.name.setTag(h.numoflike); // use setTag only once
h.numoflike.setOnClickListener(listener);
h.numoflike.setTag(h.name); // use setTag only once
Then in on click
public void onClick(View v) {
switch(v.getId())
{
case R.id.CommentName :
TextView tv1 = (Button) v.getTag();
TextView tv2 = (TextView) v;
tv1.setText("clicked");
tv2.setText("clicked");
break;
case R.id.CommentNumOfLike :
//do something
break;
}
}
Or in onClick Initialize yours views
View view = v.getParent();
TextView tv = view.findVIewById(R.id.CommentName);
TextView tv1 = view.findVIewById(R.id.CommentNumOfLike);
tv.setText("clicked");
tv1.setText("clicked");