Conditional Spinner - java

I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userEcts = (EditText) findViewById(R.id.ects_input);
summary = (TextView) findViewById(R.id.text_summary);
courses = (Spinner) findViewById(R.id.course_spinner);
calculateBtn = (Button) findViewById(R.id.calculate);
calculateBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calculate method.
calculate();
}
});
final String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(0)) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(1)) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(2)) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(3)) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
public void calculate() {
//gets entered text from the EditText,and convert to integers.
if (!TextUtils.isEmpty(userEcts.getText().toString())) {
Double ects = Double.parseDouble(userEcts.getText().toString());
//do the calculation
Double calculatedPrice = ects * price;
//set the value to the TextView, to display on screen.
summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
} else {
Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
calculate();
}
}
So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?

Use the position number to check the condition.
String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(courseArray[0])) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(courseArray[1])) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(courseArray[2])) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(courseArray[3])) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}

Use a switch statment :
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
switch(pos){
case 0:
ectsPrice.setText("200");
price = 200;
break;
case 1:
ectsPrice.setText("250");
price = 250;
break;
case 2:
ectsPrice.setText("300");
price = 300;
break;
case 3:
ectsPrice.setText("350");
price = 350;
break;
}
}

Related

radioGroup.setOnCheckedChangeListener isn't working properly

i have a problem with radioGroup.setOnCheckedChangeListener and i dont know to fix it
I have a fragment that is used to gather data and create a new instance of payment class.
the problem that i am facing is when i try to reselect the teacher after choosing how many hours have been teached the total doesnt get updated, i know that the code responsible for updating the total is tied to the spinner but i tried to create an independent "setOnCheckedChangeListener" on the radio group but it still fails to update the total.
here is a screenshot of the UI so u can better understand what am talking about
here is the code for java class responsible for this part :
public class addPaymentFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
private RadioGroup radioGroup;
private RadioButton radioButton;
private SchoolViewModel schoolViewModel;
private NumberPicker numberPicker;
private Button addPayment;
private Subject dummySubject, subject;
private Dialog dialog;
private RadioGroup radioGroup0;
private TextView datePickerTV, totalPaymentTV;
private String date;
private int hoursTeached, teacherFee;
private Payment payment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = hoursTeached*teacherFee;
payment = new Payment(crossRef,date,totalPayment);
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}
Sorry if my question is so clear and please let me know if i need to provide any more information and thanks!

Product Subtract Button is not working perfectly in ecommerce app

I am facing issue while subtracting my product, I am using three buttons to get the value of the selected one and then multiply these value for add more product or subtract . But when i click on subtract button it will minus the whole amount. So please help me in this. Below mention is my code. If you want some more info then please ask me.
public class ShowDetailActivity extends AppCompatActivity {
private TextView addToCardBtn;
private TextView titleTxt, feeTxt, descriptionTxt, numberOrderTxt;
private ImageView plusBtn, minusBtn, picFood, priceBtn, mediumPriceBtn, largePriceBtn;
private ProductsDomain object;
private int numberOrder = 1;
private ManagementCart managementCart;
private LinearLayout cheese_ll;
private LinearLayout scale_ll;
private int itemPrice;
private CheckBox cheeseBoxyes;
private int price;
private int checkvalue;
private int uncheckValue;
private boolean cheeseBoolean = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_detail);
managementCart = new ManagementCart(this);
initView();
getBundle();
//Button Code
price=object.getPrice();
priceBtn.setOnClickListener(this::onClick);
mediumPriceBtn.setOnClickListener(this::onClick);
largePriceBtn.setOnClickListener(this::onClick);
//check box code for extra cheese
}
private void onClick(View view) {
int id=view.getId();
switch (id){
case R.id.smallPriceBtn:
price=object.getPrice();
itemPrice=object.getPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
break;
case R.id.mediumPriceBtn:
price = object.getMediumPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getMediumPrice();
break;
case R.id.largePriceBtn:
price = object.getLargePrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getLargePrice();
break;
}
}
private void getBundle() {
object = (ProductsDomain) getIntent().getSerializableExtra("object");
if (object.getWithCheese() == 1)//get cheese
{
cheese_ll.setVisibility(View.VISIBLE);
scale_ll.setVisibility(View.GONE);
} else {
cheese_ll.setVisibility(View.GONE);
scale_ll.setVisibility(View.VISIBLE);
}
Glide.with(this).load("http://192.168.100.215/pizzaVill/Images/" + object.getImage()).into(picFood);
titleTxt.setText(object.getName());
descriptionTxt.setText(object.getDescription());
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(object.getPrice()));
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberOrder = numberOrder + 1;
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(numberOrder * price));
//Code if there is no size required
}
});
minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberOrder > 1) {
numberOrder = numberOrder - 1;
}
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(price - itemPrice));
}
});
addToCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
object.setNumberInCard(numberOrder);
object.setFinalPrice(price);
managementCart.insertFood(object);
}
});
}
private void initView() {
addToCardBtn = findViewById(R.id.addToCardBtn);
titleTxt = findViewById(R.id.titleTxt);
feeTxt = findViewById(R.id.priceTxt);
descriptionTxt = findViewById(R.id.descriptionTxt);
numberOrderTxt = findViewById(R.id.numberOrderTxt);
plusBtn = findViewById(R.id.plusBtn);
minusBtn = findViewById(R.id.minusBtn);
picFood = findViewById(R.id.foodPic);
priceBtn = findViewById(R.id.smallPriceBtn);
mediumPriceBtn = findViewById(R.id.mediumPriceBtn);
largePriceBtn = findViewById(R.id.largePriceBtn);
cheese_ll = findViewById(R.id.cheese_ll);
scale_ll = findViewById(R.id.scale_ll);
cheeseBoxyes = findViewById(R.id.cheeseBoxyes);
}

