Radio Group remembers old items - android

In my "FilterChoice" activity, I create the layout dynamically. I create a Radio Group and add Radio Buttons in it depending on the size of an ArrayList. There's a list in my "Filters" activity. The radio buttons are different depending on the filters clicked. When I click "Prices" filter, it views six items on the "FilterChoice" activity. Then pressing back button, when I click "Categories" filter, the checkedId's in the onCheckedChanged() starts from seven, instead of one. Why does it not start from one in the new activity call? How to solve it? Here's my "FilterChoice" activity.
`
public class FilterChoice extends AppCompatActivity {
RadioButton rb;
String filter;
String selection, domain, temp;
RadioGroup rg;
public static ArrayList<KeyValuePair> cate_old;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(FilterChoice.this);
LinearLayout.LayoutParams lrp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(lrp);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// rb = new RadioButton(FilterChoice.this);
// rb.setText("All");
// rg.addView(rb);
Intent intent = getIntent();
filter = intent.getExtras().getString("filter");
if (filter.equals("Price Range")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.prices.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.price_s_sel + "-"
+ SearchResults.price_e_sel + " ("
+ SearchResults.price_val + ")");
rg.addView(rb);
} else {
int it;
for (it = 0; it < SearchResults.prices.size() - 1; it++) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.prices.get(it).key + "-"
+ SearchResults.prices.get(it + 1).key + " ("
+ SearchResults.prices.get(it).value + ")");
rg.addView(rb);
}
rb = new RadioButton(FilterChoice.this);
rb.setText("Above" + SearchResults.prices.get(it).key + " ("
+ SearchResults.prices.get(it).value + ")");
rg.addView(rb);
}
} else if (filter.equals("Sites")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.site.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.site_sel + " ("
+ SearchResults.site_val + ")");
rg.addView(rb);
// }
} else {
StringTokenizer st;
for (int i = 0; i < SearchResults.site.size(); i++) {
st = new StringTokenizer(SearchResults.site.get(i).key, ".");
if (st.hasMoreTokens()) {
domain = st.nextToken();
}
rb = new RadioButton(FilterChoice.this);
rb.setText(domain + " (" + SearchResults.site.get(i).value
+ ")");
rg.addView(rb);
}
}
} else if (filter.equals("Categories")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.cate.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.cate_sel + " ("
+ SearchResults.cate_val + ")");
rg.addView(rb);
// }
} else {
for (int i = 0; i < SearchResults.cate.size(); i++) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.cate.get(i).key + " ("
+ SearchResults.cate.get(i).value + ")");
rg.addView(rb);
}
}
} else if (filter.equals("Colors")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.cols.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.cols_sel + " ("
+ SearchResults.cols_val + ")");
rg.addView(rb);
} else {
for (int i = 0; i < SearchResults.cols.size(); i++) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.cols.get(i).key + " ("
+ SearchResults.cols.get(i).value + ")");
rg.addView(rb);
}
}
} else if (filter.equals("Brands")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.brands.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.brand_sel + " ("
+ SearchResults.brand_val + ")");
rg.addView(rb);
} else {
for (int i = 0; i < SearchResults.brands.size(); i++) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.brands.get(i).key + " ("
+ SearchResults.brands.get(i).value + ")");
rg.addView(rb);
}
}
} else if (filter.equals("Sub Categories")) {
rg = new RadioGroup(FilterChoice.this);
rg.setLayoutParams(lp);
if (SearchResults.subcate.size() == 1) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.subcate_sel + " ("
+ SearchResults.subcate_val + ")");
rg.addView(rb);
} else {
for (int i = 0; i < SearchResults.subcate.size(); i++) {
rb = new RadioButton(FilterChoice.this);
rb.setText(SearchResults.subcate.get(i).key + " ("
+ SearchResults.subcate.get(i).value + ")");
rg.addView(rb);
}
}
}
linearLayout.addView(rg);
setContentView(linearLayout);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (filter.equals("Price Range")) {
} else if (filter.equals("Sites")) {
Log.e("checkedId", "" + checkedId);
if (SearchResults.site.size() > 1) {
selection = SearchResults.site.get(checkedId - 1).key;
temp = SearchResults.site.get(0).key;
SearchResults.site_sel = selection;
SearchResults.site_val = SearchResults.site
.get(checkedId - 1).value;
SearchResults.site_id = checkedId;
}
} else if (filter.equals("Categories")) {
Log.e("checkedId", "" + checkedId);
if (SearchResults.cate.size() > 1) {
selection = SearchResults.cate.get(checkedId - 1).key;
temp = SearchResults.cate.get(0).key;
SearchResults.cate_sel = selection;
SearchResults.cate_val = SearchResults.cate
.get(checkedId - 1).value;
SearchResults.cate_id = checkedId;
}
} else if (filter.equals("Colors")) {
Log.e("checkedId", "" + checkedId);
if (SearchResults.cols.size() > 1) {
selection = SearchResults.cols.get(checkedId - 1).key;
temp = SearchResults.cols.get(0).key;
SearchResults.cols_sel = selection;
SearchResults.cols_val = SearchResults.cols
.get(checkedId - 1).value;
SearchResults.cols_id = checkedId;
}
} else if (filter.equals("Brands")) {
Log.e("checkedId", "" + checkedId);
if (SearchResults.brands.size() > 1) {
selection = SearchResults.brands.get(checkedId - 1).key;
temp = SearchResults.brands.get(0).key;
SearchResults.brand_sel = selection;
SearchResults.brand_val = SearchResults.brands
.get(checkedId - 1).value;
SearchResults.brand_id = checkedId;
}
} else if (filter.equals("Sub Categories")) {
Log.e("checkedId", "" + checkedId);
if (SearchResults.subcate.size() > 1) {
selection = SearchResults.subcate.get(checkedId - 1).key;
temp = SearchResults.subcate.get(0).key;
SearchResults.subcate_sel = selection;
SearchResults.subcate_val = SearchResults.subcate
.get(checkedId - 1).value;
SearchResults.subcate_id = checkedId;
}
}
Intent intent = new Intent(FilterChoice.this, Filters.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
}
`

