Can't add strings containing currencies - java

I have two errors in my code that I don't know how to solve it.
Please show them and tell me what to do.
Here are the codes of my app:
public class Food {
String price = null;
String name = null;
boolean selected = false;
public Food(String price, String name, boolean selected) {
super();
this.price = price;
this.name = name;
this.selected = selected;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public class MainActivity extends Activity {
MyCustomAdapter dataAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView() {
//Array list of foods
ArrayList<Food> foodList = new ArrayList<Food>();
Food food = new Food("15 SAR", "Chicken Meal", false);
foodList.add(food);
food = new Food("10 SAR", "Sliced Chicken", false);
foodList.add(food);
food = new Food("20 SAR", "Sandwich Chicken", false);
foodList.add(food);
food = new Food("10 SAR", "Hot Chicken", false);
foodList.add(food);
food = new Food("6 SAR", "Grilled potatoes", false);
foodList.add(food);
food = new Food("2 SAR", "Pepsi", false);
foodList.add(food);
food = new Food("17 SAR", "Fish Meal", false);
foodList.add(food);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.food_info, foodList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Food> {
private ArrayList<Food> foodList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Food> foodList) {
super(context, textViewResourceId, foodList);
this.foodList = new ArrayList<Food>();
this.foodList.addAll(foodList);
}
private class ViewHolder {
TextView price;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.food_info, null);
holder = new ViewHolder();
holder.price = (TextView) convertView.findViewById(R.id.price);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Food food = foodList.get(position);
holder.price.setText(" (" + food.getPrice() + ")");
holder.name.setText(food.getName());
holder.name.setChecked(food.isSelected());
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
food.setSelected(b);
}
});
holder.name.setTag(food);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.invoic_page);
int totalPrice = 0;
for (Food f : foodList) {
if (f.isSelected) {
totalPrice += f.getPrice();
}
//totalPrice variable now has the total of all selected items
}
}
});
}
}
I tried to solve them as I can but other errors appear in different places of the code so I want the best solution.

The second issue of money as Strings. You can't simply add "1 SAR" and "2 SAR" and expect to get "3 SAR".
If this is a single currency system, don't append " SAR" everywhere and don't use strings to store the values, either ints or longs and store your currency's lowest division, e.g. halalas.
new Food("15 SAR", "Chicken Meal", false); becomes new Food(1500, "Chicken Meal", false);
Then to display to the user a price:
String forDisplay = String.format("%.2f SAR", totalHalas/100);
Alternatively, especially if this is a multicurrency system create a class for your currency:
Personally I would use a library for this: Joda Money.
But you can also roll your own:
public class Money {
private final String currency;
private final long value;
private final int dp;
public Money(long value, int dp, String currency){
this.value = value;
this.dp = dp;
this.currency = currency;
}
//optional helper factory method
public static Money sar(long halas){
return new Money(halas, 2, "SAR");
}
public Money add(Money other){
if(!other.currency.equals(currency))
throw new RuntimeException("Can't add different currencies");
if(!other.dp.equals(dp))
throw new RuntimeException("The decimal places do not match");
return new Money(value + other.value, dp, currency);
}
public String toString(){
return String.format("%."+dp+"f %s", value/Math.pow(10,dp), currency);
}
}
Example usage:
System.out.println(new Money(1500,2,"SAR").add(new Money(623,2,"SAR")));
//or:
System.out.println(Money.sar(1500).add(Money.sar(623)));
Outputs:
21.23 SAR

totalPrice is int and in Food model class price is String. So you need convet
for (Food f : foodList) {
if (f.isSelected) {
totalPrice += Integer.parseInt(f.getPrice());
}
//totalPrice variable now has the total of all selected items
}
and final Food food = foodList.get(position); need to define final

