App closing on button click - android

My app is trying to make some calculations and checking for a condition and printing the array of numbers which satisfy the condition.But the app is closing on click.Please help..
package com.example.ganesha.app1;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static android.R.attr.button;
public class MainActivity extends AppCompatActivity {
private Button result;
private EditText cap,pwfac,dis,solution;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (Button) findViewById(R.id.resbut);
cap = (EditText) findViewById(R.id.capacity);
pwfac = (EditText) findViewById(R.id.powerfactor);
dis = (EditText) findViewById(R.id.distance);
solution = (EditText) findViewById(R.id.result);
//mytextview = (TextView)findViewById(R.id.result)
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double capacity = Double.valueOf(cap.getText().toString());
Double powerfactor = Double.valueOf(pwfac.getText().toString());
Double distance = Double.valueOf(dis.getText().toString());
Double amps = capacity / (718.80 * powerfactor);
Double minimum = 24.9;
Double ampspermtr=amps/distance;
Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
Double [] volts=new Double[19];
for(int i = 0; i <19; i++)
{
volts[i]=cases[i]*ampspermtr;
}
Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
final Double [] allpossible = new Double[19];
int c=0;
for(int j=0;j<19;j++)
{
if(volts[j]<minimum)
{
allpossible[c]=wires[j];
}
c++;
}
final int g= c;
for(int p=0;p<g;p++)
{
String value = Double.toString(allpossible[g]);
solution.append(value);
}
}
});
It is based on electrical Engineering.Can someone find the mistake and help me out

Actually there some Exception occurred in you calculation in
OnClick of Button you should write the Calculation code surround
with try catch block like Below
try{
Double capacity = Double.valueOf(cap.getText().toString());
Double powerfactor = Double.valueOf(pwfac.getText().toString());
Double distance = Double.valueOf(dis.getText().toString());
Double amps = capacity / (718.80 * powerfactor);
Double minimum = 24.9;
Double ampspermtr=amps/distance;
Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
Double [] volts=new Double[19];
for(int i = 0; i <19; i++)
{
volts[i]=cases[i]*ampspermtr;
}
Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
final Double [] allpossible = new Double[19];
int c=0;
for(int j=0;j<19;j++)
{
if(volts[j]<minimum)
{
allpossible[c]=wires[j];
}
c++;
}
final int g= c;
for(int p=0;p<g;p++)
{
String value = Double.toString(allpossible[g]);
solution.append(value);
}
}
}Catch(Exception ex){
// handle your Exception here
}

Related

How to read TensorBuffer

I am new to Tensorflow and Android, I am trying to classify data from external accelerometer to predict weather it align to left, right, forward , back or center. So I trained model using colab and converted it to tflite and added it to Android App, I could not make any sense of output
package com.yogai.tensorflowlava;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Toolbar;
import com.yogai.tensorflowlava.ml.Adxl345;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.TensorFlowLite;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MainActivity extends AppCompatActivity {
Button submitButton;
EditText editText;
String text;
String TAG = "My_APp";
// private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context;
editText = findViewById(R.id.editText);
submitButton = findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text = editText.getText().toString().trim();
//String str = "geekss#for#geekss";
// String[] arrOfStr = text.split(",", 3);
//
// // String[] strings = new String[] {"1", "2", "3", "4"};
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
// Float[] floats = Arrays.stream(arrOfStr).map(Float::valueOf).toArray(Float[]::new);
// }
String[] parts = text.split(",");
float[] numbers = new float[parts.length];
for (int i = 0; i < parts.length; ++i) {
float number = Float.parseFloat(parts[i]);
float rounded = (int) Math.round(number * 1000) / 1000f;
numbers[i] = rounded;
}
// float[][] array2d = new float[1][3];
//
//
//
// for(int j=1;j<4;j++) {
// array2d[1][j] = numbers[j];
//
//
// }
// Float testValue = array2d[1][1]+1;
Log.d(TAG,String.valueOf(numbers[1]));
ByteBuffer.allocate(4).putFloat(numbers[0]).array();
byte[] byteArray= FloatArray2ByteArray(numbers);
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
getOutput(byteBuffer);
}
});
}
public static byte[] FloatArray2ByteArray(float[] values){
ByteBuffer buffer = ByteBuffer.allocate(4 * values.length);
for (float value : values){
buffer.putFloat(value);
}
return buffer.array();
}
private void getOutput(ByteBuffer byteBuffer) {
try {
Adxl345 model = Adxl345.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 3}, DataType.FLOAT32);
inputFeature0.loadBuffer(byteBuffer);
// Runs model inference and gets result.
Adxl345.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
String converted = new String(buffer.array(), "UTF-8");
Toast.makeText(this,"output: "+outputFeature0.toString(),Toast.LENGTH_SHORT).show();
// Releases model resources if no longer used.
model.close();
} catch (IOException e) {
// TODO Handle the exception
Toast.makeText(this,"Error: "+ e.toString(),Toast.LENGTH_SHORT).show();
}
}
}
You can use outputFeature0.getDataType().toString() to check the type of the data.
It would return a string among "FLOAT32","INT32","UINT8","INT64","STRING","INT8".
If the type of the data is FLOAT32, you can get the data like below:
float[] data=outputFeature0.getFloatArray()