I have not yet figured out the behavior you describe, but I would point out that you can set the IDs of the RadioButtons you're creating dynamically. For example, in your "Categories" block:
for (int i = 0; i < SearchResults.cate.size(); i++) {
rb = new RadioButton(FilterChoice.this);
rb.setId(i + 1);
rb.setText(SearchResults.cate.get(i).key + " ("
+ SearchResults.cate.get(i).value + ")");
rg.addView(rb);
}
This will set IDs from 1 to SearchResults.cate.size(), which I believe is what you're going for.

Related

Error in getting list position in Android

View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img_smc_add:
int addPos = Integer.parseInt("" + v.getTag());
int addQty = Integer.parseInt("" + mArrListMyCart.get(addPos).getmStrQty());
addQty++;
mArrListMyCart.get(addPos).setmStrQty("" + addQty);
myCartAdapter.notifyDataSetChanged();
mJsonObject = new JSONObject();
JSONObject option = new JSONObject();
try {
mJsonObject.put("productid", mArrListMyCart.get(addPos).getmStrProductId());
mJsonObject.put("itemid", mArrListMyCart.get(addPos).getmStrItemId());
mJsonObject.put("qty", mArrListMyCart.get(addPos).getmStrQty());
mJsonObject.put("shoppingcartid", shoppingcartid);
mJsonObject.put("customerid", "" + SessionClass.getUserId(getActivity()));
// option.put("options", "");
mJsonObject.put("options", "" + option);
} catch (JSONException e) {
e.printStackTrace();
}
editCartDetail();
myCartAdapter.notifyDataSetChanged();
//calculateGrandTotal();
break;
case R.id.img_smc_remove:
int removePos = Integer.parseInt("" + v.getTag());
int removeQty = Integer.parseInt("" + mArrListMyCart.get(removePos).getmStrQty());
if (removeQty > 1) {
removeQty--;
mArrListMyCart.get(removePos).setmStrQty("" + removeQty);
myCartAdapter.notifyDataSetChanged();
} else {
removeQty = 1;
mArrListMyCart.get(removePos).setmStrQty("" + removeQty);
myCartAdapter.notifyDataSetChanged();
}
myCartAdapter.notifyDataSetChanged();
mJsonObject = new JSONObject();
option = new JSONObject();
try {
mJsonObject.put("productid", mArrListMyCart.get(removePos).getmStrProductId());
mJsonObject.put("itemid", mArrListMyCart.get(removePos).getmStrItemId());
mJsonObject.put("qty", mArrListMyCart.get(removePos).getmStrQty());
mJsonObject.put("shoppingcartid", "" + shoppingcartid);
mJsonObject.put("customerid", "" + SessionClass.getUserId(getActivity()));
Log.e("customerid", "" + SessionClass.getUserId(getActivity()));
// option.put("options", "");
mJsonObject.put("options", "" + option);
} catch (JSONException e) {
e.printStackTrace();
}
editCartDetail();
//getMyCartItems();
myCartAdapter.notifyDataSetChanged();
// calculateGrandTotal();
break;
case R.id.iv_edit_cart_item:
FragmentManager fm=getActivity().getSupportFragmentManager();
Fragment fragment = new ProductDetailActivity();
int updatePos = v.getTag() != null ? Integer.parseInt("" + v.getTag()):0;
Toast.makeText(getActivity(),"updatePos:"+ updatePos,Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("key","update");
bundle.putString("product_id", mArrListMyCart.get(updatePos).getmStrProductId());
bundle.putString("item_id", mArrListMyCart.get(updatePos).getmStrItemId());
fragment.setArguments(bundle);
// showAlert("Product id-->" + mArrListMyCart.get(Integer.parseInt(""+v.getTag())).getmStrProductId(), -1);
fm.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("").commit();
break;
case R.id.iv_remove_cart_item:
int cartPos = Integer.parseInt("" + v.getTag());
int cartQty = Integer.parseInt("" + mArrListMyCart.get(cartPos).getmStrQty());
item_id = mArrListMyCart.get(cartPos).getmStrItemId();
product_id = mArrListMyCart.get(cartPos).getmStrProductId();
getDeleteCartItems();
mArrListMyCart.remove(cartPos);
//getMyCartItems();
myCartAdapter.notifyDataSetChanged();
if (cartQty > 1) {
mArrListMyCart.remove(cartPos);
myCartAdapter.notifyDataSetChanged();
} else {
removeQty = 1;
}
//calculateGrandTotal();
break;
case R.id.tv_show_details:
int pos = Integer.parseInt("" + v.getTag());
item_id = mArrListMyCart.get(pos).getmStrItemId();
product_id = mArrListMyCart.get(pos).getmStrProductId();
Toast.makeText(getActivity(),"updatePos:"+ pos,Toast.LENGTH_SHORT).show();
getCartItemDetail();
break;
}
}
};
i created listview based upon list of products.when i'm using below line,
`int updatePos = v.getTag() != null ? Integer.parseInt("" + v.getTag()):0;`
the updatepos always null.so if i select e.g a[3] product but it show always a[0] product details.how to solve it?.the updatePos is not update based upon selecting item in list.always the updatePos is 0.what can i do?

How to display same image in ImageView if I click on the horizontal images in android

