Wednesday, January 21, 2015

java - How to convert string to int to string

activity_main.xml code snippet

<TextView
 android:id="@+id/text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="0"
 android:textSize="75sp"
 android:textColor="#ff0000"
 >
</TextView>
<Button
 android:id="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Convert Now"
 android:onClick="perform_action"
 android:textSize="20sp"
 >
</Button>
MainActivity.java code snippet

public void perform_action(View v)
{
 /*
  the following example code demonstrate us
  how can we convert integer value string and
  how can we also convert string to integer value
  */

 TextView tv = (TextView) findViewById(R.id.text_view);

 //get the textview text as String variable
 String tv_text = tv.getText().toString();

 //convert string to integer value
 int tv_number = Integer.parseInt(tv_text);

 //add 1 with current textview text
 int numberOfClick = tv_number+1;

 //convert the number to string
 //String tv_new_text = Integer.toString(numberOfClick);

 //another way to convert the integer value to string
 //String tv_new_text = String.valueOf(numberOfClick);

 //another way to convert the integer value to string
 String tv_new_text = numberOfClick + "";

 //finally the textview will display the button's number of click
 tv.setText(tv_new_text);
}
Imported Class

import android.view.View;
import android.widget.TextView;
More android examples