Check if a property of a custom object ArrayList is an empty string or not?

I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.

Why List for Recyclerview returning same items in all positions? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.

How to manipulate volley response in android?

I want to add two features into my listview :-
1)On Long click I want to delete the row.
2)And once the row is
deleted I want to change the document numbers so that it is always in
order.
For eg:- I have a list with doc_no IN1000,IN1001,IN1002 and I
delete the row with doc_no IN1001. What I would like to do is change
the doc_no of IN1002 to IN1001.So that it is always in a sequence.
So far I am successfully able to delete a row using parent.removeViewInLayout(view); but there is a problem if I scroll the listview I get the deleted row back.
This is my code for deleting the row :-
lv_bsall.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, final View view, int position, long id)
{
final int pos = position;
final Dialog delete_expense = new Dialog(ReportGenerator.this);
delete_expense.setContentView(R.layout.delete_payment);
delete_expense.setTitle("DO YOUY WANT TO DELETE Invoice");
Button yes = (Button) delete_expense.findViewById(R.id.yes);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
parent.removeViewInLayout(view);
doc_no = ArrayUtils.removeElement(doc_no,doc_no[pos]);
balance =ArrayUtils.removeElement(balance,balance[pos]);
total =ArrayUtils.removeElement(total,total[pos]);
vat =ArrayUtils.removeElement(vat,vat[pos]);
profit=ArrayUtils.removeElement(profit,profit[pos]);
delete_expense.dismiss();
}
});
Button no = (Button) delete_expense.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delete_expense.dismiss();
}
});
delete_expense.show();
return true;
}
});
This is the method I call on response :-
public void showBS(String response) {
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
doc_no =ParseBS_all.doc_no;
balance =ParseBS_all.balance;
total =ParseBS_all.total;
vat=ParseBS_all.vat;
profit=ParseBS_all.profit;
bl = new BS_allList(this, doc_no, balance, total, vat, profit);
lv_bsall.setAdapter(bl);
}
And this is code for my Adapter class for the list:-
public class BS_allList extends ArrayAdapter<String>
{
private String[] doc_no;
private String[] balance;
private String[] total;
private String[] vat;
private String[] profit;
private Activity context;
public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
{
super(context, R.layout.bs_list_all, doc_no);
this.context =context;
this.doc_no= doc_no;
this.balance = balance;
this.total = total;
this.vat=vat;
this.profit = profit;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
tv_docNo.setText(doc_no[position]);
tv_balance.setText(balance[position]);
tv_tot.setText(total[position]);
tv_vat.setText(vat[position]);
tv_pf.setText(profit[position]);
return listViewItem;
}
}
I am new to programming so any Help or suggestion is most appreciated.Thank you.
I think using ArrayList should be helpful in your case. Please try this solution.It addresses both your requirements:-
public void onClick(View v)
{
ls_docno = new ArrayList<String>(Arrays.asList(doc_no));
ls_balance = new ArrayList<String>(Arrays.asList(balance));
ls_total =new ArrayList<String>(Arrays.asList(total));
ls_vat= new ArrayList<String>(Arrays.asList(vat));
ls_profit =new ArrayList<String>(Arrays.asList(profit));
ls_docno.remove(pos);
ls_balance.remove(pos);
ls_total.remove(pos);
ls_profit.remove(pos);
ls_vat.remove(pos);
Log.d("POSITION",String.valueOf(pos));
for (int i=pos; i< ls_docno.size(); i++)
{
if(i>0)
{
String doc= ls_docno.get(i-1);
String inv_no = doc.replaceAll("[^0-9]", "");
int new_invno = Integer.parseInt(inv_no);
new_invno++;
ls_docno.set(i,"IN"+new_invno);
}
}
doc_no = ls_docno.toArray(new String[ls_docno.size()]);
balance = ls_balance.toArray(new String[ls_balance.size()]);
total = ls_total.toArray(new String[ls_total.size()]);
profit = ls_profit.toArray(new String[ls_profit.size()]);
vat = ls_profit.toArray(new String[ls_vat.size()]);
bl = new BS_allList(ReportGenerator.this, doc_no, balance, total, vat, profit);
lv_bsall.setAdapter(bl);
delete_expense.dismiss();
}
Create a method in your adapter called deleteRow and pass position as am argument. Like this:
public void deleteRow(int position)
{
doc_no = ArrayUtils.removeElement(doc_no, doc_no[position]);
total = ArrayUtils.removeElement(total, total[position]);
balance = ArrayUtils.removeElement(balance, balance[position]);
vat = ArrayUtils.removeElement(vat, vat[position]);
profit = ArrayUtils.removeElement(profit, profit[position]);
notifyDataSetChanged();
}
call it in your LongClick :
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// Here 'bl' is the object of your 'BS_allList' adpater
bl.deleteRow(position);
parent.removeViewInLayout(view);
delete_expense.dismiss();
}
});

Categories