TextViews to Array of Doubles in Android: IllegalStateException, InvocationTargetException and NumberFormatException

时间:2015-08-07 02:19:54

标签: android textview type-conversion double

I'm building a simple app to calculate expenses and cost of living and provide smart living recommendations.

The app requests each expense as a textview, then when a button is clicked, it goes through the textviews, parses them as doubles and assigns them to a public value.

Here is my code:

package ericleeconklin.costoflivingcalculator;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;


public class EnterExpenses extends ActionBarActivity {

    public Double rentMortgage;
    public Double utilities;
    public Double insurance;
    public Double phoneInternet;
    public Double food;
    public Double carPayment;
    public Double miscellaneous;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_expenses);
    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_enter_expenses, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void enterExpenses(View view) {
    try {
        TextView rentView = (TextView) findViewById(R.id.enterRent);
        TextView utilitiesView = (TextView) findViewById(R.id.enterUtilities);
        TextView insuranceView = (TextView) findViewById(R.id.enterInsurance);
        TextView phoneView = (TextView) findViewById(R.id.enterTV);
        TextView foodView = (TextView) findViewById(R.id.enterFood);
        TextView carView = (TextView) findViewById(R.id.enterCarPayment);
        TextView miscView = (TextView) findViewById(R.id.enterMisc);

        Double[] doubleExpensesArray = new Double[]{Double.parseDouble(rentView.toString()),
                Double.parseDouble(utilitiesView.toString()),
                Double.parseDouble(insuranceView.toString()),
                Double.parseDouble(phoneView.toString()),
                Double.parseDouble(foodView.toString()),
                Double.parseDouble(carView.toString()),
                Double.parseDouble(miscView.toString())};

            rentMortgage = doubleExpensesArray[0];
            utilities = doubleExpensesArray[1];
            insurance = doubleExpensesArray[2];
            phoneInternet = doubleExpensesArray[3];
            food = doubleExpensesArray[4];
            carPayment = doubleExpensesArray[5];
            miscellaneous = doubleExpensesArray[6];
            Intent myIntent = new Intent(this, FinalGrade.class);
            startActivity(myIntent);

    } catch(NullPointerException nullPointer) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please enter valid amounts!")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //do things
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}
}

And my XML:

<ScrollView
android:layout_width="fill_parent"
android:id="@+id/scrollView"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Enter Your Monthly Expenses (USD)"
        android:id="@+id/textView"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:textAlignment="center"/>

    <EditText android:id="@+id/enterRent"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="100dp"
              android:layout_centerHorizontal="true"
              android:ellipsize="end"
              android:singleLine="true"
              android:textColorHint="#888888"
              android:hint="Enter Rent/Mortgage">
    </EditText>

    <EditText android:id="@+id/enterUtilities"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="160dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter Utilities">
    </EditText>

    <EditText android:id="@+id/enterInsurance"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="220dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter Insurance">
    </EditText>

    <EditText android:id="@+id/enterTV"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="280dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter TV/Phone/Internet">
    </EditText>

    <EditText android:id="@+id/enterFood"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="340dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter Food">
    </EditText>

    <EditText android:id="@+id/enterCarPayment"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="400dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter Car Payment">
    </EditText>

    <EditText android:id="@+id/enterMisc"
              android:layout_width="210dp"
              android:layout_height="wrap_content"
              android:padding="3dip"
              android:layout_marginTop="460dp"
              android:layout_centerHorizontal="true"
              android:inputType="number"
              android:textColorHint="#888888"
              android:hint="Enter Miscellaneous">
    </EditText>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Grade My Cost of Living"
        android:id="@+id/enterExpenses"
        android:layout_marginTop="520dp"
        android:layout_centerHorizontal="true"
        android:onClick="enterExpenses"/>




</RelativeLayout>
</ScrollView>

3 个答案:

答案 0 :(得分:2)

First, your XML shows only 1 TextView and the rest are EditTexts, So in your activity code will need to reflect the right object type for the id's your finding on the view.

EditText rentView = (EditText) findViewById(R.id.enterRent);
EditText utilitiesView = (EditText) findViewById(R.id.enterUtilities);
EditText insuranceView = (EditText) findViewById(R.id.enterInsurance);
EditText phoneView = (EditText) findViewById(R.id.enterTV);
EditText foodView = (EditText) findViewById(R.id.enterFood);
EditText carView = (EditText) findViewById(R.id.enterCarPayment);
EditText miscView = (EditText) findViewById(R.id.enterMisc);

Second, you must use getText().toString() on the EditTexts in order to get the text value from them. See the documentation on EditText.

Double value = Double.parseDouble(carView.getText().toString());

Then if you wanting to send this your Double[] over an Intent to the Final activity, you would do it like this.

Intent intent = new Intent(EnterExpenses.this, FinalGrade.class);
Bundle bundle = new Bundle();
bundle.putDoubleArray("your_double_key", doubleExpensesArray);
intent.putExtras(bundle);
startActivity(intent);

and would receive the double in the "FinalGrade.class" like so:

Bundle bundle = this.getIntent().getExtras();
Double[] double = bundle.getDoubleArray("your_double_key");

* You could try this *

I'd also personally set up my Button click listeners in my activity code like such instead of in XML android:onClick=""/>. This might help your issue.

Button calculate = (Button) findViewById(R.id.button).
       calculate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick() {
            enterExpenses();
        }
    });

答案 1 :(得分:1)

you are wrong in these lines

double[] doubleExpensesArray = new double[]{Double.parseDouble(rentView**.getText().**toString()),
            Double.parseDouble(utilitiesView.**.getText().**toString()),
            Double.parseDouble(insuranceView.**.getText().**toString()),
            Double.parseDouble(phoneView.**.getText().**toString()),
            Double.parseDouble(foodView.**.getText().**toString()),
            Double.parseDouble(carView.**.getText().**toString()),
            Double.parseDouble(miscView.**.getText().**toString())};

答案 2 :(得分:0)

You should first get the text of the TextView before parsing all the doubles

Double.parseDouble(utilitiesView.toString()), // that's wrong
Double.parseDouble(utilitiesView.getText().toString()), // that's right

and so on to all the TextViews.