recyclerview is not updating - android

I am trying to update my RecyclerView as the number of elements in the data set changes
PlaceHolderFragment
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static final String HOME_ADAPTER = "HOME";
public static final String TRENDING_ADAPTER = "TREND";
public static int P_START = -1;
public static int P_END = -1;
public static int T_START = -1;
public static int T_END = -1;
List<Posts> mNewsFeeds = new ArrayList<>();
List<Posts> mTrending = new ArrayList<>();
List<ChatList> mChatList = new ArrayList<>();
List<Online> mOnline = new ArrayList<>();
HomeAdapter homeAdapter;
HomeAdapter TrendAdapter;
ChatListAdapter chatListAdapter;
OnlineListAdapter onlineAdapter;
RecyclerView recyclerViewT1;
RecyclerView recyclerViewT2;
RecyclerView recyclerViewT3;
RecyclerView recyclerViewT4;
private SwipeRefreshLayout swipeRefreshLayoutT1;
private SwipeRefreshLayout swipeRefreshLayoutT2;
private SwipeRefreshLayout swipeRefreshLayoutT3;
private SwipeRefreshLayout swipeRefreshLayoutT4;
private int visibleThreshold = 2;
private int PlastVisibleItem, PtotalItemCount;
private boolean Ploading;
private int TlastVisibleItem, TtotalItemCount;
private boolean Tloading;
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Bundle args = new Bundle(getArguments());
int TabID = args.getInt(ARG_SECTION_NUMBER);
if (TabID == 1) {
recyclerViewT1 = (RecyclerView) rootView.findViewById(R.id.rv_numbers);
swipeRefreshLayoutT1 = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerViewT1.setLayoutManager(layoutManager);
recyclerViewT1.setHasFixedSize(false);
try {
OnlineltPosts();
} catch (JSONException e) {
e.printStackTrace();
}
recyclerViewT1.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
PtotalItemCount = layoutManager.getItemCount();
PlastVisibleItem = layoutManager.findLastVisibleItemPosition();
if (!Ploading && PtotalItemCount <= (PlastVisibleItem + visibleThreshold)) {
Ploading = true;
OnlineltPosts();
Log.e("coool","yeeeeeeeeeeeeee");
}
}
});
} else if (TabID == 2) {
} else if (TabID == 3) {
} else {
}
return rootView;
}
.........
Onlineltpost
void OnlineltPosts() {
String url = ApiUtil.getltPostUrl(P_END);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
mNewsFeeds.add(postHelper(arr, i));
}
if (recyclerViewT1.getAdapter() == null) {
homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
recyclerViewT1.setAdapter(homeAdapter);
}else
homeAdapter.notifyDataSetChanged();
// getActivity().runOnUiThread(new Runnable() {
// public void run() {
// homeAdapter.notifyDataSetChanged();
// }
// });
// Log.e("coool", String.valueOf(mNewsFeeds.size()));
} catch (JSONException | MalformedURLException | URISyntaxException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestManager.getInstance(getContext()).addToRequestQueue(stringRequest);
}
postHelper
public static Posts postHelper(JSONArray arr, int i) throws JSONException, URISyntaxException, MalformedURLException {
JSONObject obj = new JSONObject(String.valueOf(arr.get(i)));
int id = obj.getInt("post_id");
// SharedPreferences pref = getContext().getSharedPreferences(Preferences.POST, 0);
// SharedPreferences.Editor editor = pref.edit();
//
// int start = pref.getInt(Preferences.POST_LATEST_START, -1);
// int end = pref.getInt(Preferences.POST_LATEST_END, -1);
//
// if (start == -1 || id > start)
// editor.putInt(Preferences.POST_LATEST_START, id);
//
// if (end == -1 || id < end)
// editor.putInt(Preferences.POST_LATEST_END, id);
//
// editor.putString(Preferences.POST_PREFEX + id, obj.toString());
//
// editor.apply();
if (P_START == -1 || id > P_START)
P_START = id;
if (P_END == -1 || id < P_END)
P_END = id;
int user_id = obj.getInt("user_id");
String user_name = (String) obj.get("user_name");
String pic = (String) obj.get("user_picture");
URI uri = new URI(pic);
URL user_picture = uri.toURL();
String post_text = (String) obj.get("post_text");
String post_time = (String) obj.get("post_time");
int likes = (int) obj.get("likes");
int dislikes = (int) obj.get("dislikes");
int comments = (int) obj.get("comments");
int isliked = (int) obj.get("isliked");
int isdisliked = (int) obj.get("isdisliked");
int iscommented = (int) obj.get("iscommented");
int isfollow = (int) obj.get("isfollow");
JSONObject abc = obj.getJSONArray("post_data").getJSONObject(0);
String post_image = (String) abc.get("source");
int type = abc.getInt("type");
if (type == 4) {
String youtube = "www.youtube.com/embed/";
int x = post_image.indexOf(youtube);
post_image = post_image.substring(x + youtube.length(), post_image.length());
int x1 = post_image.indexOf("?");
post_image = post_image.substring(0, x1);
post_image = "http://img.youtube.com/vi/" + post_image + "/0.jpg";
}
List<Like> postLikes = new ArrayList<>();
List<Comment> postComments = new ArrayList<>();
JSONArray likeList = obj.getJSONArray("like_all");
for (int j = 0; j < likeList.length(); j++) {
JSONObject obj1 = new JSONObject(String.valueOf(likeList.get(j)));
int Luser_id = obj1.getInt("user_id");
String Luser_name = obj1.getString("user_name");
String Lusername = obj1.getString("username");
String Lpic = obj1.getString("user_picture");
URI uri1 = new URI(Lpic);
URL Luser_picture = uri1.toURL();
Like mlike = new Like(Luser_id, Luser_name, Lusername, Luser_picture);
postLikes.add(mlike);
}
JSONArray CommentList = obj.getJSONArray("post_comment");
for (int j = 0; j < CommentList.length(); j++) {
JSONObject obj1 = new JSONObject(String.valueOf(CommentList.get(j)));
int Lpost_id = obj1.getInt("post_id");
int Lcomment_id = obj1.getInt("comment_id");
String Lusername = obj1.getString("username");
String Lcomment = obj1.getString("comment");
String Lcomment_time = obj1.getString("comment_time");
int Luser_id = obj1.getInt("user_id");
String Luser_name = obj1.getString("user_name");
String Lpic = obj1.getString("user_picture");
URI uri1 = new URI(Lpic);
URL Luser_picture = uri1.toURL();
Comment mlike = new
Comment(Lpost_id, Lcomment_id, Luser_id, Luser_name,
Lusername, Lcomment, Lcomment_time, Luser_picture);
postComments.add(mlike);
}
return new Posts(id, user_id, user_name, user_picture,
post_text, post_time, likes, dislikes, comments,
isliked, isdisliked, iscommented, isfollow, post_image, type,
postLikes, postComments);
}
I have tried recyclerViewT1.setHasFixedSize(false); but nothing is changing. The thing I noticed is that the data set is changing successfully but recyclerview is not showing new items.
when i try:
homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
recyclerViewT1.setAdapter(homeAdapter);
instead of:
homeAdapter.notifyDataSetChanged();
it shows correct number of items but then user is pushed back to top and user needs to scroll again, which I don't want. I just want to update the data set with the new items.

