Reputation: 732
I'm new to android and Java, and I have to design a simple application that reads an amount and shows a 10 percent of this amount in a toast. This is my code:
activity_main.xml:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/amount"
android:hint="Bill amount in L.L"
android:layout_marginTop="53dp"
android:layout_below="@+id/text"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:inputType="number"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10%"
android:id="@+id/button"
android:layout_below="@+id/amount"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:onClick="tenp"/>
MainActivity.java:
public void tenp(View view1) {
EditText e = (EditText) findViewById(R.id.amount);
double amount = Double.parseDouble(e.getText().toString());
double res = (amount / 100.0f) * 10;
Toast.makeText(getApplicationContext(), "" +res, Toast.LENGTH_SHORT).show();
}
When I run my app and click on the 10% button, the app closes. I don't know what is my error here. please help.
Upvotes: 3
Views: 32759
Reputation: 5227
Your code is fine except for the handling the invalid parsing of double. You can modify your code for the invalid parsing of double as-
public void tenp(View view1) {
EditText e = (EditText) findViewById(R.id.amount);
if (!e.getText().toString().equals("")) {
double amount = Double.parseDouble(e.getText().toString());
double res = (amount / 100.0f) * 10;
Toast.makeText(getApplicationContext(), "" + res, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Amount cannot be empty", Toast.LENGTH_SHORT).show();
}
}
Upvotes: 20