Improper data type in Android TextView

Improper data type in Android TextView

Mar 17, 2013
android

Identifying the problem #

One of the common mistakes done by Android programmers is using improper data type in TextView. Let’s have a look on a simple code snippet:

int area;
TextView sampleTextView = (TextView) findViewById(R.id.myTextViewInXml);
sampleTextView.setText(area + " km");

Here, we simply set a value of the text in an exemplary TextView and append string value " km” at the end. It can be used with SeekBar. For example, when we change value of the SeekBar, we can also update value of the text inside the TextView. Let’s have a look on another example:

int area;
TextView sampleTextView = (TextView) findViewById(R.id.myTextViewInXml);
sampleTextView.setText(area);

Here, we don’t append string value " km” at the end. In such case, our application will crash. We have to remember, that Java is strongly typed language and we have to take care about data types. In previous example, we had a cast to the String type, because we appended String value at the end. In the second example, we have only int value, but argument for setText method must be in type of String. Method named setText accepts integer values as well and in such case, it will try to find resource with a specified integer identifier generated with R.java file. Resource won’t be found and application will crash. We can quickly fix this bug by casting argument of the method to the String type.

Solving the problem #

There are at least two ways of solving this problem:

Solution no. 1

int area;
TextView sampleTextView = (TextView) findViewById(R.id.myTextViewInXml);
sampleTextView.setText(Integer.toString(area));

Solution no. 2

int area;
TextView sampleTextView = (TextView) findViewById(R.id.myTextViewInXml);
sampleTextView.setText(area + "");