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).
Related
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
}
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?
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();
}
So, I have a spinner, populated with ~35 values. If I select, say, the fifth item, then when it is selected, it does what it is supposed to do (populate a second spinner). My problem is that shortly afterwards (<1/2 second) it reverts the values in the second spinner to what they would be if option 1 in the first spinner were selected. The fifth item in the first spinner is still selected but it acts as though the first item gets selected twice per second.
I've tried everything I could find on this (barely anything) and nothing has worked so far. This basically has me stuck on going further in my app.
Entire Code:
package com.nicotera.colton.londontransitguide;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.*;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class RoutesActivity extends Activity implements OnItemSelectedListener {
Spinner dirSpinner;
Spinner routeSpinner;
static String [] namedDirections = new String [2];
private static final String TAG = "RoutesActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routes);
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner = (Spinner) findViewById(R.id.route_name_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.routes_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner
routeSpinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "Item selected");
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
}
public void directionSpinner (String directions []) {
int temp;
for (int i = 1; i <=2; i++)
{
temp = Integer.parseInt(directions[i]);
if (temp == 1)
namedDirections[(i-1)] = "Eastbound";
else if (temp == 2)
namedDirections[(i-1)] = "Northbound";
else if (temp == 3)
namedDirections[(i-1)] = "Southbound";
else if (temp == 4)
namedDirections[(i-1)] = "Westbound";
}
//setContentView(R.layout.activity_routes);
dirSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add(namedDirections[0]);
adapter.add(namedDirections[1]);
dirSpinner.setAdapter(adapter);
Log.i(TAG, "spinner populated");
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
class MyInnerClass extends AsyncTask<String, Void, String> {
String [] directions = new String [3];
String [] directionNames = new String [3];
private static final String TAG = "RoutesActivity";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
RoutesActivity.this.directionSpinner(directions);
}
#Override
protected String doInBackground(String... params) {
try{
Pattern routeDirPattern = Pattern.compile("\\&d=(\\d{1,2})");
Connection conn = Jsoup.connect(params[0]);
Document doc = conn.get();
int i = 0;
Elements routeLinks = doc.select("a[href]");
for (Element routeLink : routeLinks) {
i = (i + 1);
String name = routeLink.text();
Attributes attrs = routeLink.attributes();
String href = attrs.get("href");
Matcher m = routeDirPattern.matcher(href);
if (m.find()) {
String number = m.group(1);
directions [i] = number;
directionNames [i] = name;
Log.i(TAG, directionNames [i]);
}
}
}catch(Exception e){Log.d("doinbackground exception", e.toString());}
return ("Done");
}
}
}
I was using the same onselected listener for both without an if statement to check which one was clicked so it just thought that the first one was clicked.
This is the corrected code:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Spinner spnr = (Spinner) parent;
Log.i(TAG, "Item selected");
switch(parent.getId()) {
case R.id.route_name_spinner:
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
case R.id.route_direction_spinner:
}
}
I have a function which is supposed to return an object of arraylists but for some reason it gets stuck in the return statement. Everything before the return statement is working. I had an error where the ArrayLists only contained a single value which makes the function work, but of course returns the wrong data.
package com.burninglobster.TP;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
public class Chart2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Object graphdata[] = graphsetup();
Log.d("This message is NOT shown", "");
List<Double> distances = (List<Double>) graphdata[0];
List<Double> accall = (List<Double>) graphdata[1];
List<Double> accdir = (List<Double>) graphdata[2];
List<Double> accdist = (List<Double>) graphdata[3];
List<Double> meandir = (List<Double>) graphdata[4];
List<Double> meandist = (List<Double>) graphdata[5];
linegraph lgraph = new linegraph();
setContentView(R.layout.splot);
LinearLayout layout1 = (LinearLayout) findViewById(R.id.splot2);
layout1.addView(lgraph.getView1(this, distances, accall));
LinearLayout layout2 = (LinearLayout) findViewById(R.id.splot3);
layout2.addView(lgraph.getView2(this, distances, accdir, meandir));
LinearLayout layout3 = (LinearLayout) findViewById(R.id.splot4);
layout3.addView(lgraph.getView2(this, distances, accdist, meandist));
}
public Object[] graphsetup() {
SharedPreferences rprefs;
rprefs = getSharedPreferences("com.burninglobster.TP.tprefs",
Context.MODE_WORLD_READABLE);
double setdist = rprefs.getFloat("setdist", 0);
String[] sourcesarray = rprefs.getString("sourcesarray", "Standarddef")
.split(",");
String setdisc = sourcesarray[rprefs.getInt("spindiscpos", 0)];
DBHelper dbHelper = new DBHelper(Chart2Activity.this);
SQLiteDatabase db;
db = dbHelper.getReadableDatabase();
String graphquery = "SELECT " + DBHelper.SHOOTER + "," + DBHelper.WDIR
+ "," + DBHelper.WSTR + "," + DBHelper.SMOD + ","
+ DBHelper.DIST + "," + DBHelper.R_DIST + ","
+ DBHelper.OS_DIST + " FROM " + DBHelper.TABLE + " WHERE "
+ DBHelper.SHOOTER + "='" + setdisc + "'" + " ORDER BY "
+ DBHelper.DIST;
Cursor graphcursor = db.rawQuery(graphquery, null);
int rows = graphcursor.getCount();
int ishooter = graphcursor.getColumnIndex(DBHelper.SHOOTER);
int iwdir = graphcursor.getColumnIndex(DBHelper.WDIR);
int iwstr = graphcursor.getColumnIndex(DBHelper.WSTR);
int ismod = graphcursor.getColumnIndex(DBHelper.SMOD);
int idist = graphcursor.getColumnIndex(DBHelper.DIST);
int irdist = graphcursor.getColumnIndex(DBHelper.R_DIST);
int iosdist = graphcursor.getColumnIndex(DBHelper.OS_DIST);
List<Double> accall = new ArrayList<Double>();
List<Double> accdir = new ArrayList<Double>();
List<Double> meandir = new ArrayList<Double>();
List<Double> accdist = new ArrayList<Double>();
List<Double> meandist = new ArrayList<Double>();
List<Double> accdirtemp = new ArrayList<Double>();
List<Double> accdisttemp = new ArrayList<Double>();
List<Double> distances = new ArrayList<Double>();
double dalla = 0;
double ddira = 0;
double ddista = 0;
double ddirm = 0;
double ddistm = 0;
double currentdist = 0;
graphcursor.moveToFirst();
if (rows > 0) {
currentdist = graphcursor.getDouble(idist);
}
for (int i = 0; i < rows; i++) {
// REMOVED ERROR CAUSING SINGLE VALUE IN ARRAYLISTS:
// currentdist=graphcursor.getDouble(idist);
if (graphcursor.getDouble(idist) < (currentdist + 5)) {
accdirtemp.add(graphcursor.getDouble(irdist));
accdisttemp.add(graphcursor.getDouble(iosdist));
} else {
for (int u = 0; u < accdirtemp.size(); u++) {
ddira += Math.pow(accdirtemp.get(u), 2);
ddista += Math.pow(accdisttemp.get(u), 2);
dalla += Math.pow(accdirtemp.get(u), 2)
+ Math.pow(accdisttemp.get(u), 2);
ddirm += accdirtemp.get(u);
ddistm += accdisttemp.get(u);
}
accall.add(Math.sqrt(dalla / accdirtemp.size()));
Double.toString(Math.sqrt(dalla / accdirtemp.size())));
accdir.add(Math.sqrt(ddira / accdirtemp.size()));
accdist.add(Math.sqrt(ddista / accdirtemp.size()));
meandir.add(ddirm / accdirtemp.size());
meandist.add(ddistm / accdirtemp.size());
distances.add(currentdist);
dalla = 0;
ddira = 0;
ddirm = 0;
ddista = 0;
ddistm = 0;
currentdist = graphcursor.getDouble(idist) + 5;
accdirtemp.clear();
accdisttemp.clear();
accdirtemp.add(graphcursor.getDouble(irdist));
accdisttemp.add(graphcursor.getDouble(iosdist));
}
graphcursor.moveToNext();
}
for (int u = 0; u < accdirtemp.size(); u++) {
ddira += Math.pow(accdirtemp.get(u), 2);
ddista += Math.pow(accdisttemp.get(u), 2);
dalla += Math.pow(accdirtemp.get(u), 2)
+ Math.pow(accdisttemp.get(u), 2);
ddirm += accdirtemp.get(u);
ddistm += accdisttemp.get(u);
}
accall.add(Math.sqrt(dalla / accdirtemp.size()));
accdir.add(Math.sqrt(ddira / accdirtemp.size()));
accdist.add(Math.sqrt(ddista / accdirtemp.size()));
meandir.add(ddirm / accdirtemp.size());
meandist.add(ddistm / accdirtemp.size());
distances.add(currentdist);
db.close();
dbHelper.close();
Log.d("This message", " is shown");
return new Object[] { distances, accall, accdir, accdist, meandir,
meandist };
}
}
I have a similar function that works just fine and I can't see the difference:
package com.burninglobster.TP;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
public class ChartActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Object plotdata[] = plotsetup();
Log.d("This message", " is also shown");
List<Double> rd1 = (List<Double>) plotdata[0];
List<Double> osd1 = (List<Double>) plotdata[1];
List<Double> rd2 = (List<Double>) plotdata[2];
List<Double> osd2 = (List<Double>) plotdata[3];
List<Double> rd3 = (List<Double>) plotdata[4];
List<Double> osd3 = (List<Double>) plotdata[5];
scatterplot plot = new scatterplot();
setContentView(R.layout.tplot);
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
layout.addView(plot.getView(this, rd1, osd1, rd2, osd2, rd3, osd3));
}
public Object[] plotsetup() {
SharedPreferences rprefs;
rprefs = getSharedPreferences("com.burninglobster.TP.tprefs",
Context.MODE_WORLD_READABLE);
double setdist = rprefs.getFloat("setdist", 0);
String[] sourcesarray = rprefs.getString("sourcesarray", "Standarddef")
.split(",");
String setdisc = sourcesarray[rprefs.getInt("spindiscpos", 0)];
DBHelper dbHelper = new DBHelper(ChartActivity.this);
SQLiteDatabase db;
db = dbHelper.getReadableDatabase();
String plotquery = "SELECT " + DBHelper.SHOOTER + "," + DBHelper.WDIR
+ "," + DBHelper.WSTR + "," + DBHelper.SMOD + ","
+ DBHelper.DIST + "," + DBHelper.R_DIST + ","
+ DBHelper.OS_DIST + " FROM " + DBHelper.TABLE;
Cursor plotcursor = db.rawQuery(plotquery, null);
int ishooter = plotcursor.getColumnIndex(DBHelper.SHOOTER);
int iwdir = plotcursor.getColumnIndex(DBHelper.WDIR);
int iwstr = plotcursor.getColumnIndex(DBHelper.WSTR);
int ismod = plotcursor.getColumnIndex(DBHelper.SMOD);
int idist = plotcursor.getColumnIndex(DBHelper.DIST);
int irdist = plotcursor.getColumnIndex(DBHelper.R_DIST);
int iosdist = plotcursor.getColumnIndex(DBHelper.OS_DIST);
int rows = plotcursor.getCount();
List<Double> rd1 = new ArrayList<Double>();
List<Double> osd1 = new ArrayList<Double>();
List<Double> rd2 = new ArrayList<Double>();
List<Double> osd2 = new ArrayList<Double>();
List<Double> rd3 = new ArrayList<Double>();
List<Double> osd3 = new ArrayList<Double>();
plotcursor.moveToFirst();
int disccount = 0;
int array1 = 0;
int array2 = 0;
int array3 = 0;
double cursordist;
for (int i = 0; i < rows; i++) {
if (plotcursor.getString(0).equals(setdisc)) {
cursordist = plotcursor.getDouble(idist);
if (cursordist > (setdist - 5) && cursordist < (setdist + 5)) {
rd1.add(plotcursor.getDouble(irdist));
osd1.add(plotcursor.getDouble(iosdist));
array1++;
} else if (cursordist > (setdist)
&& cursordist < (setdist + 10)) {
rd2.add(plotcursor.getDouble(irdist));
osd2.add(plotcursor.getDouble(iosdist));
array2++;
} else if (cursordist > (setdist - 10)
&& cursordist < (setdist)) {
rd3.add(plotcursor.getDouble(irdist));
osd3.add(plotcursor.getDouble(iosdist));
array3++;
}
disccount++;
}
plotcursor.moveToNext();
}
db.close();
dbHelper.close();
Log.d("This message", " is shown");
return new Object[] { rd1, osd1, rd2, osd2, rd3, osd3 };
}
}
I added a 'Log.d' just before the return statement and then another just after the function call in the activity and only the first one is shown. It freezes for ½-1 minute and then shows the dialogue to wait or kill. I don't know how to get more info on the problem. Suggestions?
Don't know what the problem is, and you will have to explain "stuck in the return statement". Code does not simply get "stuck".
But you will help yourself a lot of you break the problem up.
For example, if you created a class and handled instances of the class rather than untyped arrays of objects, your code would be much easier to write, much easier to debug and much easier to maintain. Doing so will also enable the compiler to catch a lot of errors before you need to ask for help :)
Whenever you are tempted to use 'Object', you should stop and question yourself. Of course, there are times when Object is useful and times when you have no choice but they are exceptional and should only be done for good reason - not because you haven't taken the time to think of a correct solution.
You should also choose better names for your variables and use proper Java naming conventions. Here, I've named the object Thing because your code does not give proper clues as to what dalla, ddira, ddista etc are and how the relate to each other, either in comments or code (which is a bad thing - this code might only ever be seen by you but when you come back in a year, you will wish that you'd done these things).
For example:
class Thing{
double dalla = 0;
double ddira = 0;
double ddista = 0;
double ddirm = 0;
double ddistm = 0;
double currentdist = 0;
}
Then, in your loops or methods or whatever,
ArrayList<Thing> things = new ArrayList<Thing>();
...
Thing thing = new Thing();
for (int u = 0; u < accdirtemp.size(); u++) {
thing.ddira += Math.pow(accdirtemp.get(u), 2);
thing.ddista += Math.pow(accdisttemp.get(u), 2);
thing.dalla += Math.pow(accdirtemp.get(u), 2)
+ Math.pow(accdisttemp.get(u), 2);
thing.ddirm += accdirtemp.get(u);
thing.ddistm += accdisttemp.get(u);
}
things.add(thing);
...
And so on. Take the time now to refactor your code before it becomes even more of a nightmare to read.
OK, so I'm feeling quite stupid for posting this and wasting coders' time!!
My problem was to be found elsewhere. The real problem was, that I was using Log.d wrong. If the text string is empty, it seems that it doesn't get sent to the log:
Log.d("This return","something") ; Log.d("This returns nothing","") :S log.d