Android Listview new item at top

I have a Listview. I want to order it such that when new item added they add at top. I try
Collections.reverse(ListElementsArrayList);
And it works. But after (second,third click,....) it mix all earlier item.Is this possible. If yes help me.
My MainActivity is
package com.pradeep.ap;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class AP extends AppCompatActivity {
EditText A, B, D, N, AN;
Button a, b, d, n, an, AP, GP, HP;
int Count = 0;
ListView LV;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ap);
A = (EditText) findViewById(R.id.eta);
B = (EditText) findViewById(R.id.etb);
D = (EditText) findViewById(R.id.etd);
N = (EditText) findViewById(R.id.etn);
AN = (EditText) findViewById(R.id.etan);
AP = (Button) findViewById(R.id.apap);
GP = (Button) findViewById(R.id.apgp);
HP = (Button) findViewById(R.id.aphp);
a = (Button) findViewById(R.id.a);
b = (Button) findViewById(R.id.b);
d = (Button) findViewById(R.id.d);
n = (Button) findViewById(R.id.n);
an = (Button) findViewById(R.id.an);
LV = (ListView) findViewById(R.id.lv);
handler = new Handler();
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(AP.this,android.R.layout.simple_list_item_1,
ListElementsArrayList);
LV.setAdapter(adapter);
adapter.notifyDataSetChanged();
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numb = 0;
float numd = 0;
float numleal=0;
float result = 0;
int Result;
if (TextUtils.isEmpty(B.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())) {
return;
}
numb = Float.parseFloat(B.getText().toString());
numd = Float.parseFloat(D.getText().toString());
ListElementsArrayList.add(" First term of AP is = " + A.getText().toString());
result = numb - numd;
Count = LV.getAdapter().getCount() + 1;
Result = (int) result;
A.setText("" + Result);
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float result = 0;
int Result;
Count = LV.getAdapter().getCount() + 1;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
result = numa + numd;
Result = (int) result;
B.setText("" + Result);
ListElementsArrayList.add(" Second term of AP is = " + B.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numb = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(B.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numb = Float.parseFloat(B.getText().toString());
result = numb - numa;
Result = (int) result;
Count = LV.getAdapter().getCount() + 1;
D.setText("" + Result);
ListElementsArrayList.add(" Value of D is = " + D.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float numan = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())
|| TextUtils.isEmpty(AN.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
numan = Float.parseFloat(AN.getText().toString());
result = ((numan - numa) / numd) + 1;
Result = (int) result;
Count = LV.getAdapter().getCount() + 1;
N.setText("" + Result);
ListElementsArrayList.add(" Number of term/terms in this AP is = " + N.getText().toString());
adapter.notifyDataSetChanged();
Collections.reverse(ListElementsArrayList);
}
});
an.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float numa = 0;
float numd = 0;
float numn = 0;
float result = 0;
int Result;
if (TextUtils.isEmpty(A.getText().toString())
|| TextUtils.isEmpty(D.getText().toString())
|| TextUtils.isEmpty(N.getText().toString())) {
return;
}
numa = Float.parseFloat(A.getText().toString());
numd = Float.parseFloat(D.getText().toString());
numn = Float.parseFloat(N.getText().toString());
result = ((numn - 1) * numd) + numa;
Result = (int) result;
AN.setText("" + Result);
Count = LV.getAdapter().getCount() + 1;
ListElementsArrayList.add(" Term/Terms of this AP is = " + AN.getText().toString());
adapter.notifyDataSetChanged();
adapter.getCount();
Collections.reverse(ListElementsArrayList);
}
});
}
}
Just use
List.add(0, element)
to add an element as first element of a list. As described in the documentation.

