i use RecyclerViewAdapter for my json adaper.i make some radiobutton and check box and edittext in RecyclerViewAdapter programically but when i check some radio button or type in edittext and scroll more than 1 screen when i come back all my fill content are removed;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
public MyRecyclerViewAdapter(Context context, ArrayList<HashMap<String, Object>> hash_all) {
}
#Override
public int getItemCount() {
return hash_all.size();
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
hash_all.size();
hash_get = hash_all.get(position);
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.MATCH_PARENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, 0);
String s = hash_get.get("ModelShowOption").toString();
String toggle = "";
String direc = "";
String type = "";
String model = "";
String rows = "";
String resize = "";
String[] split = s.split("\\|");
String[] split2 = new String[0];
for (int i = 0; i < split.length; i++) {
String s2 = split[i];
split2 = s2.split(":");
if (split2[0].equals("isToggleButton")){
toggle=split2[1];
}else if (split2[0].equals("type")){
type=split2[1];
}else if (split2[0].equals("direction")){
direc=split2[1];
}else if (split2[0].equals("model")){
model=split2[1];
}else if (split2[0].equals("rows")){
rows=split2[1];
}else if (split2[0].equals("resize")){
resize=split2[1];
}
}
String title = hash_get.get("title").toString();
String myValue =hash_get.get("MyValue").toString();
String[] splitValue = myValue.split("\\|");
RadioGroup[] rg;
RadioButton[] rb;
if (toggle.equals("true") && holder.row_list_title.getText().equals("")){
holder.row_list_placeholder.setVisibility(View.GONE);
holder.row_list_buttn.setVisibility(View.GONE);
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
if (splitMultiValue[1].equals("1")){
int p = 0;
rg = new RadioGroup[1];
rb = new RadioButton[splitValue.length];
rg[0] = new RadioGroup(holder.row_list_placeholder.getContext());
rg[0].setOrientation(RadioGroup.VERTICAL);
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
rb[j] = new RadioButton(getApplicationContext());
rg[p].addView(rb[j]);
rb[j].setId(j);
rb[j].setText(splitValue2[0]);
}
holder.linearLayoutCheckBox.addView(rg[p]);
p++;
holder.row_list_title.setText(title);
if (rg[0].getCheckedRadioButtonId() == -1) {
} else {
for (int r = 0; r < splitValue.length; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
}
}
}
}else{
holder.row_list_title.setText(title);
CheckBox[] ch;
final int[] checkd = {0};
List<String> checkvl = new ArrayList<>();
ch = new CheckBox[splitValue.length];
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
ch[j] = new CheckBox(getApplicationContext());
holder.linearLayoutCheckBox.addView(ch[j]);
ch[j].setId(j);
ch[j].setText(splitValue2[0]);
}
for (int r = 0; r < splitValue.length; r++) {
int finalR = r;
int finalR1 = r;
ch[r].setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
if (checkd[0] < Integer.parseInt(splitMultiValue[1])){
//checkvl.add(ch[finalR1].getText().toString());
//hash_all_string.get(position).remove("value");
//hash_all_string.get(position).put("value", String.valueOf(checkvl));
//CheckBox id = findViewById(ch[finalR].getId());
//String CheckBoxText = id.getText().toString();
//Log.e("CheckBoxString", CheckBoxText);
checkd[0] = checkd[0] +1;
}else{
ch[finalR].setChecked(false);
}
} else {
ch[finalR].setChecked(false);
checkd[0] = checkd[0] -1;
//checkvl.remove(ch[finalR1].getText().toString());
//hash_all_string.get(position).remove("value");
//hash_all_string.get(position).put("value", String.valueOf(checkvl));
}
});
}
}
}else{
if (myValue.equals("NULL")){
holder.row_list_title.setText(title);
holder.row_list_placeholder.setVisibility(View.VISIBLE);
holder.row_list_buttn.setVisibility(View.GONE);
holder.row_list_placeholder.setHint(hash_get.get("placeholder").toString());
if (type.equals("Text")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_TEXT);
}else if(type.equals("Int")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER);
}else if(type.equals("Float")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}else {
holder.row_list_placeholder.setVisibility(View.GONE);
holder.row_list_buttn.setVisibility(View.VISIBLE);
holder.row_list_title.setText(title);
int selct = 0;
for (int j = 0; j < hash_all2.size(); j++) {
if (hash_all2.get(j).get("selected").equals("true")) {
selct = selct+1;
}
}
if (selct>0){
holder.row_list_buttn.setBackgroundColor(getResources().getColor(R.color.purple_500));
holder.row_list_buttn.setText("انتخاب شد");
}else{
holder.row_list_buttn.setText("انتخاب کنید");
holder.row_list_buttn.setBackgroundColor(getResources().getColor(R.color.teal_200));
}
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
holder.row_list_buttn.setOnClickListener(v -> {
if (hash_all2.size() == 0) {
for (int j = 0; j < splitValue.length; j++) {
HashMap<String, String> hash_add2 = new HashMap<>();
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
hash_add2.put("Id", String.valueOf(j));
hash_add2.put("name", String.valueOf(splitValue2[0]));
hash_add2.put("value", String.valueOf(splitValue2[1]));
hash_add2.put("selected", "false");
hash_add2.put("max", splitMultiValue[1]);
hash_all2.add(hash_add2);
}
adapt.notifyDataSetChanged();
}
alertDialogSelect(position);
});
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row_form, parent, false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_list_title;
EditText row_list_placeholder;
LinearLayout linearLayoutCheckBox;
Button row_list_buttn;
ViewHolder(View itemView) {
super(itemView);
row_list_title = itemView.findViewById(R.id.row_list_title);
row_list_placeholder = itemView.findViewById(R.id.row_list_placeholder);
linearLayoutCheckBox = itemView.findViewById(R.id.mainrow);
row_list_buttn = itemView.findViewById(R.id.row_list_buttn);
}
}
}
please help.i tryed many code from stack but not working
holder.setIsRecyclable(false);
setHasStableIds(true);
this is not working for me
In RecyclerView when scrolling state of view removed and creating new view by scroll,
you must change your data when radioButton or edittext content changed, and set new data in your model.
Related
I know it is common problem with Listview and Checkbox, I am try from 2 days but it is not solving, so I raised question here.
I had list of items in Arraylist, like 15(supposed) items. Inside listview there is a checkbox, by default 11(supposed) checkbox is comes checked by API (JSON Response)
But I have to show only 5 items checked. I tried alot but not find any solution.
I had create a dummy list that contain 11 items that comes from API and save 5 items from original arraylist. Here is code to match items in listview and save this list in Shared Preference.
Adapter class inside getViwe() function
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String idget = getIds.get(i).getOrderId();// it get ids from save list
for (int j = 0; j < newOrders.size(); j++) {
String bot = newOrders.get(j).getId(); // id from orginal list
if (bot.equalsIgnoreCase(idget)) {
showErrorLog(TAG, String.format("Bot id is %s and Saved Id is %s", bot, idget));
myViewHolder.add_payment.setChecked(true);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
myViewHolder.txt_check_status.setText("ADDED");
} else {
getPerspective().showErrorLog(TAG, "Not Equal");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
}
}
Adapter class code is here
public class NewOrderAdapter extends BaseAdapter {
private String TAG = "Current Order";
private Context context;
private List<NewOrder> newOrders;
private MyOrders myOrders;
private Perspective perspective;
private double total = 0.0;
private PrefManager prefManager;
// private List<SaveOrderId> ids;
private boolean isAdded = false;
private List<SaveOrderId> papa = new ArrayList<>();
private LayoutInflater inflater;
public NewOrderAdapter(Context context, List<NewOrder> newOrders, MyOrders myOrders) {
this.context = context;
this.newOrders = newOrders;
this.myOrders = myOrders;
prefManager = new PrefManager(this.context);
total = myOrders.total;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ids = new ArrayList<>();
}
private void showDeleteAlert(final String orderId) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle("Alert");
builder1.setMessage(context.getString(R.string.delete_order));
builder1.setCancelable(false);
builder1.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
myOrders.cancelOrder(orderId);
}
});
builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public int getCount() {
return newOrders.size();
}
#Override
public Object getItem(int position) {
return newOrders.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder myViewHolder;
if (convertView == null) {
myViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_new_order_row, parent, false);
myViewHolder.img_delete = (ImageView) convertView.findViewById(R.id.img_delete);
myViewHolder.add_payment = (CheckBox) convertView.findViewById(R.id.add_payment);
myViewHolder.txt_topic_name = (TextView) convertView.findViewById(R.id.txt_topic_name);
myViewHolder.txt_order_id = (TextView) convertView.findViewById(R.id.txt_order_id);
myViewHolder.txt_delivery_date = (TextView) convertView.findViewById(R.id.txt_delivery_date);
myViewHolder.txt_words = (TextView) convertView.findViewById(R.id.txt_words);
myViewHolder.txt_order_status = (TextView) convertView.findViewById(R.id.txt_order_status);
myViewHolder.txt_offer_price = (TextView) convertView.findViewById(R.id.txt_offer_price);
myViewHolder.txt_price_tag = (TextView) convertView.findViewById(R.id.txt_price_tag);
myViewHolder.txt_check_status = (TextView) convertView.findViewById(R.id.txt_check_status);
myViewHolder.txt_total_amount = (TextView) convertView.findViewById(R.id.txt_total_amount);
myViewHolder.txt_payment_status = (TextView) convertView.findViewById(R.id.txt_payment_status);
myViewHolder.txt_paid_amount = (TextView) convertView.findViewById(R.id.txt_paid_amount);
myViewHolder.txt_view_more = (TextView) convertView.findViewById(R.id.txt_view_more);
myViewHolder.txt_order_tag = (TextView) convertView.findViewById(R.id.txt_order_tag);
myViewHolder.txt_layout_checked = (RelativeLayout) convertView.findViewById(R.id.txt_layout_checked);
myViewHolder.layout_payment_details = (RelativeLayout) convertView.findViewById(R.id.layout_payment_details);
myViewHolder.layout_paid = (LinearLayout) convertView.findViewById(R.id.layout_paid);
convertView.setTag(myViewHolder);
} else {
myViewHolder = (ViewHolder) convertView.getTag();
}
try {
myViewHolder.txt_topic_name.setText(newOrders.get(position).getTopic());
if (newOrders.get(position).getOrder_code().equalsIgnoreCase("Not allotted")
|| newOrders.get(position).getOrder_code().equalsIgnoreCase("")) {
myViewHolder.txt_order_tag.setText(context.getString(R.string.temp_id));
myViewHolder.txt_order_id.setText(newOrders.get(position).getId());
} else {
myViewHolder.txt_order_tag.setText(context.getText(R.string.order_code_));
myViewHolder.txt_order_id.setText(newOrders.get(position).getOrder_code());
}
myViewHolder.txt_words.setText(String.format("%s Words", newOrders.get(position).getWords()));
myViewHolder.txt_order_status.setText(newOrders.get(position).getProject_status());
myViewHolder.txt_offer_price.setText(String.format("%s %s %s", newOrders.get(position).getPrice_label(), newOrders.get(position).getSymbol(), newOrders.get(position).getDue()));
myViewHolder.txt_price_tag.setText(newOrders.get(position).getPayment_label());
myViewHolder.txt_total_amount.setText(String.format("%s %s", newOrders.get(position).getSymbol(), newOrders.get(position).getCost()));
String projectStatus = newOrders.get(position).getProject_status();
if (projectStatus.equalsIgnoreCase("in process")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (projectStatus.equalsIgnoreCase("delivered")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.green_text));
} else if (projectStatus.equalsIgnoreCase("pending")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.red));
} else if (projectStatus.equalsIgnoreCase("feedback")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.feedback));
} else if (projectStatus.equalsIgnoreCase("checked")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.checked));
} else if (projectStatus.equalsIgnoreCase("ready")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.ready));
} else if (projectStatus.equalsIgnoreCase("delivered draft")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.delivered_draft));
} else if (projectStatus.equalsIgnoreCase("Payment Refund")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.payment_refund));
} else if (projectStatus.equalsIgnoreCase("Not Accepted")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.black));
}
String payStatus = newOrders.get(position).getPay_status();
if (payStatus.equalsIgnoreCase("Pending")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.red));
}
if (payStatus.equalsIgnoreCase("Partially paid")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.orange));
}
if (payStatus.equalsIgnoreCase("Complete")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.green_text));
}
double paidAmt = newOrders.get(position).getPaid();
if (paidAmt == 0) {
myViewHolder.layout_paid.setVisibility(View.GONE);
} else {
myViewHolder.layout_paid.setVisibility(View.VISIBLE);
myViewHolder.txt_paid_amount.setText(String.format("%s %s", newOrders.get(position).getSymbol(), newOrders.get(position).getPaid()));
}
final String gateway_name = newOrders.get(position).getPayment_gateway_name();
myViewHolder.add_payment.setEnabled(false);
if (gateway_name.equalsIgnoreCase(prefManager.getCurrencyGateway())) {
if (!newOrders.get(position).getPay_status().equalsIgnoreCase("Complete")) {
double dueAmt = newOrders.get(position).getDue();
myViewHolder.layout_payment_details.setVisibility(View.VISIBLE);
if (dueAmt != 0) {
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String idget = getIds.get(i).getOrderId();
for (int j = 0; j < newOrders.size(); j++) {
String bhoot = newOrders.get(j).getId();
if (bhoot.equalsIgnoreCase(idget)) {
showErrorLog(TAG, String.format("Bhoot id is %s and Saved Id is %s", bhoot, idget));
myViewHolder.add_payment.setChecked(true);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
myViewHolder.txt_check_status.setText("ADDED");
} else {
showErrorLog(TAG, "Not Equal");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
}
}
}
} else {
myViewHolder.layout_payment_details.setVisibility(View.GONE);
}
} else {
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
// prefManager.saveNewOrders(context, ids);
myViewHolder.txt_layout_checked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// myViewHolder.add_payment.performClick();
double dueAmt = newOrders.get(position).getDue();
if (dueAmt == 0.00) {
showErrorLog("Adapter", "No Order");
myViewHolder.add_payment.setChecked(false);
showAlert(context.getString(R.string.alert_header_warning), context.getString(R.string.alert_3_msg), "Ok");
} else {
if (!myViewHolder.add_payment.isChecked()) {
int size = prefManager.getNewOrders(context).size();
if (size < 6) {
String dis = newOrders.get(position).getId().concat(newOrders.get(position).getTopic());
if (size == 0) {
String orderid = newOrders.get(position).getId();
String payName = newOrders.get(position).getPayment_gateway_name();
SaveOrderId saveOrderId = new SaveOrderId(orderid, payName);
papa.add(saveOrderId);
prefManager.saveNewOrders(context, papa);
myViewHolder.add_payment.setChecked(true);
myViewHolder.txt_check_status.setText("ADDED");
String sym = newOrders.get(position).getSymbol();
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
total = total + newOrders.get(position).getDue();
myOrders.setPrice(sym, total, payName, dis);
} else {
String orderid = newOrders.get(position).getId();
String payName = newOrders.get(position).getPayment_gateway_name();
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String name = getIds.get(i).getGateWayName();
if (name.equalsIgnoreCase(payName)) {
isAdded = true;
break;
} else {
isAdded = false;
}
}
if (isAdded) {
myViewHolder.txt_check_status.setText("ADDED");
String sym = newOrders.get(position).getSymbol();
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
total = total + newOrders.get(position).getDue();
myOrders.setPrice(sym, total, payName, dis);
myViewHolder.add_payment.setChecked(true);
SaveOrderId saveOrderId = new SaveOrderId(orderid, payName);
papa.add(saveOrderId);
prefManager.saveNewOrders(context, papa);
} else {
showAlert(context.getString(R.string.alert_header_notic), context.getString(R.string.alert_1_msg), "Ok");
myViewHolder.add_payment.setChecked(false);
}
}
} else {
showMessage("Maximum limit reached.");
}
} else {
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
String name = newOrders.get(position).getPayment_gateway_name();
String dis = newOrders.get(position).getId().concat(newOrders.get(position).getTopic());
if (getIds.size() != 0) {
for (int i = 0; i < getIds.size(); i++) {
String abc = getIds.get(i).getGateWayName();
if (abc.equalsIgnoreCase(name)) {
getIds.remove(i);
prefManager.saveNewOrders(context, getIds);
break;
}
}
}
if (prefManager.getNewOrders(context).size() == 0) {
papa.clear();
prefManager.clearOrderIds(context);
}
String sym = newOrders.get(position).getSymbol();
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
total = total - newOrders.get(position).getDue();
myOrders.setPrice(sym, total, name, dis);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
class ViewHolder {
TextView txt_topic_name, txt_order_id, txt_delivery_date, txt_words, txt_order_status, txt_offer_price, txt_price_tag, txt_check_status,
txt_total_amount, txt_payment_status, txt_paid_amount, txt_view_more, txt_order_tag;
CheckBox add_payment;
ImageView img_delete;
RelativeLayout txt_layout_checked, layout_payment_details;
LinearLayout layout_paid;
}
}
Problem is that, all 11 items showing checked. Please help.
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();
}
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);
I am creating here a dynamic layout. I have one parent layout in which I am adding all the dynamic created views. Now on click of particular view I need position.
According to that position I have to send JsonObject which contain this view in Android. Here I am not able to get exact position of view.
This is my code:
int len = result.length();
View addView;
if (!(len == 0)) {
finalResult.clear();
for (int i = 0; i <= len; i++) {
try {
finalResult.add(result.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
if (i == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
image = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurl1 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl1, image,
Common.optionsSmall);
textview.setText(category1);
} else if (i % 5 == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
images = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurlss = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurlss, images,
Common.optionsSmall);
textview.setText(category1);
} else {
addView = mInflater.inflate(R.layout.sightseeing_secondview, null);
iv = (ImageView) addView.findViewById(R.id.secondimagesightseeing_second);
tv = (TextView) addView.findViewById(R.id.textView2);
llsecond = (LinearLayout) addView.findViewById(R.id.llsecondview);
String category2 = finalResult.get(i).getString("CategoryName");
imageurl2 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl2, iv,
Common.optionsSmall);
tv.setText(category2);
if (result.length() > i + 1) {
i++;
ivview = (ImageView) addView.findViewById(R.id.secondimagesightseeing_third);
text = (TextView) addView.findViewById(R.id.textView3);
llthird = (LinearLayout) addView.findViewById(R.id.llthirdview);
String category3 = finalResult.get(i).getString("CategoryName");
imageurl3 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl3, ivview,
Common.optionsSmall);
text.setText(category3);
}
llayout.addView(addView);
}
position = llayout.indexOfChild(addView);
addView.setTag(position);
addView.setOnClickListener(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
position = (Integer) v.getTag();
Toast.makeText(SightseeingToursActivity.this, "Position" + position, Toast.LENGTH_SHORT).show();
try {
Intent in = new Intent(SightseeingToursActivity.this, sightseeing_list.class);
in.putExtra("TourList", result.getJSONObject(position).toString());
startActivity(in);
} catch (Exception e) {
}
}
ViewGroup parent;
int position;
for(int i = 0; i < parent.getChildCount(); ++i) {
int currentViewId = parent.getChildAt(i).getId();
if(currentViewId == wantendViewId) {
position = i;
}
}
try this
public void clickresult(View v){
String temp = "";
int cards[] = {etnumber1.getText().toString(),etnumber2.getText().toString(),
etnumber3.getText().toString(),etnumber4.getText().toString()
,etnumber4.getText().toString()};
int noOfCard = cards.length;
for (int marker = 1; marker < noOfCard; marker++) {
for (int j = 0; j < marker; j++) {
if (cards[marker] < cards[j]) {
int tmp = cards[marker];
cards[marker] = cards[j];
cards[j] = tmp;
}
}
}
for (int i = 0; i < noOfCard; i++) {
temp += cards[i] + " ";
}
Toast.makeText(this, temp, Toast.LENGTH_LONG).show();
}
it still have one error -> type missmatch : cannot convert from string to int
how to fix that
int cards[] = {etnumber1.getText().toString(),etnumber2.getText().toString(),
etnumber3.getText().toString(),etnumber4.getText().toString()
,etnumber4.getText().toString()};
#Override
protected void onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_fragment_layout, container, false);
etnumber1 = (EditText)findViewById(R.id.etnumber1);
etnumber2 = (EditText)findViewById(R.id.etnumber2);
etnumber3 = (EditText)findViewById(R.id.etnumber3);
etnumber4 = (EditText)findViewById(R.id.etnumber4);
etnumber5 = (EditText)findViewById(R.id.etnumber5);
}
public void onClickResult(){
String cards[] = {etnumber1.getText().toString,
etnumber2.getText().toString(),
etnumber3.getText().toString(),
etnumber4.getText().toString(),
etnumber5.getText().toString()
};
int noOfCard = cards.length;
Arrays.sort(cards);
StringBuilder builder = new StringBuilder();
for (String s : cards)
builder.append(s).append(" ");
Toast.makeText(context, builder.toString(), Toast.LENGTH_SHORT).show();
}
This will sort your array and display it in a Toast in this format: "2 3 5 6 7" (according to the numbers you provided). If the EditTexts are going to have only numbers, consider using NumberPicker instead.
LENGTH_SHORT can also be LENGTH_LONG.
public class MainActivity extends Activity {
EditText number1,number2,number3,number4,number5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText)findViewById(R.id.etnumber1);
number2 = (EditText)findViewById(R.id.etnumber2);
number3 = (EditText)findViewById(R.id.etnumber3);
number4 = (EditText)findViewById(R.id.etnumber4);
number5 = (EditText)findViewById(R.id.etnumber5);
}
public void clickresult(){
int cards[] = {6,7,3,2,5};
int noOfCard = cards.length;
for (int marker = 1; marker < noOfCard; marker++) {
for (int j = 0; j < marker; j++) {
if (cards[marker] < cards[j]) {
int tmp = cards[marker];
cards[marker] = cards[j];
cards[j] = tmp;
}
}
}
for (int i = 0; i < noOfCard; i++) {
System.out.print(cards[i] + " ");
}
System.out.println();
}