I have the list of images in horizontal LinearLayout If I click particular image the same image will appear on the above of single image view.
How can I get the position of Images in Image View.
CODE
JSONArray multipleimage = alertObj.getJSONArray(PRODUCT_IMAGES);
/*JSONObject singleimage = multipleimage.getJSONObject(Integer.parseInt("original_res"));
String singleimg = productpath + alertObj.getString("seller_id") + String.valueOf(singleimage);
firstimages=(ImageView)
findViewById(R.id.singleimage);
YelloPage.imageLoader.displayImage(singleimg,firstimages,options);*/
horizontalimage=(LinearLayout) findViewById(R.id.linearimage);
if(multipleimage.length()>0)
{
for (int j = 0; j < multipleimage.length(); j++) {
JSONObject pimages = multipleimage.getJSONObject(j);
JSONObject oneimage = multipleimage.getJSONObject(0);
ii = new ImageView(singleshooppingcart.this);
multipleimages = (ImageView) findViewById(R.id.singleimage);
ii.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayout.LayoutParams image = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.width = 150;
image.height = 150;
image.setMargins(5, 0, 0, 0);
String multimgs = pimages.getString("original_res");
String oneimg = oneimage.getString("original_res");
String[] img2 = multimgs.split("\\.");
String imagone = productpath + alertObj.getString("seller_id") + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String singleiamges = productpath + alertObj.getString("seller_id") + '/' + oneimg;
YelloPage.imageLoader.displayImage(imagone, ii, options);
YelloPage.imageLoader.displayImage(singleiamges, multipleimages, options);
ii.setLayoutParams(image);
horizontalimage.addView(ii);
ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
How to solve this problem Thanks in Advance.
You can use many approaches for this-
Simplest approach is using ViewGroup#indexOfChild(View child) method. This will simply return what you want.
Or you can use View#setTag(Object) and View#getTag(), specially if you want to get some thing more than mere index in onClick.
You can also use View#setTag(int, Object) and View#getTag(int), if you want to set more than one tag per view.
Hope below example code for first approach helps-
ii.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// the parameter view here is your imageview, which is clicked.
// horizontalimage is your LinearLayout, which is a ViewGroup
int indexOfImage = horizontalimage.indexOfChild(view);
// do what you want to do with index
}
});
Not tested..try like this...
JSONArray multipleimage = alertObj.getJSONArray(PRODUCT_IMAGES);
/*JSONObject singleimage = multipleimage.getJSONObject(Integer.parseInt("original_res"));
String singleimg = productpath + alertObj.getString("seller_id") + String.valueOf(singleimage);
firstimages = (ImageView)findViewById(R.id.singleimage);
YelloPage.imageLoader.displayImage(singleimg,firstimages,options);*/
horizontalimage = (LinearLayout)findViewById(R.id.linearimage);
if(multipleimage.length()>0)
{
for (int j = 0; j < multipleimage.length(); j++) {
JSONObject pimages = multipleimage.getJSONObject(j);
JSONObject oneimage = multipleimage.getJSONObject(0);
ii = new ImageView(singleshooppingcart.this);
multipleimages = (ImageView) findViewById(R.id.singleimage);
ii.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayout.LayoutParams image = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.width = 150;
image.height = 150;
image.setMargins(5, 0, 0, 0);
String multimgs = pimages.getString("original_res");
String oneimg = oneimage.getString("original_res");
String[] img2 = multimgs.split("\\.");
String imagone = productpath + alertObj.getString("seller_id") + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String singleiamges = productpath + alertObj.getString("seller_id") + '/' + oneimg;
YelloPage.imageLoader.displayImage(imagone, ii, options);
YelloPage.imageLoader.displayImage(singleiamges, multipleimages, options);
ii.setLayoutParams(image);
horizontalimage.addView(ii);
ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
multipleimages.setImageURI (singleiamges);
}
});
}
}

getting duplicate objects in json in android

