can't get integer number from EditText - android

Hello I am very new in android
I am trying to get integer value from an EditText, But When I am parsing string to Integer I got NumberFormatException.
Please help me to come out of this error.
thanks in advance.
Program is:
int day,month,year;
EditText expense,ammount;
String[] exp=new String[10];
int[] amt=new int[10];
int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Calendar cal=Calendar.getInstance();
day=cal.get(Calendar.DAY_OF_MONTH);
month=cal.get(Calendar.MONTH)+1;
year=cal.get(Calendar.YEAR);
final TextView txtdate=(TextView)findViewById(R.id.txtdate);
expense=(EditText)findViewById(R.id.exp);
ammount=(EditText)findViewById(R.id.amnt);
final Button add=(Button)findViewById(R.id.btnadd);
final Button cancel=(Button)findViewById(R.id.btncancel);
final Button done=(Button)findViewById(R.id.btndone);
txtdate.setText(day+"/"+month+"/"+year);
add.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
getval();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
clean();
}
});
done.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
total();
getval();
clean();
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(Integer.toString(total()));
}
private int total() {
int total = 0;
// TODO Auto-generated method stub
for(int i=0;i<=count;i++)
{
total+=amt[i];
}
return total;
}
});
}
protected void clean() {
// TODO Auto-generated method stub
expense.setText(" ");
ammount.setText(" ");
}
protected void getval() {
// TODO Auto-generated method stub
final Editable e2=expense.getText();
final Editable e1=ammount.getText();
final int i=Integer.parseInt(e1.toString());
amt[count]=i;
exp[count]=e2.toString();
System.out.println(amt[count]);
System.out.println(exp[count]);
count++;
}
}
Exception is:
java.lang.NumberFormatException: unable to parse ' 600' as integer

Remove any leading or trailing spaces from the number first:
int inputNumber = Integer.parseInt(editText.getText().toString().trim());
Alternatively, you can remove all non-numeric characters from the string using regular expressions:
String cleanInput = editText.getText().toString().replaceAll("[^\\d]", "");
int inputNumber = Integer.parseInt(cleanInput);
Though if non-numeric input characters is a problem you'd probably want to restrict the EditText to numeric only. See this question. It says to add the following attribute to the EditText:
android:inputType="number"

You have a space in your integer.
Add the following attribute to your EditText in your xml to only allow entering integers:
android:inputType="number"

Try this..
final int i=Integer.parseInt(e1.toString().trim());
bacause there is a space before that number see ' 600' that's why that error..
Hope this will help..

use this code
final int f = -1; // or other invalid value
if (edittext.getText().toString().length() > 0)
f = Integer.parseInt(edittext.getText().toString());

Related

Need help to change the textview content on button click

This is my code. In this code I am trying to change the content of four text on a button click on first time and on same button click I am trying to change the content of only three textview. But it's not working.
public class Home_page_Activity extends Activity {
Button next;
int textids[]={R.id.text1,R.id.text2,R.id.text3,R.id.text4};
String Question[]={"1","2","3","4"};
String three[]={"7","27","37"};
TextView t1,t2,t3,t4,t5,t6,t7;
int count=0;
int check=0;
//int button_id[]={R.id.next};
//Button btn[];
int test=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page_);
t1=(TextView)findViewById(R.id.text1);
t2=(TextView)findViewById(R.id.text2);
t3=(TextView)findViewById(R.id.text3);
t4=(TextView)findViewById(R.id.text4);
t5=(TextView)findViewById(R.id.text5);
t6=(TextView)findViewById(R.id.text6);
t7=(TextView)findViewById(R.id.text7);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(test==1)
{
String get=(String) t1.getText();
//int inter=Integer.parseInt(get);
Log.i("t1", get);
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
threetext();
}
nextquestion();
}
});
}
public void nextquestion()
{
t1.setText(Question[count]);
t2.setText(Question[count+1]);
t3.setText(Question[count+2]);
t4.setText(Question[count+3]);
Log.i("count", "value" +count);
test++;
}
public void threetext()
{
Log.i("threetext", "working");
t1.setText(three[check]);
t2.setText(three[check+1]);
t3.setText(three[check+2]);
t4.setText("");
}
Could you increment a counter in the onClick and change the views based on the counter value?

ResourceNotFoundException - String resource ID

07-25 10:15:37.960: E/AndroidRuntime(8661): android.content.res.Resources$NotFoundException: String resource ID #0x7
07-25 10:15:37.960: E/AndroidRuntime(8661): at android.content.res.Resources.getText(Resources.java:230)
Good day to all.
I am trying to display an integer value in a Text View and the above error shows up in LogCat.
There are other similar posts about this issue; like this, this, and this, but none of the solutions worked for me.
Any other ideas of what the problem might be?
Edited for code:
private static Button btnCancel;
private static Button btnConfirm;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtRoomNumber = (EditText)findViewById(R.id.txtRoomNumber);
btnCancel = (Button)findViewById(R.id.btnCancel);
btnConfirm = (Button)findViewById(R.id.btnConfirm);
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
System.exit(0);
}
});
btnConfirm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int rmNo = getRoomNumberValue();
txtTesting.setText(rmNo);
}
});
}
private int getRoomNumberValue()
{
int temp = 0;
try
{
temp = Integer.parseInt(txtRoomNumber.getText().toString());
}
catch(Exception e)
{
e.printStackTrace();
}
return temp;
}
If you are trying to display an integer value in a TextView, use this:
myTextView.setText("" + 1); // Or whatever number
The error happens because TextView has another method: setText(int resid). This method looks for a resource id, which does not exist in your case. Link
You are trying to set the content text of a TextView with an integer value.
The issue is that the method you are using is expecting a resource id.
You need to make a String out of your integer before putting it in the TextView :
textView.setText(Integer.toString(7));
Change your Integer to String
textview.setText(String.valueOf(valueofint));
To convert integer to string use
int x=10;
Integer.toString(x);
That will solve your problem