For the first error, you need need to make the food variable final:
// Make this final.
final Food food = foodList.get(position);
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
food.setSelected(b);
}
});
For the second error, you need to convert the String value to interger:
for (Food f : foodList) {
if (f.isSelected) {
totalPrice += Integer.valueOf(f.getPrice());
}
}
But you better make the price variable as integer or BigInteger for price in Food class or BigDecimal.
UPDATE
Never save your currency in your price value. Instead, you can add a new variable like currency name. Do not save it for the sake of portability and future bug-free code.

Related

How to save Rating of each item in list view?

1. I have a ListView that contains images, persons names, persons birthdays. When the user click on an item a new activity will be launched to show the details of this item. In this activity i have created a Rating bar where the user are going to rate each item.
2. I have tried to use SharedPreferences to save the average calculated of rated items.I found that when i save the rates and launch the app again the values are not stored in SharedPreferences.
My main goal to achieve is to calculate the average of each rated items and save them in SharedPreferences.
3. Person Class:
public class PersonInfo {
private int image;
private String name;
private String birthday;
private float rating;
public PersonInfo(int image, String name, String birthday, float rating) {
this.image = image;
this.name = name;
this.birthday = birthday;
this.rating = rating;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getName(){
return name;
}
public int getImage() {
return image;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
Person Adapter:
public class StudentsListAdapter extends ArrayAdapter<PersonInfo>{
private Context contxt;
private int rsrc;
private List<PersonInfo> persons;
private boolean isAdmin;
private TextView pName, pBirthday;
public StudentsListAdapter( Context context, int resource, List<PersonInfo> _persons, boolean _isAadmin) {
super(context, resource, _persons);
contxt = context;
rsrc = resource;
persons=_persons;
isAdmin = _isAadmin;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(contxt);
View view = inflater.inflate(rsrc, null,false);
ImageView imageView = view.findViewById(R.id.imgP);
pName = view.findViewById(R.id.txtView2);
pBirthday = view.findViewById(R.id.txtView3);
PersonInfo p = persons.get(position);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(contxt,ViewItems.class);
String name = persons.get(position).getName();
String birth = persons.get(position).getBirthday();
intent1.putExtra("name",name);
intent1.putExtra("birth",birth);
contxt.startActivity(intent1);
}
});
imageView.setImageDrawable(contxt.getResources().getDrawable(p.getImage()));
pBirthday.setText(p.getBirthday());
pName.setText(p.getName());
}
return view;
}
Rate Items:
public class ViewItems extends AppCompatActivity {
EditText edName;
TextView edBirth;
float myRating = 0;
Button svRate;
RatingBar rtBar;
String position;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_items);
edName = findViewById(R.id.st_editName);
edBirth = findViewById(R.id.tv_editDate);
rtBar = findViewById(R.id.ratingBar);
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
edName.setText(name);
edName.setEnabled(false);
edName.setTextColor(Color.BLACK);
String birth = extras.getString("birth");
edBirth.setText(birth);
edBirth.setEnabled(false);
edBirth.setTextColor(Color.BLACK);
ImageView image = (ImageView) findViewById(R.id.user_img);
image.setBackgroundResource(android.R.drawable.btn_star);
position = getIntent().getStringExtra("position");
rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
int rating1 = (int) rating;
String message = null;
myRating = ratingBar.getRating();
switch (rating1){
case 1:
message = "Sorry to hear that!";
break;
case 2:
message = "You always accept suggestions!";
break;
case 3:
message = "Good enough!";
break;
case 4:
message = "Great! Thank you!";
break;
case 5:
message = "Awesome! You are the best!";
break;
}
Toast.makeText(ViewItems.this, message, Toast.LENGTH_SHORT).show();
}
});
svRate = findViewById(R.id.sv_item);
svRate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i4 = new Intent(ViewItems.this, MainActivity.class);
SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
myRating = sharedPreferences.getFloat("rating_float", 0f);
float total = 0;
total += rtBar.getRating();
float average = total / 2;
rtBar.setRating(average);
startActivity(i4);
Toast.makeText(ViewItems.this, "Your rating is:" + (myRating), Toast.LENGTH_SHORT).show();
}
});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView edName,edBirth;
String position;
String ed_name;
String ed_birth;
String username, password;
ArrayList<PersonInfo> students;
ArrayList<PersonInfo> students1;
ListView listView1;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
float rtBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
students = new ArrayList<>();
students1 = new ArrayList<>();
Intent intent = getIntent();
if(getIntent() != null){
username = intent.getStringExtra("Username");
password = intent.getStringExtra("Password");
edName = findViewById(R.id.txtView2);
edBirth = findViewById(R.id.txtView3);
listView1 = (ListView) findViewById(R.id.li_view);
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students1, true);
listView1.setAdapter(test1);
if(username!= null && username.equals("test") && password != null && password.equals("123")){
Log.d(TAG, "onCreate: Started.");
ListView listView = (ListView) findViewById(R.id.li_view);
students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students, true);
listView1.setAdapter(test1);
}
else if (username != null && username.equals("test2") && password != null && password.equals("1234"))
{
ListView listView = (ListView) findViewById(R.id.li_view);
students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students,false);
listView1.setAdapter(test1);
}
SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putFloat("rating_float", rtBar);
editor.apply();
}
}
}
What am i doing wrong?
Any help will be greatly appreciated.
Thank you!
You dont even try to save anything. You just put rtBar
editor.putFloat("rating_float", rtBar);
that even not initialized but in case this is a primitive type of data float it have default value 0
I think you forgot to initialize rtBar, as #Eugene told you. You can initialize it by grabbing the average of all student:
for (PersonInfo personInfo : students) {
rtBar += personInfo.getRating();
}
// now store it in sharedPrefs