update the getItemCount & your datas before set notifyDataSetChanged
In your adapter:
private int mListSize;
public void setItemCount(int listsize){
mListSize=listsize;
}
#Override
public int getItemCount() {
return mListSize;
}
before notifydataset changed:
if (recyclerViewT1.getAdapter() == null) {
homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
recyclerViewT1.setAdapter(homeAdapter);
}else{
homeAdapter.setData(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
homeAdapter.setItemCount(yourlist.size());
homeAdapter.notifyDataSetChanged();
}
Try this answer also
https://stackoverflow.com/a/40220412/3879847

You should always provide new mNewsFeeds to HomeAdapter and call homeAdapter.notifyDataSetChanged(); to change data
try {
JSONArray arr = new JSONArray(trending);
for (int i = 0; i < arr.length(); i++) {
mNewsFeeds.add(postHelper(arr, i));
}
if (recyclerViewT1.getAdapter() == null) {
homeAdapter = new HomeAdapter(mNewsFeeds, mNewsFeeds.size() + 1, HOME_ADAPTER);
recyclerViewT1.setAdapter(homeAdapter);
}else {
homeAdapter.setNewsFeeds(mNewsFeeds)
}
homeAdapter.notifyDataSetChanged();
// getActivity().runOnUiThread(new Runnable() {
// public void run() {
// homeAdapter.notifyDataSetChanged();
// }
// });
// Log.e("coool", String.valueOf(mNewsFeeds.size()));
} catch (JSONException | MalformedURLException | URISyntaxException e) {
e.printStackTrace();
}

Related

Items not displaying orderwise in Recycler View

In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);