Retrieve text from edittext to array string in android eclipse

I am making text to voice conversion app. I want to take text from user and change it to voice. when i made input text hard coded. my app works perfectly.
static final String[] texts = {"what's up dude"};
TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.btexttovoice);
b.setOnClickListener(this);
tts = new TextToSpeech(textvoice.this,new TextToSpeech.OnInitListener(){
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status!= TextToSpeech.ERROR)
{
tts.setLanguage(Locale.US);
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(tts!= null)
{
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random();
String random = texts[r.nextInt(3)];
tts.speak(random, TextToSpeech.QUEUE_FLUSH, null);
}
}
it works great but if i want to take input from user through Edit text
i make the following changes:
String[] texts ;
text = (EditText)findViewById(R.id.ttexttovoice);
texts = text.getText().toString();
Here i get error since texts is the array type. How can i get text from edit text to array type of string?
if i do this without array string
String texts ;
text = (EditText)findViewById(R.id.ttexttovoice);
texts = text.getText().toString();
i get no error but i didn't find the desired output. In fact no voice is received.
it seems a simple problem but i am stuck here. kindly help me. Thanks in advance.
String[] texts = new String[3];
text = (EditText)findViewById(R.id.ttexttovoice);
texts[0] = text.getText().toString();

Printing Stuff on Screen in Android

Ok i am developing a cows and bulls game, i am confused how to print messages to the user, i dont want to use dialogs or toasts! As far as i know, the only way is to update textviews , is that the only other option? or can i use something else to display stuff on the screen?
my code till now :
public class Play extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
CowsNBulls();
}
private void CowsNBulls() {
// TODO Auto-generated method stub
int target=0;
final String targetStr = target +"";
boolean guessed= false;
final int guess;
final String Sguess;
System.out.print("Guess a 4-digit number with no duplicate digits");
EditText guess1 = (EditText)findViewById(R.id.etGuess);
Sguess=guess1.getText().toString();
Button ent = (Button) findViewById(R.id.bEnter);
guess= Integer.parseInt(Sguess);
ent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int guesses=0;
int bulls=0;
int cows=0;
if(hasDupes(guess)||guess < 1000){
guesses++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}}}}});
any ideas?
TextView or EditText will be your only possibility. You'd have to attach it to the Layout and maybe even wrap it in a ScrollView to make room for enough statements.

Getting user input from dynamically created views

I've this problem of not being able to get the user input from the second inflated view.
I've upload an picture to this site http://postimage.org/image/b4syhdzrr/
as I'm still not allowed to post images directly on SO.
As you can see, the TextView only displays the top two EditText inputs + calculations, the third input however was not taken into consideration.(The first EditText for numbers is not inflated)
As I'm not sure how many EditText the end user would need.
How should I go about getting user inputs from all of the EditText ?
Here's what I had tried, setting up a SharePreferences to store the user input inside a TextWatcher, inside a OnClickListener, but with this code, the OnClickListener for the Plus button crashes the app even if the TextWatcher is empty.
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
llNewRow = (LinearLayout) findViewById(R.id.llP1AddNewRow);
etNewRow = (EditText) findViewById(R.id.editTextNewRow);
View newRow = View.inflate(BillCalculator1.this,R.layout.newrow, null);
llNewRow.addView(newRow);
TextWatcher input = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
//SharedPreferences here
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
};
}
});
The XML for the inflated view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editTextNewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:hint="Enter new amount">
<requestFocus />
</EditText>
Very new to programming and Android, do let me know if there's any additional information needed, Thank you very much.
I would try another approach to what you're trying to do. I would add a special TextWatcher to the inflated EditText and store the user entered values in an ArrayList. First of all you'll need two extra fields in your class:
private ArrayList<String> mData = new ArrayList<String>(); // this will store the entered values
private static int counter = 0; // to identify the rows
Make a class that implements the TextWatcher interface like this:
public class InputWatcher implements TextWatcher {
private int mRowNumber;
public InputWatcher(int rowNumber) {
mRowNumber = rowNumber;
}
#Override
public void afterTextChanged(Editable s) {
// here you'll add the text as the user enters it in the correct position in the
mData.set(mRowNumber, s.toString());
}
}
Then:
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
mData.clear();
counter = 0;
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
// I sure hope that you have the Buttons with the id button1Add and buttonP1GST in the layout that you inflate
// otherwise the code will throw a NullPointerException when you use them below
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// add an entry in the data holder for this row
mData.add("");
View newRow = View.inflate(BillCalculator1.this,
R.layout.newrow, null);
EditText justAdded = (EditText) newRow
.findViewById(R.id.editTextNewRow);
justAdded.addTextChangedListener(new InputWatcher(counter));
ll.addView(newRow);
counter++;
}
});
When it's time to calculate the total, in a Button's OnClickListener, just do:
#Override
public void onClick(View v) {
int storedSize = mData.size();
int sum = 0;
for (int i = 0; i < storedSize; i++) {
sum += Integer.parseInt(mData.get(i).equals("") ? "0"
: mData.get(i));
}
Toast.makeText(getApplicationContext(), "Total" + sum, Toast.LENGTH_SHORT).show();
}
From your picture I didn't understand if you already start with one EditText in the layout(the one to the left of the + Button). If this is the case then you would have to manually set the InputWatcher to it and move the counter incrementation before adding the InputWatcher where you add the rows.

Categories

Resources