How to make a recyclerview show only one array depending on a percantage?

i want a recyclerview to show only one array, but having more of them in the arraylist. The one that has to be shown can't always be the same, but it will depend on some percentages.
Eg.: the 1st array has 20% of chances, the 2nd 50% and the 3rd 50% percent too. And randomly one will be shown. But when i refresh the screen it will change.
I suppose that what i should do is to set percentages to every single array on the arraylist, but i don't know how to do it and what to do next.
That's my java file.
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And that is the adapter:
public class Adaptador extends RecyclerView.Adapter<Adaptador.ViewHolder> //implements View.OnClickListener
{
private List<Entidad> listItems;
private OnRecipeListener mOnRecipeListener;
public Adaptador(List<Entidad> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
this.mOnRecipeListener = onRecipeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista, parent, false);
//view.setOnClickListener(this);
return new ViewHolder(view, mOnRecipeListener);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
int resource = listItems.get(position).getImgFoto();
String title = listItems.get(position).getTitulo();
String time = listItems.get(position).getTiempo();
int barra = listItems.get(position).getRating();
int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra, fondo);
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
private ImageView colorfondo;
OnRecipeListener onRecipeListener;
public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);
imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
colorfondo = itemView.findViewById(R.id.colorfondo);
this.onRecipeListener = onRecipeListener;
itemView.setOnClickListener(this);
}
private void setData(int resource, String title, String time, int barra, int fondo){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
colorfondo.setImageResource(fondo);
}
#Override
public void onClick(View v) {
onRecipeListener.OnRecipe(getAdapterPosition());
}
}
public interface OnRecipeListener{
void OnRecipe(int position);
}
}
Here there is the Entidad file:
public class Entidad2 {
private int imgFoto;
private String titulo;
private String tiempo;
private int ratingBar;
private int colorfondo;
public Entidad2(int imgFoto, String titulo, String tiempo, int ratingBar, int colorfondo) {
this.imgFoto = imgFoto;
this.titulo = titulo;
this.tiempo = tiempo;
this.ratingBar = ratingBar;
this.colorfondo = colorfondo;
}
public int getImgFoto() {
return imgFoto;
}
public String getTitulo() {
return titulo;
}
public String getTiempo() {
return tiempo;
}
public int getRating() { return ratingBar; }
public int getColorfondo() {
return colorfondo;
}
}
Please if anyone has any idea of how to do it, tell me.
And in case you need more code just tell me,
thank you.
enter image description here
Here #Emir look if it is inside
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, R.drawable.color_carnes, 50));
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, R.drawable.color_carnes, 200));
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, R.drawable.color_carnes, 350));
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
Adaptador2 Adaptador2 = new Adaptador2(listItems, this);
recyclerView1.setAdapter(Adaptador2);
Adaptador2.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int position) {
if (position == 0) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(351);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
Adaptador2.notifyDataSetChanged();
}
}
What I understand is that you want to show a single Entidad object from your Entidad list randomly with different show chances.
Ex: Create an integer field named Priority on your Entidad object. Set the first Entidad's priority to 50, the second 200, the third 350.Create the following method to randomly pick depending on priority.(Save references of your Entidad objects on your mainactivity after you create them.)
Edit: Entidad.java
public class Entidad {
private int imgFoto;
private String titulo;
private String tiempo;
private int ratingBar;
private int colorfondo;
private int priority;
public Entidad(int imgFoto, String titulo, String tiempo, int ratingBar, int colorfondo, int priority) {
this.imgFoto = imgFoto;
this.titulo = titulo;
this.tiempo = tiempo;
this.ratingBar = ratingBar;
this.colorfondo = colorfondo;
this.priority = priority;
}
public int getRatingBar() {
return ratingBar;
}
public int getPriority() {
return priority;
}
public int getImgFoto() {
return imgFoto;
}
public String getTitulo() {
return titulo;
}
public String getTiempo() {
return tiempo;
}
public int getRating() { return ratingBar; }
public int getColorfondo() {
return colorfondo;
}
}
Edit 2: Use of the getEntidad()
public class Comida extends AppCompatActivity implements Adaptador.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad> listItems;
Adaptador adaptor;
private Entidad entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new
LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
//Initialize entidad objects and keep references of them to use in pickEntidad() method
entidad1 = new Entidad(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, R.drawable.color_carnes,50);
entidad2 = new Entidad(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, R.drawable.color_carnes,200);
entidad3 = new Entidad(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, R.drawable.color_carnes,350);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador(listItems, this);
recyclerView1.setAdapter(adaptador);
adaptor.notifyDataSetChanged();
//Call pickEntidad() to randomly pick one entidad and show on the list
pickEntidad();
}
#Override
public void OnRecipe(int position) {
if (position == 0) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
}
private void pickEntidad(){
//Generates random int value between 0-350
final int random = new Random().nextInt(351);
//get priorities from your created Entidad objects.
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear()
//Pick one randomly depending on priority
if(random < priority1){
listItems.add(entidad1)
}else if(random < priority2){
listItems.add(entidad2)
}else if (random <= priority3){
listItems.add(entidad3)
}
//update your adapter
adaptor.notifyDataSetChanged()
}
}
Each time you want to refresh your list, call this pickEntidad() method. This is a hardcoded approach though, would be useless if you have too many items and do not know the priority values or the range. You can also set your item priorities randomly by generating an int between 0-351. Hope I understood your question correctly.
Also, don't give variables names with capital latters. Changed your 'Adaptor' variable into 'adaptor'

