I'm trying to create a for
-loop to add views to a layout. The for
-loop is working fine (I tried it with initialized variables) but I need to get an integer from an EditText
. I used a try-catch
and LogCat tells me the following...
java.lang.NumberFormatException: invalid int "".
The website developers.android.com says this is from incorrectly converting a string to an integer, but I don't understand how I could be incorrectly getting the data from the EditText
.
This is my code...
public class UserPref2Activity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText numSensors = (EditText) findViewById(R.id.num_sensors);
String change = numSensors.getText().toString();
int i = Integer.parseInt(change);
int j; //iterates through the for loop
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
for(j=1;j<i;j++)
{
EditText name = new EditText(this);
name.setText("Name:");
EditText type = new EditText(this);
type.setText("Type:");
EditText bits = new EditText(this);
bits.setText("Bits:");
ll.addView(name);
ll.addView(type);
ll.addView(bits);
}
this.setContentView(sv);
}
catch (Exception e)
{
//sends actual error message to the log
Log.e("ERROR", "ERROR IN CODE:" + e.toString());
//prints out location of error
e.printStackTrace();
}
}
}
And this is my XML file...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/userLayout" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter number of sensors:" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="@+id/num_sensors" />
If you try to parse empty string it will always throw
NumberFormatException
.Change your code to following.