I am putting objects in Json but I want only 1 key to be update.Right now it is creating new object every time function is called I want only quantity should get updated if it is already there in json. Please help
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private List<ProductBean> productList ;
static int qtyValues;
static int itemRem = -1;
static int addItem = 1;
static boolean isSKU1;
static boolean isSKU2;
static boolean isSKU;
static int value;
static int totalAmount = 0;
static int totalItems = 0;
SharedPreferences myPrefs;
SharedPreferences.Editor editor;
private final Activity context;
private AQuery aq;
JSONObject jsonObject = new JSONObject();
JSONArray obj = new JSONArray();
ArrayList list = new ArrayList();
public ProductAdapter(Activity context,List<ProductBean> productList){
this.productList = productList;
this.context = context;
isSKU = true;
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
myPrefs = context.getSharedPreferences("qty", Context.MODE_PRIVATE);
editor = myPrefs.edit();
aq = new AQuery(context.getApplicationContext());
final ProductBean productBean = productList.get(position);
holder.extratxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.BLACK);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice() + "");
isSKU = true;
isSKU1 = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)+"");
}
});
holder.extratxt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.BLACK);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice2() + "");
isSKU1 = true;
isSKU = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)+"");
}
});
holder.extratxt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.BLACK);
holder.extratxt1.setText(productBean.getProductPrice3() + "");
isSKU2 = true;
isSKU = false;
isSKU1 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)+"");
}
});
holder.decreaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = 0 - productBean.getProductPrice2();
add(itemRem);
amount(value);
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = 0 - productBean.getProductPrice3();
add(itemRem);
amount(value);
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = 0 - productBean.getProductPrice();
add(itemRem);
amount(value);
}
}
}
});
holder.increaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId2(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = productBean.getProductPrice2();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId2(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice2());
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId3(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = productBean.getProductPrice3();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId3(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice3());
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId1(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = productBean.getProductPrice();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId1(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice());
}
}
}
});
holder.txtTitle.setText(productBean.getProductName());
holder.extratxt.setText(productBean.getSkuId1() + "");
holder.extratxt2.setText(productBean.getSkuId2() + "");
holder.extratxt3.setText(productBean.getSkuId3() + "");
holder.extratxt1.setText(productBean.getProductPrice() + "");
holder.imageView1.setImageResource(R.drawable.rupee);
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0) + "");
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_beverages_item, viewGroup, false);
return new ProductViewHolder(itemView);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView extratxt;
TextView extratxt2;
TextView extratxt3;
ImageView imageView1;
TextView extratxt1;
TextView qtyCounter;
ImageView decreaseQty;
ImageView increaseQty;
/**
* Instantiates a new card view holder.
*
* #param v the v
*/
public ProductViewHolder(View v) {
super(v);
imageView = (ImageView) v.findViewById(R.id.drinks);
txtTitle = (TextView) v.findViewById(R.id.drinkTitle);
extratxt = (TextView) v.findViewById(R.id.drinkQuantity);
extratxt2 = (TextView) v.findViewById(R.id.drinkQuantity1);
extratxt3 = (TextView) v.findViewById(R.id.drinkQuantity2);
imageView1 = (ImageView) v.findViewById(R.id.rupee);
extratxt1 = (TextView) v.findViewById(R.id.drinkPrice);
qtyCounter = (TextView) v.findViewById(R.id.drinkCounter);
decreaseQty = (ImageView) v.findViewById(R.id.decreaseCounter);
increaseQty = (ImageView) v.findViewById(R.id.increaseCounter);
extratxt.setTextColor(Color.BLACK);
}
}
public void setCartItem(final int skuId ,final int qty , final long productId , String description , String productName , int price) {
try {
jsonObject.put("skuId",skuId);
jsonObject.put("quantity",qty);
jsonObject.put("productId",productId);
jsonObject.put("price",price);
jsonObject.put("productName",productName);
jsonObject.put("description",description);
obj.put(jsonObject);
editor.putString("data",obj.toString());
editor.commit();
}catch (JSONException e){
e.printStackTrace();
}
}
public void add(int items){
totalItems = totalItems + items;
editor.putInt("totalItems",totalItems);
editor.commit();
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
}
else{
BeveragesMainActivity.cartTotal.setVisibility(View.INVISIBLE);
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
}
public void amount(int price){
totalAmount = totalAmount+price;
editor.putInt("totalAmount", totalAmount);
editor.commit();
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
}
Use this code inside setCartItem(...) method
// loop through each object
for (int i = 0; i < obj.length(); i++) {
try {
JSONObject item = obj.getJSONObject(i);
int itemId = item.getInt("skuId ");
if (itemId == skuId) {// object already exists update quantity
item.put("quantity", qty);
// update other keys if you want to
// do other stuff
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject jsonObject = new JSONObject();
// If skudId does not exits in the array list add new one
try {
jsonObject.put("skuId", skuId);
jsonObject.put("quantity", qty);
jsonObject.put("productId", productId);
jsonObject.put("price", price);
jsonObject.put("productName", productName);
jsonObject.put("description", description);
obj.put(jsonObject);
editor.putString("data", obj.toString());
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Smooth scrolling in listview with multiple row layouts

I have a listview which inflates 4 different types of row layouts depending on the position(overriden getViewTypeCount() and getItemViewType(int position) to achieve it) .Each row has an Image and other textviews and buttons . I am loading the image in a seaparate thread . I am using android viewholder pattern to cache the viewholders for each row type .
When I scroll from one kind of row layout to another row layout I observe a jerkiness in scrolling .
Any pointers to improve will be appreciated.
public View getView(int arg0, View arg1, ViewGroup arg2) {
int width = (Utils.getWidth(mCtx)-Utils.dpToPx(40, mCtx)) ;
final FeedViewData mFeedViewData = getFeedViewData().get(arg0);
if( getItemViewType(arg0) == Utils.SMALL_OBJECT_LEFT){
ObjectViewHolder viewHolderLeft = new ObjectViewHolder() ;
float imgWidth = (width-Utils.dpToPx(1, mCtx))*(0.6f);
float descWidth = (width-Utils.dpToPx(1, mCtx))*(0.4f) ;
float rowHeight = (width-Utils.dpToPx(1, mCtx))*(0.6f)*Utils.PRODUCT_PRI_ASPECT_RATIO;
if(arg1==null){
LayoutInflater inflater = ((Activity)mCtx).getLayoutInflater();
arg1 = inflater.inflate(R.layout.view_multipane_left_image, arg2, false);
viewHolderLeft.row = arg1.findViewById(R.id.rowLayout);
viewHolderLeft.imagesLayout = (RelativeLayout)arg1.findViewById(R.id.layout_image);
viewHolderLeft.objImg = (ImageView)arg1.findViewById(R.id.img_object);
viewHolderLeft.price = (TextView)arg1.findViewById(R.id.text_price);
viewHolderLeft.paneMargin = arg1.findViewById(R.id.pane_margin);
viewHolderLeft.descriptionsLayout = (LinearLayout)arg1.findViewById(R.id.layout_description);
viewHolderLeft.likeActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_like);
viewHolderLeft.likeCount = (TextView)arg1.findViewById(R.id.text_like_count);
viewHolderLeft.shareActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_share);
viewHolderLeft.shareCount = (TextView)arg1.findViewById(R.id.text_share_count);
viewHolderLeft.commentActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_comment);
viewHolderLeft.commentCount = (TextView)arg1.findViewById(R.id.text_share_comment);
viewHolderLeft.activityLayout = (LinearLayout)arg1.findViewById(R.id.layout_activity);
viewHolderLeft.userImg = (ImageView)arg1.findViewById(R.id.img_user);
viewHolderLeft.userActivity = (TextView)arg1.findViewById(R.id.text_activity);
viewHolderLeft.timeline = (TextView)arg1.findViewById(R.id.text_timeline);
RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
imgLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
viewHolderLeft.objImg.setLayoutParams(imgLp);
RelativeLayout.LayoutParams rlLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
rlLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
rlLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.TRUE);
viewHolderLeft.imagesLayout.setLayoutParams(rlLp);
RelativeLayout.LayoutParams marginLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams(Utils.dpToPx(1,mCtx),(int)rowHeight));
marginLp.addRule(RelativeLayout.RIGHT_OF,R.id.layout_image);
viewHolderLeft.paneMargin.setLayoutParams(marginLp);
RelativeLayout.LayoutParams descLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)descWidth,(int)rowHeight));
descLp.addRule(RelativeLayout.RIGHT_OF,R.id.pane_margin);
descLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
viewHolderLeft.descriptionsLayout.setLayoutParams(descLp);
ImageSizeUtils.defineTargetSizeForView(viewHolderLeft.objImg, (int)imgWidth,(int)rowHeight);
arg1.setTag(viewHolderLeft);
}
else{
viewHolderLeft = (ObjectViewHolder)arg1.getTag();
ImageSizeUtils.defineTargetSizeForView(viewHolderLeft.objImg, (int)imgWidth,(int)rowHeight);
}
String mLeftImgUrl = null;
mLeftImgUrl = Utils.m_img_base_url+
mFeedViewData.getProductId() + "/pri-" + mFeedViewData.getFileidn()+".jpg";
try{
ImageLoader.getInstance().displayImage(mLeftImgUrl, viewHolderLeft.objImg,
new SingleImageListener(mFeedViewData,viewHolderLeft.objImg));
}
catch(Exception e){
return null;
}
viewHolderLeft.objImg.setOnClickListener(new ProdImageOnClickListener(mFeedViewData));
if(mFeedViewData.getIsLoved())
viewHolderLeft.likeActionLayout.setBackgroundColor(mCtx.getResources().getColor(R.color.auth_btn_color_normal));
else
viewHolderLeft.likeActionLayout.setBackgroundResource(R.drawable.selector_pink_button);
viewHolderLeft.likeActionLayout.setOnClickListener(new LikeActionListener(mFeedViewData,viewHolderLeft.likeActionLayout));
viewHolderLeft.shareActionLayout.setOnClickListener(new ShareClickListener(mLeftImgUrl));
viewHolderLeft.commentActionLayout.setOnClickListener(new OnCommentClickListener(mFeedViewData));
viewHolderLeft.price.setTypeface(Utils.getFontForRupeeSymb(mCtx));
viewHolderLeft.price.setText(Html.fromHtml( "` " + "</font>" + "<b>" + mFeedViewData.getPrice() + "</b>"));
if(!mFeedViewData.getLikeCount().equals("0"))
viewHolderLeft.likeCount.setText(" (" + mFeedViewData.getLikeCount() + ")");
if(!mFeedViewData.getShareCount().equals("0"))
viewHolderLeft.shareCount.setText(" (" + mFeedViewData.getShareCount() + ")");
if(!mFeedViewData.getRevCount().equals("0"))
viewHolderLeft.commentCount.setText(" (" + mFeedViewData.getRevCount() + ")");
int minutes=0;
if(mFeedViewData.getTimestamp()!=""){
long timeDiff = System.currentTimeMillis() - Long.parseLong(mFeedViewData.getTimestamp());
minutes = (int)((int) (timeDiff/1000))/60;
}
if(mFeedViewData.getUsername().length()>0){
ImageLoader.getInstance().displayImage(mFeedViewData.getTnPic(), viewHolderLeft.userImg,new UserImageListener(viewHolderLeft.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getUsername() + "</b>" + " "+ mFeedViewData.getActivity()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getDoer()), 0, mFeedViewData.getUsername().length(), Spanned.SPAN_COMPOSING);
viewHolderLeft.userActivity.setText(ss);
if(minutes!=0){
viewHolderLeft.timeline.setText( minutes + " minutes ago");
}
viewHolderLeft.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getReview()!=null){
ImageLoader.getInstance().displayImage(mFeedViewData.getReview().getTnUrl(), viewHolderLeft.userImg,new UserImageListener(viewHolderLeft.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getReview().getReviewerName() + "</b>" + " "+ mFeedViewData.getReview().getReview()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getReview().getId()), 0, mFeedViewData.getReview().getReviewerName().length(), Spanned.SPAN_COMPOSING);
viewHolderLeft.userActivity.setText(ss);
if(minutes!=0){
viewHolderLeft.timeline.setText( minutes + " minutes ago");
}
viewHolderLeft.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getActivity().length()>0){
String activityText;
if(mFeedViewData.getActivity().equals("null"))
activityText = Html.fromHtml("<b>" + "A user: "+ "</b>" + "" +" ").toString();
else
activityText = Html.fromHtml("<b>" + "A user: "+ "</b>" + "" +" "+ mFeedViewData.getActivity()).toString();
viewHolderLeft.userActivity.setText(activityText);
if(minutes!=0){
viewHolderLeft.timeline.setText( minutes + " minutes ago");
}
viewHolderLeft.userImg.setImageResource(R.drawable.ic_blank_profile);
}
if(feedType == Utils.ADAPTER_FEED_TUTORIAL){
viewHolderLeft.userActivity.setClickable(false);
viewHolderLeft.objImg.setClickable(false);
}
}
else if(getItemViewType(arg0) == Utils.SMALL_OBJECT_RIGHT){
ObjectViewHolder viewHolderRight = new ObjectViewHolder();
float imgWidth = (width-Utils.dpToPx(1, mCtx))*(0.6f);
float descWidth = (width-Utils.dpToPx(1, mCtx))*(0.4f) ;
float rowHeight = (width-Utils.dpToPx(1, mCtx))*(0.6f)*Utils.PRODUCT_PRI_ASPECT_RATIO;
if(arg1==null){
LayoutInflater inflater = ((Activity)mCtx).getLayoutInflater();
arg1 = inflater.inflate(R.layout.view_multipane_right_image, arg2, false);
viewHolderRight.row = arg1.findViewById(R.id.rowLayout);
viewHolderRight.imagesLayout = (RelativeLayout)arg1.findViewById(R.id.layout_image);
viewHolderRight.objImg = (ImageView)arg1.findViewById(R.id.img_object);
viewHolderRight.price = (TextView)arg1.findViewById(R.id.text_price);
viewHolderRight.paneMargin = arg1.findViewById(R.id.pane_margin);
viewHolderRight.descriptionsLayout = (LinearLayout)arg1.findViewById(R.id.layout_description);
viewHolderRight.likeActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_like);
viewHolderRight.likeCount = (TextView)arg1.findViewById(R.id.text_like_count);
viewHolderRight.shareActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_share);
viewHolderRight.shareCount = (TextView)arg1.findViewById(R.id.text_share_count);
viewHolderRight.commentActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_comment);
viewHolderRight.commentCount = (TextView)arg1.findViewById(R.id.text_share_comment);
viewHolderRight.activityLayout = (LinearLayout)arg1.findViewById(R.id.layout_activity);
viewHolderRight.userImg = (ImageView)arg1.findViewById(R.id.img_user);
viewHolderRight.userActivity = (TextView)arg1.findViewById(R.id.text_activity);
viewHolderRight.timeline = (TextView)arg1.findViewById(R.id.text_timeline);
RelativeLayout.LayoutParams descLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)descWidth,(int)rowHeight));
descLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.TRUE);
descLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
viewHolderRight.descriptionsLayout.setLayoutParams(descLp);
RelativeLayout.LayoutParams marginLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams(Utils.dpToPx(1,mCtx),(int)rowHeight));
marginLp.addRule(RelativeLayout.RIGHT_OF,R.id.layout_description);
viewHolderRight.paneMargin.setLayoutParams(marginLp);
RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
imgLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
viewHolderRight.objImg.setLayoutParams(imgLp);
RelativeLayout.LayoutParams rlLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
rlLp.addRule(RelativeLayout.RIGHT_OF,R.id.pane_margin);
rlLp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
viewHolderRight.imagesLayout.setLayoutParams(rlLp);
ImageSizeUtils.defineTargetSizeForView(viewHolderRight.objImg, (int)imgWidth,(int)rowHeight);
arg1.setTag(viewHolderRight);
}
else{
viewHolderRight = (ObjectViewHolder)arg1.getTag();
ImageSizeUtils.defineTargetSizeForView(viewHolderRight.objImg, (int)imgWidth,(int)rowHeight);
}
String mRightImgUrl = null;
mRightImgUrl = Utils.m_img_base_url+
mFeedViewData.getProductId() + "/pri-" + mFeedViewData.getFileidn()+".jpg";
try{
ImageLoader.getInstance().displayImage(mRightImgUrl, viewHolderRight.objImg,
new SingleImageListener(mFeedViewData,viewHolderRight.objImg));
}
catch(Exception e){
return null;
}
viewHolderRight.objImg.setOnClickListener(new ProdImageOnClickListener(mFeedViewData));
if(mFeedViewData.getIsLoved())
viewHolderRight.likeActionLayout.setBackgroundColor(mCtx.getResources().getColor(R.color.auth_btn_color_normal));
else
viewHolderRight.likeActionLayout.setBackgroundResource(R.drawable.selector_pink_button);
viewHolderRight.likeActionLayout.setOnClickListener(new LikeActionListener(mFeedViewData,viewHolderRight.likeActionLayout));
viewHolderRight.shareActionLayout.setOnClickListener(new ShareClickListener(mRightImgUrl));
viewHolderRight.commentActionLayout.setOnClickListener(new OnCommentClickListener(mFeedViewData));
viewHolderRight.price.setTypeface(Utils.getFontForRupeeSymb(mCtx));
viewHolderRight.price.setText(Html.fromHtml( "` " + "</font>" + "<b>" + mFeedViewData.getPrice() + "</b>"));
if(!mFeedViewData.getLikeCount().equals("0"))
viewHolderRight.likeCount.setText(" (" + mFeedViewData.getLikeCount() + ")");
if(!mFeedViewData.getShareCount().equals("0"))
viewHolderRight.shareCount.setText(" (" + mFeedViewData.getShareCount() + ")");
if(!mFeedViewData.getRevCount().equals("0"))
viewHolderRight.commentCount.setText(" (" + mFeedViewData.getRevCount() + ")");
int minutes=0;
if(mFeedViewData.getTimestamp()!=""){
long timeDiff = System.currentTimeMillis() - Long.parseLong(mFeedViewData.getTimestamp());
minutes = (int)((int) (timeDiff/1000))/60;
}
if(mFeedViewData.getUsername().length()>0){
ImageLoader.getInstance().displayImage(mFeedViewData.getTnPic(), viewHolderRight.userImg,new UserImageListener(viewHolderRight.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getUsername() + "</b>" + " "+ mFeedViewData.getActivity()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getDoer()), 0, mFeedViewData.getUsername().length(), Spanned.SPAN_COMPOSING);
viewHolderRight.userActivity.setText(ss);
if(minutes!=0){
viewHolderRight.timeline.setText( minutes + " minutes ago");
}
viewHolderRight.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getReview()!=null){
ImageLoader.getInstance().displayImage(mFeedViewData.getReview().getTnUrl(), viewHolderRight.userImg,new UserImageListener(viewHolderRight.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getReview().getReviewerName() + "</b>" + " "+ mFeedViewData.getReview().getReview()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getReview().getId()), 0, mFeedViewData.getReview().getReviewerName().length(), Spanned.SPAN_COMPOSING);
viewHolderRight.userActivity.setText(ss);
if(minutes!=0){
viewHolderRight.timeline.setText( minutes + " minutes ago");
}
viewHolderRight.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getActivity().length()>0){
String activityText = Html.fromHtml("<b>" + "A user: "+ "</b>" + " "+ mFeedViewData.getActivity()).toString();
viewHolderRight.userActivity.setText(activityText);
if(minutes!=0){
viewHolderRight.timeline.setText( minutes + " minutes ago");
}
viewHolderRight.userImg.setImageResource(R.drawable.ic_blank_profile);
}
if(feedType == Utils.ADAPTER_FEED_TUTORIAL){
viewHolderRight.userActivity.setClickable(false);
viewHolderRight.objImg.setClickable(false);
}
}
else if(getItemViewType(arg0) == Utils.MAGAZINE_OBJECT){
MagazineViewHolder viewHolderMag = new MagazineViewHolder();
float imgWidth = width/2;
float descWidth = width;
float rowHeight = ((width)/2)*Utils.MAG_ASPECT_RATIO;
if(arg1==null){
LayoutInflater inflater = ((Activity)mCtx).getLayoutInflater();
arg1 = inflater.inflate(R.layout.view_magazine, arg2, false);
viewHolderMag.row = arg1.findViewById(R.id.rowLayout);
viewHolderMag.imagesLayout = (RelativeLayout)arg1.findViewById(R.id.layout_image);
viewHolderMag.magImgLeft = (ImageView)arg1.findViewById(R.id.img_object_1);
viewHolderMag.magImgRight = (ImageView)arg1.findViewById(R.id.img_object_2);
viewHolderMag.price = (TextView)arg1.findViewById(R.id.text_price);
viewHolderMag.likeActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_like);
viewHolderMag.likeCount = (TextView)arg1.findViewById(R.id.text_like_count);
viewHolderMag.shareActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_share);
viewHolderMag.shareCount = (TextView)arg1.findViewById(R.id.text_share_count);
viewHolderMag.commentActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_comment);
viewHolderMag.commentCount = (TextView)arg1.findViewById(R.id.text_share_comment);
viewHolderMag.activityLayout = (LinearLayout)arg1.findViewById(R.id.layout_activity);
viewHolderMag.userImg = (ImageView)arg1.findViewById(R.id.img_user);
viewHolderMag.userActivity = (TextView)arg1.findViewById(R.id.text_activity);
viewHolderMag.timeline = (TextView)arg1.findViewById(R.id.text_timeline);
LinearLayout.LayoutParams imgLp1 = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams((int)imgWidth,(int)rowHeight));
imgLp1.gravity = Gravity.CENTER;
viewHolderMag.magImgLeft.setLayoutParams(imgLp1);
viewHolderMag.magImgRight.setLayoutParams(imgLp1);
RelativeLayout.LayoutParams rlLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)descWidth,(int)rowHeight));
viewHolderMag.imagesLayout.setLayoutParams(rlLp);
ImageSizeUtils.defineTargetSizeForView(viewHolderMag.magImgLeft,(int) imgWidth,(int)rowHeight);
ImageSizeUtils.defineTargetSizeForView(viewHolderMag.magImgRight,(int) imgWidth,(int)rowHeight);
arg1.setTag(viewHolderMag);
}
else{
viewHolderMag = (MagazineViewHolder)arg1.getTag();
ImageSizeUtils.defineTargetSizeForView(viewHolderMag.magImgLeft,(int) imgWidth,(int)rowHeight);
ImageSizeUtils.defineTargetSizeForView(viewHolderMag.magImgRight,(int) imgWidth,(int)rowHeight);
}
String mImgUrlLeft = Utils.m_img_mag_base_url+mFeedViewData.getFileidn().split("-")[1]+".jpg";
String mImgUrlRight = Utils.m_img_mag_base_url+mFeedViewData.getFileidn().split("-")[2];
try{
ImageLoader.getInstance().displayImage(mImgUrlLeft, viewHolderMag.magImgLeft,
new MagazineImageListener(viewHolderMag.magImgLeft));
ImageLoader.getInstance().displayImage(mImgUrlRight, viewHolderMag.magImgRight,
new MagazineImageListener(viewHolderMag.magImgRight));
}
catch(Exception e){
return null;
}
viewHolderMag.imagesLayout.setOnClickListener(new ProdImageOnClickListener(mFeedViewData));
viewHolderMag.price.setTypeface(Utils.getFontForRupeeSymb(mCtx));
viewHolderMag.price.setText(Html.fromHtml( "` " + "</font>" + "<b>" + mFeedViewData.getPrice() + "</b>"));
//TODO: Remove once mag has price
viewHolderMag.price.setVisibility(View.GONE);
if(!mFeedViewData.getLikeCount().equals("0"))
viewHolderMag.likeCount.setText(" (" + mFeedViewData.getLikeCount() + ")");
if(!mFeedViewData.getShareCount().equals("0"))
viewHolderMag.shareCount.setText(" (" + mFeedViewData.getShareCount() + ")");
if(!mFeedViewData.getRevCount().equals("0"))
viewHolderMag.commentCount.setText(" (" + mFeedViewData.getRevCount() + ")");
if(mFeedViewData.getIsLoved())
viewHolderMag.likeActionLayout.setBackgroundColor(mCtx.getResources().getColor(R.color.auth_btn_color_normal));
else
viewHolderMag.likeActionLayout.setBackgroundResource(R.drawable.selector_pink_button);
viewHolderMag.shareActionLayout.setOnClickListener(new ShareClickListener(mFeedViewData.getMagImage()));
viewHolderMag.likeActionLayout.setOnClickListener(new LikeActionListener(mFeedViewData,viewHolderMag.likeActionLayout));
viewHolderMag.commentActionLayout.setOnClickListener(new OnCommentClickListener(mFeedViewData));
int minutes=0;
if(mFeedViewData.getTimestamp()!=""){
long timeDiff = System.currentTimeMillis() - Long.parseLong(mFeedViewData.getTimestamp());
minutes = (int)((int) (timeDiff/1000))/60;
}
if(mFeedViewData.getUsername().length()>0){
ImageLoader.getInstance().displayImage(mFeedViewData.getTnPic(), viewHolderMag.userImg,new UserImageListener(viewHolderMag.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getUsername() + "</b>" + " "+ mFeedViewData.getActivity()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getDoer()), 0, mFeedViewData.getUsername().length(), Spanned.SPAN_COMPOSING);
viewHolderMag.userActivity.setText(ss);
if(minutes!=0){
viewHolderMag.timeline.setText( minutes + " minutes ago");
}
viewHolderMag.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getReview()!=null){
ImageLoader.getInstance().displayImage(mFeedViewData.getReview().getTnUrl(), viewHolderMag.userImg,new UserImageListener(viewHolderMag.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getReview().getReviewerName() + "</b>" + " "+ mFeedViewData.getReview().getReview()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getReview().getId()), 0, mFeedViewData.getReview().getReviewerName().length(), Spanned.SPAN_COMPOSING);
viewHolderMag.userActivity.setText(ss);
if(minutes!=0){
viewHolderMag.timeline.setText( minutes + " minutes ago");
}
viewHolderMag.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getActivity().length()>0){
String activityText = Html.fromHtml("<b>" + "A user: "+ "</b>" + " "+ mFeedViewData.getActivity()).toString();
viewHolderMag.userActivity.setText(activityText);
if(minutes!=0){
viewHolderMag.timeline.setText( minutes + " minutes ago");
}
viewHolderMag.userImg.setImageResource(R.drawable.ic_blank_profile);
}
if(feedType == Utils.ADAPTER_FEED_TUTORIAL){
viewHolderMag.userActivity.setClickable(false);
viewHolderMag.imagesLayout.setClickable(false);
}
}
else if(getItemViewType(arg0) == Utils.SCRAP_OBJECT){
ObjectViewHolder viewHolderScrap = new ObjectViewHolder();
float imgWidth = width;
float rowHeight = (width)*Utils.SCRAPBOOK_ASPECT_RATIO;
if(arg1==null){
LayoutInflater inflater = ((Activity)mCtx).getLayoutInflater();
arg1 = inflater.inflate(R.layout.view_single_pane, arg2, false);
viewHolderScrap.row = arg1.findViewById(R.id.rowLayout);
viewHolderScrap.imagesLayout = (RelativeLayout)arg1.findViewById(R.id.layout_image);
viewHolderScrap.objImg = (ImageView)arg1.findViewById(R.id.img_object);
viewHolderScrap.price = (TextView)arg1.findViewById(R.id.text_price);
viewHolderScrap.likeActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_like);
viewHolderScrap.likeCount = (TextView)arg1.findViewById(R.id.text_like_count);
viewHolderScrap.shareActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_share);
viewHolderScrap.shareCount = (TextView)arg1.findViewById(R.id.text_share_count);
viewHolderScrap.commentActionLayout = (RelativeLayout)arg1.findViewById(R.id.layout_action_comment);
viewHolderScrap.commentCount = (TextView)arg1.findViewById(R.id.text_share_comment);
viewHolderScrap.activityLayout = (LinearLayout)arg1.findViewById(R.id.layout_activity);
viewHolderScrap.userImg = (ImageView)arg1.findViewById(R.id.img_user);
viewHolderScrap.userActivity = (TextView)arg1.findViewById(R.id.text_activity);
viewHolderScrap.timeline = (TextView)arg1.findViewById(R.id.text_timeline);
RelativeLayout.LayoutParams imgLp1 = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
viewHolderScrap.objImg.setLayoutParams(imgLp1);
RelativeLayout.LayoutParams rlLp = new RelativeLayout.LayoutParams(
new RelativeLayout.LayoutParams((int)imgWidth,(int)rowHeight));
viewHolderScrap.imagesLayout.setLayoutParams(rlLp);
ImageSizeUtils.defineTargetSizeForView(viewHolderScrap.objImg,(int) imgWidth,(int)rowHeight);
arg1.setTag(viewHolderScrap);
}
else{
viewHolderScrap = (ObjectViewHolder)arg1.getTag();
ImageSizeUtils.defineTargetSizeForView(viewHolderScrap.objImg,(int) imgWidth,(int)rowHeight);
}
String mNormalImgUrl = null;
mNormalImgUrl = Utils.m_img_scrap_base_url + mFeedViewData.getScrapId() + ".png";
try{
ImageLoader.getInstance().displayImage(mNormalImgUrl, viewHolderScrap.objImg,
new SingleImageListener(mFeedViewData,viewHolderScrap.objImg));
}
catch(Exception e){
return null;
}
viewHolderScrap.objImg.setOnClickListener(new ProdImageOnClickListener(mFeedViewData));
if(mFeedViewData.getIsLoved())
viewHolderScrap.likeActionLayout.setBackgroundColor(mCtx.getResources().getColor(R.color.auth_btn_color_normal));
else
viewHolderScrap.likeActionLayout.setBackgroundResource(R.drawable.selector_pink_button);
viewHolderScrap.likeActionLayout.setOnClickListener(new LikeActionListener(mFeedViewData,viewHolderScrap.likeActionLayout));
viewHolderScrap.shareActionLayout.setOnClickListener(new ShareClickListener(mNormalImgUrl));
viewHolderScrap.commentActionLayout.setOnClickListener(new OnCommentClickListener(mFeedViewData));
viewHolderScrap.price.setTypeface(Utils.getFontForRupeeSymb(mCtx));
viewHolderScrap.price.setText(Html.fromHtml( "` " + "</font>" + "<b>" + mFeedViewData.getPrice() + "</b>"));
//TODO:Remove once scrap has price
viewHolderScrap.price.setVisibility(View.GONE);
if(!mFeedViewData.getLikeCount().equals("0"))
viewHolderScrap.likeCount.setText(" (" + mFeedViewData.getLikeCount() + ")");
if(!mFeedViewData.getShareCount().equals("0"))
viewHolderScrap.shareCount.setText(" (" + mFeedViewData.getShareCount() + ")");
if(!mFeedViewData.getRevCount().equals("0"))
viewHolderScrap.commentCount.setText(" (" + mFeedViewData.getRevCount() + ")");
int minutes=0;
if(mFeedViewData.getTimestamp()!=""){
long timeDiff = System.currentTimeMillis() - Long.parseLong(mFeedViewData.getTimestamp());
minutes = (int)((int) (timeDiff/1000))/60;
}
if(mFeedViewData.getUsername().length()>0 && (!mFeedViewData.getActivity().equals("null")) && mFeedViewData.getActivity().length()>0){
ImageLoader.getInstance().displayImage(mFeedViewData.getTnPic(), viewHolderScrap.userImg,new UserImageListener(viewHolderScrap.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getUsername() + "</b>" + " "+ mFeedViewData.getActivity()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getDoer()), 0, mFeedViewData.getUsername().length(), Spanned.SPAN_COMPOSING);
viewHolderScrap.userActivity.setText(ss);
if(minutes!=0){
viewHolderScrap.timeline.setText( minutes + " minutes ago");
}
viewHolderScrap.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getReview()!=null){
ImageLoader.getInstance().displayImage(mFeedViewData.getReview().getTnUrl(), viewHolderScrap.userImg,new UserImageListener(viewHolderScrap.userImg));
String activityText = Html.fromHtml("<b>" + mFeedViewData.getReview().getReviewerName() + "</b>" + " "+ mFeedViewData.getReview().getReview()).toString();
SpannableString ss = new SpannableString(activityText);
ss.setSpan(new MyClickableSpan(activityText, mFeedViewData.getReview().getId()), 0, mFeedViewData.getReview().getReviewerName().length(), Spanned.SPAN_COMPOSING);
viewHolderScrap.userActivity.setText(ss);
if(minutes!=0){
viewHolderScrap.timeline.setText( minutes + " minutes ago");
}
viewHolderScrap.userActivity.setMovementMethod(LinkMovementMethod.getInstance());
}
else if(mFeedViewData.getActivity().length()>0){
String activityText = Html.fromHtml("<b>" + "A user: "+ "</b>" + " "+ mFeedViewData.getActivity()).toString();
viewHolderScrap.userActivity.setText(activityText);
if(minutes!=0){
viewHolderScrap.timeline.setText( minutes + " minutes ago");
}
viewHolderScrap.userImg.setImageResource(R.drawable.ic_blank_profile);
}
if(feedType == Utils.ADAPTER_FEED_TUTORIAL){
viewHolderScrap.userActivity.setClickable(false);
viewHolderScrap.objImg.setClickable(false);
}
}
return arg1;
}
Make sure you do not load or process any images in Adapter.getView() method. If you need to do so, do it in a separate AsyncTask. If you download images from Internet you should better use some helper libraries like Volley or Picasso
I use this library to load images in list view, I never had a problem:Android Image Loader

JSON remove special characters

I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

Categories

Resources