Android : empty Edit Text gives me error for 0 value

on Saturday, August 2, 2014


I'm developing a project and I have problem with my addition for empty EditText( unused) . If I enter a number in my editText then click the button it will show the output in the viewtext (which is right) also if you keep doing that the number will be added to the total number .


BUT !! if I click the button without enter any number in my edittext . the project will be crashed showing the project has stopped !


What I want is : if I just click the button without enter any number the 0 will be added to the total number . ex.. 5 >> Button >> 5+0=5 show 5 for total >> 6 >> Button >> 6 + 5= 11 >> 0 >> Button >> 0 + 11 = 11 (<< KEY)


My code



MyActivity.java

package b3du.im.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class MyActivity extends ActionBarActivity {


int total = 0;

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

public void Add(View v){

TextView text1 = (TextView) findViewById(R.id.text1);
EditText text2 = (EditText) findViewById(R.id.text2);


int valueText2 = Integer.parseInt(text2.getText().toString());

total= Integer.parseInt(text1.getText().toString());

total += valueText2;

text1.setText(Integer.toString(total));

text2.setText("");

}

}


activity_my.xml



<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
>

<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="@+id/text1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="0"
android:textSize="30dp"
android:gravity="center" />

<EditText
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/text2"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:hint="0"
android:gravity="center" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:onClick="Add" />
</LinearLayout>

0 comments:

Post a Comment