About the "unfortunately has stopped" error.

I am recently building an app that calculates the mortgage as my school project in Android studio using Java. However, when I try to run the app on my tablet, it keeps crashing and appearing "unfortunately the app has stopped". I wonder what's wrong with my codes, the below are my codes.
This is my controller:
package ca.roumani.mcalc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import hr.YumModel;
public class EntryForum extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_forum);
}
public void buttonClicked(View v)
{
View principleView = findViewById(R.id.principlebox);
EditText principleEdit = (EditText) principleView;
String principle = principleEdit.getText().toString();
View amortizationView = findViewById(R.id.amortizationbox);
EditText amortizationEdit = (EditText) amortizationView;
String amortization = amortizationEdit.getText().toString();
View annualinterestView = findViewById(R.id.interestbox);
EditText annualinterestEdit = (EditText) annualinterestView;
String annualinterest = annualinterestEdit.getText().toString();
MortgageModel model = new MortgageModel(principle, amortization, annualinterest);
String answer = model.computePayment();
((TextView) findViewById(R.id.answer)).setText( "$" + answer);
}
public void yumButton(View v)
{
View principleView = findViewById(R.id.principlebox);
EditText principleEdit = (EditText) principleView;
String principle = principleEdit.getText().toString();
View amortizationView = findViewById(R.id.amortizationbox);
EditText amortizationEdit = (EditText) amortizationView;
String amortization = amortizationEdit.getText().toString();
View annualinterestView = findViewById(R.id.interestbox);
EditText annualinterestEdit = (EditText) annualinterestView;
String annualinterest = annualinterestEdit.getText().toString();
YumModel yumModel = new YumModel();
yumModel.setAmortization(amortization);
yumModel.setInterest(annualinterest);
yumModel.setPrinciple(principle);
String answer2 = yumModel.computePayment();
((TextView) findViewById(R.id.answer2)).setText(answer2);
}
}
The following is my model:
public class MortgageModel
{
private double principle;
private int amortization;
private double annualInterest;
public MortgageModel(String p, String a, String i)
{
this.principle = Double.parseDouble(p);
this.amortization = Integer.parseInt(a);
this.annualInterest = Double.parseDouble(i);
}
public String computePayment()
{
double r = this.annualInterest * 0.01 / 12 ;
double n = this.amortization * 12;
double index1 = 1 + (n * r) + (n * (n-1) * r * r) / 2;
double index2 = 1 - (1 / index1);
double index3 = (r * this.principle) / index2;
String result = String.format("%.d", index3);
return result;
}
}
Does anyone know what's wrong with my code?

how to set the button so as not to force close when empty EditText [duplicate]