How do I use onResume and onPause method when I am pressed back button

I have a custom adapter for recyclerview using json webservices. I had to parse the url one by one and show cardview using onscrolllistener(). My question is when I pressed the back button and after I open in recent app (that time onResume called) it will show only which url called at the time of onPause called. So how can I refresh the listview when I call onResume.
Thanks in Advance,
Here my code synepet..
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private GridLayoutManager mGridManager;
private ProgressBar mProgressBar;
private static String url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList = new ArrayList<PlayListItem>();
private PlayListItem mContact;
private Bundle mbundle;
String name2 = "Arasu";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
new GetContacts().execute();
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
getScreenOrientation();
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Size2---->" + mContactList.size());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setMax(100);
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonArray = sh.makeServiceCall(url, ServiceHandler.GET);
//Log.d("Response: ", "> " + jsonArray);
if (jsonArray != null) {
try {
jsonObj = new JSONObject(jsonArray);
if (jsonObj.has("nextPageToken")) {
loading = true;
mNextToken = jsonObj.getString("nextPageToken");
} else {
loading = false;
}
// Getting JSON Array node
contacts = jsonObj.getJSONArray("items");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String title = c.getJSONObject("snippet").getString("title");
String time = c.getJSONObject("snippet").getString("publishedAt");
String playlist_id = c.get("id").toString();
// Find Screen size and set the Image for this size
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
int inch = (int) Math.round(screenInches);
String image = null;
try {
if (inch <= 4) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 4 && inch <= 6) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 6 && inch <= 10) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url");
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
mContact = new PlayListItem();
mContact.setmTitle(title);
mContact.setmID(playlist_id);
mContact.setmTime(time);
mContact.setmThumbnailURL(image);
mContact.setmNextToken(mNextToken);
mContactList.add(mContact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (mProgressBar.isShown())
mProgressBar.setVisibility(ProgressBar.GONE);
mAdapter.notifyDataSetChanged();
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mGridManager.getChildCount();
totalItemCount = mGridManager.getItemCount();
pastVisiblesItems = mGridManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
Log.v("...", "Last Item Wow !");
if (jsonObj.has("nextPageToken")) {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url--->" + url);
new GetContacts().execute();
} else {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url----else--->" + url);
new GetContacts().execute();
}
loading = false;
}
}
}
});
}
}
}
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private List<PlayListItem> mItems;
private Activity activity;
public ImageLoader imageLoader;
public CardAdapter(Activity activity, List<PlayListItem> items) {
this.activity = activity;
this.mItems = items;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_outer_playlist_cardview, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
System.out.println("Title Value is----------->"+mItems.get(0));
PlayListItem nature = mItems.get(i);
Log.d("Title Value is","----------->"+nature.getmTitle());
viewHolder.tvTitle.setText(nature.getmTitle());
final String playListID = nature.getmID();
final String thumnailsURL = nature.getmThumbnailURL();
final Calendar c = Calendar.getInstance();
int cur_year = c.get(Calendar.YEAR);
int cur_month = c.get(Calendar.MONTH) + 1;
int cur_day = c.get(Calendar.DAY_OF_MONTH);
int cur_hour = c.get(Calendar.HOUR_OF_DAY);
int cur_minute = c.get(Calendar.MINUTE);
// Getting updated date from url
String string = nature.getmTime();
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
String part3 = parts[2];
String[] part4 = part3.split("T");
String part5 = part4[0];
String part6 = part4[1];
// Toast.makeText(activity, "Given Date is : " + part1 + "/" + part2 + "/" + part3, Toast.LENGTH_LONG).show();
// Log.d("Updated Current Day", part5);
int giv_yr = Integer.parseInt(part1);
int giv_mnt = Integer.parseInt(part2);
int giv_day = Integer.parseInt(part5);
// Difference Two dates
int day_yr = 0, day_mnt = 0, day_day = 0;
if (cur_year >= giv_yr) {
if (cur_year >= giv_yr) {
day_yr = cur_year - giv_yr;
} else {
day_yr = giv_yr - cur_year;
}
if (cur_month >= giv_mnt) {
day_mnt = cur_month - giv_mnt;
} else {
day_mnt = giv_mnt - cur_month;
}
if (cur_day >= giv_day) {
day_day = cur_day - giv_day;
} else {
day_day = giv_day - cur_day;
}
}
String yr = Integer.toString(day_yr);
String mnt = Integer.toString(day_mnt);
String days = Integer.toString(day_day);
if (day_day == 0)
viewHolder.tvTime.setText("Updated Today");
else if (day_day < 7)
viewHolder.tvTime.setText("Updated " + days + " Days ago");
else if (day_day < 30) {
int week = day_day / 7;
String Week = Integer.toString(week);
viewHolder.tvTime.setText("Updated " + Week + " Weeks ago");
} else {
viewHolder.tvTime.setText("Updated " + mnt + " Months ago");
}
//imageLoader.DisplayImage(nature.getmThumbnailURL(), viewHolder.imgThumbnail);
Picasso.with(activity)
.load(nature.getmThumbnailURL())
/*.placeholder(R.drawable.my_thumnail)*/
.into(viewHolder.imgThumbnail);
viewHolder.item_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, VideoPlayActivity.class);
intent.putExtra("PLAYLIST_ID", playListID);
intent.putExtra("THUMNAIL_URL", thumnailsURL);
v.getContext().startActivity(intent);
}
});
/*System.out.println("URL -------------->"+nature.getmThumbnailURL());
// String img_url = nature.getmThumbnailURL();
try {
URL url = new URL(nature.getmThumbnailURL());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
System.out.println("Image bmp -------------->"+bmp);
//imageView.setImageBitmap(bmp);
viewHolder.imgThumbnail.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgThumbnail;
public TextView tvTitle;
public TextView tvID;
public TextView tvTime;
public View item_view;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
//tvID = (TextView) itemView.findViewById(R.id.tv_id);
tvTime = (TextView) itemView.findViewById(R.id.tv_time);
item_view = itemView;
}
}
}
I made a small mistake declaring String URL as static but it should be final also assign to another String variable. Finally set the adapter and notifyDataSetChanged where placed in onStart().
private final static String URL = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
private String url = URL;
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList;
private PlayListItem mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
if (mContactList == null)
mContactList = new ArrayList<PlayListItem>();
System.out.println("onCreate :: Size2---->" + mContactList.size());
}
#Override
protected void onStart() {
super.onStart();
if (mContactList != null)
mContactList.clear();
url = URL;
new GetContacts().execute();
if (mAdapter == null)
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
getScreenOrientation();
System.out.println("onStart :: Size2---->" + mContactList.size());
}
#Override
protected void onResume() {
ActivitySwitcher.animationIn(findViewById(R.id.container_first),
getWindowManager());
super.onResume();
System.out.println("onResume :: Size2---->" + mContactList.size());
mAdapter.notifyDataSetChanged();
}

email extractor android program crashes aide

public class MainActivity extends Activity {
public static LinearLayout layout = null;
public static EditText urlstring = null;
public static Button submit = null;
public static ListView emailsfound = null;
public static ArrayList<String> emaillist = new ArrayList<String>();
public static ArrayList<String> urllist = new ArrayList<String>();
public static ArrayAdapter<String> adapter = null;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
urlstring = new EditText(this);
submit = new Button(this);
submit.setText("Submit");
emailsfound = new ListView(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(urlstring);
layout.addView(submit);
layout.addView(emailsfound);
setContentView(layout);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, emaillist);
emailsfound.setAdapter(adapter);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urllist.add(urlstring.getText().toString());
int i = 0;
while (true) {
String page = getPage(urlstring.getText().toString());
ArrayList<String> urls = new ArrayList<String>();
urls = getURLs(page);
ArrayList<String> addresses = new ArrayList<String>();
addresses = getAddresses(page);
for (int a = 0; i < urls.size(); i++) {
urllist.add(urls.get(a));
}
for (int a = 0; a < addresses.size(); i++) {
emaillist.add(addresses.get(a));
}
removeDuplicates(urllist);
removeDuplicates(emaillist);
adapter.notifyDataSetChanged();
i++;
urlstring.setText(urllist.get(i).toString());
}
}
;
});
}
public String getPage(String url) {
if (url.toLowerCase().startsWith("http") == false) {
url = "http://" + url;
}
URL fromstring = null;
URLConnection openConnection = null;
try {
fromstring = new URL(url);
openConnection = fromstring.openConnection();
BufferedReader in = null;
url = "";
in = new BufferedReader(new InputStreamReader(openConnection.getInputStream()));
String input = "";
if (in != null) {
while ((input = in.readLine()) != null) {
url = url + input + "\r\n";
}
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return url;
}
public ArrayList<String> getURLs(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.toLowerCase().contains("<a href=\"http")) {
int i = page.toLowerCase().indexOf("href=\"http") + "href=\"".length();
if (i > -1) {
String s1 = page.substring(i, page.toLowerCase().indexOf("\"", i));
s.add(s1);
page = page.substring(i + "http".length());
}
}
return s;
}
public boolean validate(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*" + "#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
public ArrayList<String> getAddresses(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.contains("#")) {
int i = page.indexOf("#");
if (i > -1) {
int beginning = page.lastIndexOf(" ", i);
if (beginning > -1) {
int ending = page.indexOf(" ", i);
if (ending > -1) {
String address = page.substring(beginning + 1, ending - 1);
address = address.toLowerCase();
if (address.startsWith("href=\"mailto:")) {
int b = address.indexOf(":") + 1;
address = address.substring(b);
int e = address.indexOf("\"");
if (e > -1) {
if (e > address.indexOf("#")) {
address = address.substring(0, address.indexOf("\""));
}
if (address.contains("?")) {
address = address.substring(0, address.indexOf("?"));
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
} else {
int b2 = address.indexOf(">") + 1;
if (b2 > -1) {
if (b2 < address.indexOf("#")) {
address = address.substring(b2);
}
}
int e2 = address.indexOf("<");
if (e2 > -1) {
if (e2 > address.indexOf("#")) {
address = address.substring(0, e2);
}
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
}
}
}
}
}
page = page.substring(i + 1);
}
return s;
}
public ArrayList<String> removeDuplicates(ArrayList<String> List) {
ArrayList<String> output = new ArrayList<String>();
for (int i = 0; i < List.size(); i++) {
boolean b = false;
for (int a = 0; a < List.size(); i++) {
if (List.get(i).toString().toLowerCase().equals(List.get(a).toString().toLowerCase())) {
b = true;
}
}
if (b == false) {
output.add(List.get(i));
}
}
return output;
}
}
This Program Was Made in AIDE on an android netbook.
It Crashes On Button Click. I was wondering what I Was doing wrong.
I tried before with runnables but it crashed then too. I'm new to
android development but I am fluent in Java. I noticed there are
alot of differences between android and Java.

Get the value of clicked Item of a custom listview?

I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}

Missing data in Section list view in Android?

I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}

Categories

Resources