how to put a few data into array variable and post as JSONarray?

I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.

How to Delete Item Without Deleting Position in Recycler View?

I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}

Clear ListView if response is a empty array?

I have two spinners the first one for month and the second for years.I am trying to call a method send_date() if on Item Selected is called for any of the 2 spinners.
So I have two problems:- 1)send_date() gets called twice the first
time it gets the correct data as expected but the 2nd time it returns
a empty array. 2)When I select another month or year the old data does
not get removed that is the list does not refresh.
The following is my code for on Item Selected :-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int i = spinYear.getSelectedItemPosition();
selected_year = years.get(i);
Log.d("Selection Year",selected_year);
tv_year.setText(selected_year);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
And for the month spinner:-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int j = spinMonths.getSelectedItemPosition();
selected_month = Months[j];
Date date = null;
try {
date = new SimpleDateFormat("MMMM").parse(selected_month);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
tv_month.setText(String.valueOf(cal.get(Calendar.MONTH)+1));
Log.d("Selection Month",selected_month);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
On response I call the following method for populating the list view with data:-
public void showBS(String response)
{
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
bl = new BS_allList(getActivity(),ParseBS_all.doc_no,ParseBS_all.balance,ParseBS_all.total,ParseBS_all.vat,ParseBS_all.profit);
lv_bsall.setAdapter(bl);
}
This is the code for the send_date method:-
//This method is used to send month and year
private void send_date() throws JSONException {
final String year = tv_year.getText().toString();
final String month = tv_month.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, SEND_DATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//display.setText("This is the Response : " + response);
String resp = response.toString().trim();
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
// bl.clear();
lv_bsall.setAdapter(bl);
bl.notifyDataSetChanged();
}else
{
Toast.makeText(getContext(), "Response" + response, Toast.LENGTH_LONG).show();
Log.d("RESPONSE for date", response.toString().trim());
showBS(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
GlobalClass gvar = (GlobalClass) getActivity().getApplicationContext();
String dbname = gvar.getDbname();
Map<String, String> params = new HashMap<>();
params.put(KEY_DBNAME, dbname);
params.put(KEY_MONTH, month);
params.put(KEY_YEAR,year);
return params;
}
};
RequestQueue requestQ = Volley.newRequestQueue(getContext());
requestQ.add(stringRequest);
}
Adapter code for list view.
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;
}
}
Also note that I have set the spinner to point to the current month and year so the first time it works properly.
I am new to programming so any help or suggestion is appreciated.Thank you.
Hi #AndroidNewBee,
As per our discussion made following changes in your code and you will get proper output and it will resolve your issues.
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
bl = new BS_allList(getActivity(),{""},{""},{""},{""},{""});
lv_bsall.setAdapter(bl);
}
And second is check validation as below,
try {
if((selected_year != null & selected_year.length > 0 ) & (tv_month.getText().toString() != null & tv_month.getText().toString().length > 0))
{
send_date();
}
} catch (JSONException e) {
e.printStackTrace();
}
First you shouldn't be using so many String[], instead wrap them in a class
Class BSDataModel{
private String doc_no;
private String balance;
private String total;
private String vat;
private String profit;
//getters and setters
}
Now the reponse result should be added as in ,it returns List<BSDataModel>
List<BSDataModel> reponseList = new ArrayList<>();
//for example adding single response
for(int i=0;i<jsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(jsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(jsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
BS_allList.java
public class BS_allList extends ArrayAdapter<BSDataModel>
{
private List<BSDataModel> bsList;
private Activity context;
public BS_allList(Activity context,List<BSDataModel> bsList)
{
super(context, R.layout.bs_list_all, bsList);
this.context =context;
this.bsList = bsList;
}
#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);
BSDataModel bsData = bsList.get(position);
tv_docNo.setText(bsData.getDoc());
tv_balance.setText(bsData.getBalance());
tv_tot.setText(bsData.getTot());
tv_vat.setText(bsData.getVat());
tv_pf.setText(bsData.getPF());
return listViewItem;
}
}
Now in your class
BS_allList bl = new BS_allList(getActivity(),responseList);//which you got above
After receiving new Response
// remove old data
responseList.clear(); // list items in the sense list of array used to populate listview
if(newresponseArray.size() > 0){
for(int i=0;i<newjsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(newjsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(newjsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
}
//refresh listview
bl.notifyDataSetChanged();
Try this way,
1. adapter.clear();
2. Add/Remove your list Items.
3. listview.setAdapter(adapter);
4. adapter.notifyDatasetChanged();
this procedure should work.

Categories

Resources