getting an error of invalid Double
java.lang.numberformatexception invalid double: ""
what is the reason for this
Activity 1
package com.example.solarcalculator;
import android.os.Bundle;
import android.widget.Button;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
#SuppressLint("UseValueOf")
public class MainActivity extends Activity {
private EditText input1;
private EditText input2;
private EditText input3;
private EditText input4;
private EditText input5;
private MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
input5 = (EditText) findViewById(R.id.input5);
Button button1 = (Button) findViewById(R.id.button1);
input4 = (EditText) findViewById(R.id.input4);
input1 = (EditText) findViewById(R.id.input1);
input2 = (EditText) findViewById(R.id.input2);
input3 = (EditText) findViewById(R.id.input3);
button1.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
private AlertDialog show;
#SuppressLint("UseValueOf")
#Override
public void onClick(View arg0) {
if ( (input4.getText().toString() == " ")
|| (input4.getText().length() ==0) ||
(input5.getText().length() == 0)
|| (input5.getText().toString() == " ")){
show = new AlertDialog.Builder(mContext).setTitle("Error")
.setMessage("Some inputs are empty")
.setPositiveButton("OK", null).show();
}
else if ((input1.getText().length() != 0) &&
(input3.getText().length() ==0) && (input2.getText().length() == 0)){
double w = new Double(input3.getText().toString());
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
float e = 7;
double num = 1000*x;
double den = w*t*e;
double payback = num/den;
double money = w*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else if ((input1.getText().length() == 0) && (input3.getText().length() != 0) &&
(input2.getText().length() != 0)){
double t = new
Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else {
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Activity2
package com.example.solarcalculator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Power extends Activity {
private double money;
private double payback;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.power);
payback = getIntent().getDoubleExtra("payback",0);
money = getIntent().getDoubleExtra("money", 0);
TextView pay = (TextView) findViewById(R.id.textView2);
String payback1 = Double.toString(payback);
pay.setText(payback1);
TextView mon = (TextView) findViewById(R.id.textView4);
String money1 = Double.toString(money);
mon.setText(money1);
}
}
I am getting java.lang.numberformatexception invalid double: "" error in logcat
anyone please help
The reason is, that "" is not a valid double. You need to test the String before or catch such exceptions
double w;
try {
w = new Double(input3.getText().toString());
} catch (NumberFormatException e) {
w = 0; // your default value
}
The value of the double depends on the language of the device.For example, for devices in french the number 0.179927 becomes 0,179927 which will always throw a NumberFormatException when parsing it to double because of the comma.
You need to change the separator from a comma to a point.
You can change the separator either by setting a locale or using the DecimalFormatSymbols.
If you want the grouping separator to be a point, you can use a european locale:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
You should do as below. Put it inside a try catch block
double w = new Double(input3.getText().toString());
Better to also test for .equals("") along with null.
Consider you have an afterTextChanged listener on an EditText. When you back press and clear the entered text, it'll pass != null, but still have "".
This worked for me:
double myDouble;
String myString = ((EditText) findViewById(R.id.editText1)).getText().toString();
if (myString != null && !myString.equals("")) {
myDouble = Double.valueOf(myString);
} else {
myDouble = 0;
}
Basically, you need to test whether the string that you want to convert into double is empty or not.
If it is empty, then you can just initialise it with some value and then proceed further.
For example:
if(myString.isEmpty()){
myString = ""+0.0;
}
double answer = Double.parseDouble(myString);
double latitude;
double longitude;
try {
latitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLatitude());
longitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLongitude());
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=loc:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
} catch (NumberFormatException e) {
// your default value
Toast.makeText(AppointmentsActivity.this, "Invalid location", Toast.LENGTH_LONG).show();
}

Activity crash if there is no entries

I have a problem. When there is entries stats activity works correctly. But If there is NO entries the stast activity crashes.
Please, help me. Need something to prevent it.
(I'm not programmer, so its not easy for me)
package com.sudarmuthu.android.wt.activities;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.sudarmuthu.android.wt.R;
import com.sudarmuthu.android.wt.data.DBUtil;
import com.sudarmuthu.android.wt.data.Entry;
/**
* Activity class to handle stats
*
public class EntriesStatsActivity extends Activity {
// for debugging
private static boolean D = true;
private static String TAG = "WT - EntriesStatsActivity";
private List<Entry> mEntries;
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry_stats);
Bundle bundle = getIntent().getExtras();
int typeId = bundle.getInt("typeId");
if (D) Log.d(TAG, "Got type id: " + typeId);
mEntries = DBUtil.fetchEntries(this, typeId, null);
Entry firstEntry = mEntries.get(0);
int count = mEntries.size();
float sum = 0;
float average = 0;
float min = Float.parseFloat(firstEntry.getValue());
float max = Float.parseFloat(firstEntry.getValue());
// calculate
for (Entry entry : mEntries) {
float value = Float.parseFloat(entry.getValue());
sum += value;
if (value < min) {
min = value;
}
if (value > max) {
max = value;
}
}
average = sum / count;
// populate the values
TextView statsCount = (TextView) findViewById(R.id.statsCount);
statsCount.setText("" + count);
TextView statsSum = (TextView) findViewById(R.id.statsSum);
statsSum.setText("" + sum);
TextView statsAverage = (TextView) findViewById(R.id.statsAverage);
statsAverage.setText("" + average);
TextView valueFrom = (TextView) findViewById(R.id.valueFrom);
valueFrom.setText("" + min);
TextView valueTo = (TextView) findViewById(R.id.valueTo);
valueTo.setText("" + max);
}
}
You may get a null pointer exception :
mEntries = DBUtil.fetchEntries(this, typeId, null);
if( mEntries == null ) {
return;
}
If there is no Entries, mEntries.size() is equals to 0. So when you do
average = sum / count;
You divide by 0, which throws an Arithmetic Exception(you can't divide a number by 0).

Categories

Resources