I am saving data in my firebase database and I want to display it. This works but I get an exception when I say textview.setText("Bla " + object); The exception happens because of the result1 and result2 variable, but I don't know how to solve this problem. It happens in the setBias method.
public static class BetViewHolder extends RecyclerView.ViewHolder {
TextView bias, foodEp, profit;
View resultColor;
double result1;
double result2;
double result;
public BetViewHolder(View itemView) {
super(itemView);
bias= (TextView) itemView.findViewById(R.id.bias);
foodEp= (TextView) itemView.findViewById(R.id.food);
profit= (TextView) itemView.findViewById(R.id.profit);
}
public void setBias(String biasFoll) {
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(bias.getText().toString());
}
public void setFoodEp(String foodEpsa) {
foodEp.setText(foodEpsa);
result2 = Double.parseDouble(foodEp.getText().toString());
result = result1 * result2;
profit.setText(String.valueOf(result));
}
I have 2 ideas:
1) Mb you should change result1 = Double.parseDouble(bias.getText().toString()); with result1 = Double.parseDouble(biasFoll);?
2) Surround your "result1 = Double.parseDouble(bias.getText().toString());" with try {} catch (NumberFormatException e) {} and set some default value to result1
You are trying to convert String to Double:
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(bias.getText().toString());
That is not possible and that's why you are getting NumberFormatException.
You cannot parse string bias 88 to double, I have made some changes in your method look into it and try
public void setBias(String biasFoll) {
bias.setText("Bias: " + biasFoll);
result1 = Double.parseDouble(biasFoll);
}
use the following
Remeber that your string must consist a numeric value
bias.setText( biasFoll);
result1 = Double.parseDouble(bias.getText().toString().trim());
Related
This is my recycler view in which I am storing my expense related information . I want to sum the amount paid of each corresponding user . For example , sadaf : Rs (50+10+5)=65 , Gulatiji: (50)Rs =50 , Amen :(50+5)= Rs 55 .
I thought of using hash map but the problem is that the user names in my recycler view are not unique . So , how should I store the sum of each corresponding user .
I have also tried this but this is giving me the wrong answer .
I am able to successfully sum the total amount column but for the amount paid , it is giving me the wrong answer. For the time being , I was just trying to calculate the total amount of a single user by using an integer variable my_total .I am getting the answer for sadaf as 110 but it should be 65.
calcuationAdap = new CalcuationAdap(Calculation.this,data);
for (int i = 0 ;i<data.size();i++) {
System.out.println(data.get(i).getItem());
main_total = main_total + Integer.parseInt(data.get(i).getTot_amt());
}
for(int i=0;i<data.size();i++)
{
for( int j=i+1;j<data.size()-1;j++)
{
if(data.get(i).getUser_name().equals(data.get(j).getUser_name()))
{
System.out.println(data.get(i).getUser_name());
my_total = my_total+Integer.parseInt(data.get(i).getMy_amt());
}
}
}
Toast.makeText(getApplicationContext(), String.valueOf(main_total ), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), String.valueOf(my_total), Toast.LENGTH_SHORT).show();
If you have user id then use user id. other wise use below code to get each total amount
calcuationAdap = new CalcuationAdap(Calculation.this,data);
HashMap<String,Integer> result =new HashMap<>();
for (int i = 0 ;i<data.size();i++) {
System.out.println(data.get(i).getItem());
main_total = main_total + Integer.parseInt(data.get(i).getTot_amt());
}
for(int i=0;i<data.size();i++) {
if (result.containsKey(data.get(i).getUser_name())){
Integer addTotal=result.get(data.get(i).getUser_name());
addTotal= addTotal + Integer.parseInt(data.get(i).getMy_amt());
result.put(data.get(i).getUser_name(),addTotal);
}else {
result.put(data.get(i).getUser_name(),Integer.parseInt(data.get(i).getMy_amt()));
}
}
Toast.makeText(getApplicationContext(), String.valueOf(main_total ), Toast.LENGTH_SHORT).show();
for (Map.Entry<String, Integer> entry:result.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
Toast.makeText(getApplicationContext(), entry.getKey() + "/" + entry.getValue(), Toast.LENGTH_SHORT).show();
}
create a model class like
public class MyDataClass {
String userName;
String date;
String item;
int totoalAmount;
int amountPaid;
public int getAmountPaid() {
return amountPaid;
}
public int getTotoalAmount() {
return totoalAmount;
}
public String getDate() {
return date;
}
public String getItem() {
return item;
}
public String getUserName() {
return userName;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public void setDate(String date) {
this.date = date;
}
public void setItem(String item) {
this.item = item;
}
public void setTotoalAmount(int totoalAmount) {
this.totoalAmount = totoalAmount;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
and whenever you need to store data as a list of such type create array list of this type like
ArrayList list =new ArrayList<>()
and create object of this class to store data with getter methods like
MyDataClass data =new MyDataClass()
data.setUserName("userName")
....
list.add(data);
and whenever you need to get data use getter method to get data like
list.get(index).getUserName();
I have created a simple app to calculate the discount. it works fine when the values are provided, but keeps on crashing when calculation is done with empty text fields. thanks in advance..!!
public class Firstctivity extends AppCompatActivity {
Button find;
EditText ed1,ed2;
TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstctivity);
find=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.text39);
ed1=(EditText)findViewById(R.id.sai);
ed2=(EditText)findViewById(R.id.editText);
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
try {
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
});
}
}
try tihs.
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(ed1.getText().toString.length() >0){
try {
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
}
});
When you try to calculate the discount, you call ed1.getText() and then, you try to convert a null value into a double value, witch causes a NullPointerException.
To solve that issue, you have to check if the getText() method is returning a valid text to convert it.
You'll want to check for empty strings and null values:
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ed1.getText() != null && !TextUtils.isEmpty(ed1.getText().toString()) &&
ed2.getText() != null && !TextUtils.isEmpty(ed2.getText().toString())) {
try {
final double a = Double.parseDouble(String.valueOf(ed1.getText().toString()));
final double b = Double.parseDouble(String.valueOf(ed2.getText().toString()));
double c = a * b;
double results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
} catch (NumberFormatException ex) {
Log.e("SOME TAG", ex.getMessage(), ex);
}
}
}
});
using try- catch in such simple calculations is not recommended and may "hide" crusial errors. First of all start with an If-statement inside your click event and do all your checks inside there. (if txtValue.getText()!=null {do something} ). this way it is easier for you to debug and correct your code.
So, just to clarify; remove try-catch. do if-stament and check if your txt fields are not null before proceeding to any calculations.finish you click event without any problem and with a valid calculation.
Here is my main issue, after some researches, I didn't find a solution so... I would like to sort my list of custom objects. These items have a price, but for a reason they are strings not int. I would like to know how to achieve this, thanks for helping !
Little personnal question, sorting a listview and a recyclerview are they done the same way ?
EDIT:
public class Product implements Parcelable {
private String imgUrl, titre, description, prix, nomAgence, pays, ville, type_produit, nbPieces = null;
List<String> urlImageList_thumb = new ArrayList<>();
List<String> urlImageList_full = new ArrayList<>();
private int isAdded = 0;
/* getters and setters*/
}
EDIT 2 :After your help, here's my code for comparable
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "");
String tmp2 = otherProduct.prix.replace(" €", "");
//Integer p1 = Integer.valueOf(tmp); --> does not work
//Integer p2 = Integer.valueOf(tmp2); --> does not work
Integer p1 = Integer.parseInt(tmp); //same error
Integer p2 = Integer.parseInt(tmp2); // same error
return p1.compareTo(p2);
}
Here's the code in the activity:
bouton_tri.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collections.sort(productList);
}
});
EDIT 3 :
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
I still have an error, but when I just take off " €" the value is "5 300 000", if only spaces "5300000€". But putting both together gives me this error java.lang.NumberFormatException: Invalid int: "-" ... Any ideas ? Thanks
You can make modify your Product class to implement Comparable
Before converting the String to an Integer you need to remove the €and all spaces.
public class Product implements Parcelable, Comparable<Product> {
private String prix;
//...
#Override
public int compareTo(Product otherProduct) {
String tmp = prix.replace(" €", "").replaceAll(" ", "");
String tmp2 = otherProduct.prix.replace(" €", "").replaceAll(" ", "");
Integer p1 = Integer.valueOf(tmp);
Integer p2 = Integer.valueOf(tmp2);
return p1.compareTo(p2);
}
}
Once done to sort your collection you can use : Collections.sort(...); this method will take as parameter the list of custom objects you are using in your adapter.
For example:
List<Product> l = new ArrayList();
Collections.sort(l);
Note that sorting the collection will not refresh the views of the recyclerview.
You will have to call notifyDataSetChanged() on your adapter to refresh the recyclerview:
You can do this in your main activity where you have declared your adapter :
yourAdapter.notifyDataSetChanged();
Just assuming you have List<String> sampleData object
Collections.sort(sampleData, new Comparator<String>() {
#Override
public int compare(String c1, String c2) {
return Integer.valueOf(c1) - Integer.valueOf(c2);
}
});
This will sort your data.
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
int value = Integer.parseInt(string)
Try this:
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
OR
Collections.sort (list, new Comparator<String> () {
#Override
public int compare (String s1, String s2) {
//cast string price to integer
int price1 = Integer.parseInt(s1);
int price2 = Integer.parseInt(s2);
if (price1 > price1) {
return 1;
}
else if (price2 > price1) {
return -1;
}
else {
return 0;
}
}
});
I want to sum the numbers entered in two EditText then when the button is clicked I want the sum to be showed in the third EditText but it seems something is wrong.
This is my code:
result = (Button)findViewById(R.id.btn1);
nb1 = (EditText)findViewById(R.id.nb1);
nb2 = (EditText)findViewById(R.id.nb2);
nb3 = (EditText)findViewById(R.id.nb3);
}
public void result (View v){
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
nb3.setText(n11 + n22);
Use following code.
nb3.setText(String.valueOf(n11 + n22));
Change this
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));
Change:
nb3.setText(n11 + n22);
to
nb3.setText(String.valueOf(n11 + n22));
setText treats integers as a resource ID which is why you need to explicitly convert it to a string.
Do the following:
int num1 = Integer.parseInt(edit1.getText().toString());
int num2 = Integer.parseInt(edit2.getText().toString());
edit3.setText(String.valueOf(num1+num2));//this you need to do
Put:
nb3.setText("" + n11 + n22);
It will show NumberFormatException if you press the button without entering the value in the edittext. So do like this
public void result (View v){
try
{
int sum = 0;
String n1 = nb1.getText().toString();
int n11 = Integer.parseInt(n1);
String n2 = nb2.getText().toString();
int n22 = Integer.parseInt(n2);
sum = n11 + n22;
nb3.setText("Sum is = " + sum); // nb3.setText(" " + sum); if you don't want only result to be displayed.
}
catch (Exception e)
{
}
}
I've been looking for a way to capture the order of element's listed within a tag, but haven't been very successful..
EDIT NEW:
<android>
<leags>
<leag name = "someName">
<headlines>
<pageType>headlines</pageType>
<story>someStoryURL</story>
<fullStory>someFullStoryURL</fullStory>
</headlines>
<scores></scores>
<statistics></statistics>
</leag>
<leags>
</android>
-Want to capture the order of elements in leag as 1)headlines 2)scores 3)statistics. If the xml changes and scores is listed before headlines it would be 1)scores 2)headlines 3)statistics.
I parse only android - Like this:
#Root(name = "android", strict = false)
public class android
{
#ElementList(name = "leags", required = false)
private List<Leag> leags;
public Leag getLeagByName(String name)
{ // go through list of leags and return leag with matching name}
}
So in my "leag" object I'd want to capture the order of elements - Is there a way to do that?
I'm assuming you'd need to set new AnnotionStrategy() like this:
tAndroid android = null;
Serializer serial = new Persister(new AnnotationStrategy());
android = serial.read(android .class, source);
League x= android.getLeagueByName("oeoe");
for(String s: x.getOrder())
{
Log.i("Order", s);
}
BEFORE EDIT:
Supposing the xml above is what's being pased by the following code:
#Element(name="headlines")
public class Headlines
{
#Element(name="pageType", required = false)
private String pageType;
#Element(name="story", required = false)
private String storiesURL;
#Element(name="fullStory", required = false)
private String fullStoryURL;
public String getStoriesURL()
{
return storiesURL;
}
public String getFullStoryURL()
{
return fullStoryURL;
}
#Override
public String toString()
{
return "PageType: " + this.pageType +
"\nStoriesURL: " + this.storiesURL +
"\nFullStoryURL: " + this.fullStoryURL;
}
}
Is there a way to somehow return the order in which the elements get parsed?
Like a method that will return a string of some sort with the correct order like:
pageType
story
fullStory
You can use a Converter to get the order. But you can't return the order from it (or better: you can, but better don't do it).
It's relatively easy to get the order - the trick is getting it out from the Converter. On way is to add a list to your class and store it there.
Implementation:
#Root(name = "headlines")
#Convert(value = Headlines.HeadlinesConverter.class)
public class Headlines
{
#Element(name="pageType", required = false)
private String pageType;
#Element(name="story", required = false)
private String storiesURL;
#Element(name="fullStory", required = false)
private String fullStoryURL;
private List<String> order; // Here we save the order of the elements
public String getPageType()
{
return pageType;
}
public String getStoriesURL()
{
return storiesURL;
}
public String getFullStoryURL()
{
return fullStoryURL;
}
public List<String> getOrder()
{
return order;
}
#Override
public String toString()
{
return "Headlines{" + "pageType=" + pageType
+ ", storiesURL=" + storiesURL
+ ", fullStoryURL=" + fullStoryURL + '}';
}
// You can implement the converter as an extra class too
static class HeadlinesConverter implements Converter<Headlines>
{
#Override
public Headlines read(InputNode node) throws Exception
{
Headlines h = new Headlines();
h.order = new ArrayList<>(3);
InputNode next = node.getNext();
while( next != null )
{
final String value = next.getValue();
/*
* You can use reflection (= slower) instead the switch, or
* remove the switch:
*
* h.order.add(next.getName());
*
* and do this after the while loop:
*
* h.pageType = node.getNext("pageType");
* ...
*/
switch(next.getName())
{
case "pageType":
h.pageType = value;
break;
case "story":
h.storiesURL = value;
break;
case "fullStory":
h.fullStoryURL = value;
break;
default:
/* Maybe some error-handling here?! */
break;
}
h.order.add(next.getName()); // add 'value' if you want the order of the values
next = node.getNext();
}
return h;
}
#Override
public void write(OutputNode node, Headlines value) throws Exception
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Note: I didn't use setter here - but it's better you do so.
Example code:
final File f = new File("test.xml");
Serializer ser = new Persister(new AnnotationStrategy()); /* ! */
Headlines h = ser.read(Headlines.class, f);
int i = 1;
for( String s : h.getOrder() )
{
System.out.println((i++) + ". " + s);
}
and finally the output:
1. pageType
2. story
3. fullStory
You need to use #Order annotation. Here can see an example http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#xpath