I'm trying to write my first Android app. It will take a number input by a user in an EditText field, convert it to an integer, then find the factors. I want to port this from a Java program that I wrote before. I have stubs working to the point that I have a UI, but I haven't yet ported the code that will find the factors. I'm stuck trying to convert the EditText to an integer. If I insert either of the following lines, the program crashes in the emulator. Log.Cat says, "Caused by NumberFormatExcepion: Unable to parse '' as an integer."
Any suggestions are appreciated.
userNumber is the name of the value taken from the EditText field, and the EditText field is also named userNumber. I don't know if that's bad form or not. I want to assign the value of userNumber to the integer value userInt. userInt will then be factored.
Either of these approaces will cause the problem:
userNumber = (EditText) findViewById(R.id.userNumber);
userInt = Integer.parseInt(userNumber.getText().toString());
Integer userInt = new Integer(userNumber.getText().toString());
The EditText block of XML looks like this:
<EditText
android:id="#+id/userNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
Here is the relevant code from the class:
public class AndroidFactoringActivity extends Activity {
// Instance Variables
EditText userNumber;
Button factorButton;
TextView resultsField;
int factorResults = 1;
int userInt = 0; // This comes out if using Integer userInt
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultsField = (TextView) findViewById(R.id.resultsField);
factorButton = (Button) findViewById(R.id.factorButton);
userNumber = (EditText) findViewById(R.id.userNumber);
// userNumber is also the name of the EditText field.
// userInt = Integer.parseInt(userNumber.getText().toString());
// Integer userInt = new Integer(userNumber.getText().toString());
resultsField.append("\n" + String.valueOf(userInt));
//Later, this will be factorResults, not userInt.
// Right now, I just want it to put something on the screen.
}
}
You're trying to parse the int in your onCreate method, which occurs before the user has a chance to enter anything into the EditText. Hence the exception from trying to parse an empty string.
You'll have to either make a button to press, which will then parse the int out of the EditText, or attach a listener to the EditText that will parse it when something is typed into it.
Related
The app crashes when the button is selected which uses the values converted from edit texts. Tried multiple ways to move the part edittext = R.ids .. to try and make sure the edittexts picks new values after the oncreate first runs.
Think the calculation part causes the crash because its trying to perform a calculation with stored values from the edit text when the value is false from the first time the edit text gets the R.ids... in the onCreate method.
needed hide/display editText based off a radio button setonCheckedChangeListener in the onCreate method. So edittext = R.ids .. set in this method, the app does not crash at runtime like it would if I moved the edittext = R.ids .. to the testFunction method.
EditText editTextValue;
EditText editTextValue2;
double amount;
protected void onCreate(){...
//Get edittext field parameters
editTextValue = (EditText) findViewById(R.id.editText_weight_kg);
//listener to switch editTexts on which radio button selected in units group
unitsRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.imperial) {
editTextValue2.setVisibility(View.VISIBLE);
editTextValue.setVisibility(View.GONE);
}
void testFunction(View view){
String stringValue = editTextValue..getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
}
but now when I run the app I get this error in the long cat
enter image description here
E/ClipboardServiceEx﹕ clipEx is android.sec.clipboard.ClipboardExManager#1f70b420
E/ClipboardServiceEx﹕ clipEx has text data : false
here is the xml for one of the edit texts
<EditText
android:id="#+id/editText_weight_lb"
style="#style/EditTextViewStyle"
android:visibility="visible"/>
In the editTextStyle , I set the textCursorDrawable to null to try and have different colors for the pointer and underline colors. Not sure if this could also be affecting the editTextView storing the value
<item name="android:textCursorDrawable">#null</item>
I also tried setting edittext = R.ids in the testfunction and in the onCreate method. See if the editTexts would store the values the user enters rather than keeping the empty values when onCreate initially run.
I still got the same clipEx has text data:false error after trying this.
I searched the logcat error "clipEx has text data: false" and found something regarding samsung memory leaks.
https://github.com/square/leakcanary/issues/133
I am using a samsung galaxy for testing. I feel the issue is more with where I'm setting the edittexts to the R.ids thats causing the issue.
I saw the post for checking to make sure valid value entered for edittext.
Issue with empty EditText
How to Check whether a value is entered in editexts before submitting?
will add the check after finding out why values are not getting stored/ still remaining false.
Thanks
well I tried a different approach to implement the method.
I placed a button in the OnCreate method to define the event handlers against the buttons:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
String stringValue = editTextValue.getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
.....
.....
}
}
By using the button method in the OnCreate, when I ran the app, errors would actually come up on the Integer.parseInt() method call. Turns out that even though the editTexts that I was entering text for did not have text values, the other editTexts still had strings for the text, so this would cause the app to crash.
<EditText...
android:text="kg"/>
I took out the text values. It worked again.
I also took out this line in the style sheet for the editText. This was to change the editText border color, cursor color, or line.
<item name="android:textCursorDrawable">#null</item>
I tried the public void testFunction() approach which I had used before, the app works, but the clipEx has text data : false continues to show up.
But the app works now with either the Button method in onCreate or as a public void testFunction() approach.
I want to setText in EditView but it will error. I dont know why.
This is on OnCreate function.
name = (EditText) findViewById(R.id.input_name);
String editname = String.valueOf(getName());
MessageTo.message(this,editname);
name.setText(editname);
The string i will set in EditText name.
public String getName(){
int id = 1;
String data=dbhandler.getName(id);
return data;
}
If i remove this code from the OnCreate function
name.setText(editname);
It will have no error. The MessageTo.message code is where it pops a dialog of the String editname. It will show the String editname.
So i put back the code and change it into this code,
name.setText("testing");
But it still won't work.
I dont know why though. All other sources have EditText.setText("String") as how to setText in EditText but it won't work in my case.
LOGCAT ERROR:
09-20 21:00:36.677 1436-1436/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.organizer/com.organizer.ManageProfileActivity}: java.lang.NullPointerException
Your EditText name appears to be null. In your onCreate method, make sure you are calling setContentView(R.layout.YOUR_LAYOUT) where the layout parameter is an XML layout containing your EditText with the ID R.id.input_name.
You assign it later on with
name = (EditText) findViewById(R.id.input_name);
but if the layout does not contain this ID, name will be null, thus causing your error.
It is correct that you should be using the setText() method on the EditText.
Everything looks correct in terms of your codes, so I would suggest to check for the following things:
Are you calling setText anywhere else?
Is the id of your EditText correct (Is the id of your EditText input_name)
Are you sure you are looking at the right activity.
Are you initializing your name variable in the right scope? (Outside the onCreate Method)
Declare the EditText in the xml file
Find the EditText in the activity
Set the text in the EditText
And If you check the docs for EditText, you'll find a setText() method. It takes in a String and a TextView.BufferType. For example:
EditText editText = (EditText)findViewById(R.id.edit_text);
editText.setText("Google is your friend.", TextView.BufferType.EDITABLE);
Or
Use +, the string concatenation operator:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);
or
String.valueOf(int):
ed.setText(String.valueOf(x));
I have entered values in my text field, But the debugger shows null value.
The text id's are correct yet no value is being printed.
The log cat is showing null pointer exception. I have declared all the variables in the class.
The edit text string functions are declared in the method itself.
et1 = (EditText)findViewById(R.id.editText1);
et2 = (EditText)findViewById(R.id.editText2);
et3 = (EditText)findViewById(R.id.editText3);
et4 = (EditText)findViewById(R.id.editText4);
et5 = (EditText)findViewById(R.id.editText5);
set1 = et1.getText().toString();
set2 = et2.getText().toString();
set3 = et3.getText().toString();
set4 = et4.getText().toString();
set5 = et5.getText().toString();
System.out.println("set1 ="+set1);
System.out.println("set2 ="+set2);
All values given input are showing null and these are the few values that are being declared in the xml.
I need to know what mistake i am doing and how to rectify it.
i have initialized the values after setContent the data access happens in button on click listener... i didnt want to post the entire code.. –
I think your problem is same as this question.
You are directly accesssing the EditText's value after initializtion of EditText. You should accept the value on some event like onClick.
Let me Explain,
public class MainActivity extends Activity
{
EditText editText;
#Override
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById ( R.id.firstEditText );
String str = editText().getText().toString();
// Here Str will be null blank all the time because EditText it self is blank.
}
}
Now see this
public class MainActivity extends Activity implements OnClickListener
{
EditText editText;
#Override
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById ( R.id.firstEditText );
String str = editText().getText().toString();
// Here Str will be null blank all the time, since you haven't input anything in your EditText
}
#Override
public void onClick ( View view )
{
// Assuming you have already put some text in edittext.
String newStr = editText().getText().toString();
}
}
I would suggest you to follow some steps to find out your actual problem
check that you have set right layout in the setContentView.
before getting text from edit text set some text in it and then get text form the EditText view. Check that it still printing null.
I think you have done some silly mistake because EditText.getText() never returns null.
NullPoint exception is thrown because you are converting a NULL value to a string
et1.getText() is null and you are doing
et1.getText().toString();
which is wrong.
Every EditText is initially NULL because it does not contain any value.
According to Android Docs
public Editable getText ()
Added in API level 1
Return the text the TextView is displaying.
Since the EditText has not been set any text hence its current value is null.
basically what I've tried, is to create a XML with two input types decimal. Input A and Input B, and when I click add, these values will get passed onto a class method, and that method will do so and so.
The problem I have is that I have no way of passing the value from an XML file to a java file (I think)
I spent like an hour doing the XML thing only to find out I can't do it.
Can you possibly guide me as to how I might go about doing this?
EditText mEditText1 = (EditText)findViewById(R.id.number1i);
String val1 = mEditText1.getText().toString();
EditText mEditText2 = (EditText)findViewById(R.id.number2i);
String val2 = mEditText2.getText().toString();
Your XML contains two editText and one button?
in your java file you should do:
EditText e1 = (EditText)findViewById(R.id.e1);
EditText e2= (EditText) findViewById(R.id.e2);
and in xml set onClick attribute on button (example onClick="onClick")
in code:
public void onClick(View v){
e1.getText.toString(); e2.getText.toString(); //save it to string and
you have what you want}
with this code, my program just force close(error)
***public View x = findViewById(R.string.nfoname);***
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
//edittext
***final EditText infoname=(EditText)findViewById(R.id.infoname);***
//clear,confirm
Button clear = (Button)findViewById(R.id.buttonclear);
Button confirm = (Button)findViewById(R.id.buttonconfirm);
//clear button
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
infoname.setText("");
}
});
//confirm button
confirm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
***x=(View) infoname.getText();***
}
});
}
the one with the * are the source of error
program function:
if the user clicks confirm, his name will be set to R.string.nfoname
which will then be used in another layout through TextView x = setText(R.string.nfoname);
I am not sure that you can save text to the R.string. This is a generated class that the compiler creates for you. It gets packaged with your apk. Think of the resources as a means of translation and to present text to the screen.
I think what you would want to do is save the user input as a SharedPreference or in a database.
See:SharedPreferences on the android docs for an example usage.
At least in the case of your variable infoname scoping is most likely causing your application to throw an error. infoname is a local variable to the function onCreate(), not an instance variable for your class, so it can't be accessed by your onClick() methods because they are part of an anonymous class.
Another thing I'd question is why you marked infoname as final? It goes out of scope when onCreate() exits so if it gets changed, you can see who changed it since it only exists while the method is executing.
You cannot set values to R.string.xxx because all these values will be constants much like a read only stuff. If you want to use the value of edit text to another layout use class variables or intent.putextra()
Coming to ur source code i see this
public View x = findViewById(R.string.nfoname);
How can a view be found by R.String? This should be R.id.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Why this editText has to be final?
***x=(View) infoname.getText();***
You just use infoname.getText().toString() you will get the string value of the Edittext's current text.
Dude you can do stuff simply.
public View x = findViewById(R.string.nfoname);
This can't work as not only are you trying to find a View using a R.string resource id, you are doing it before setContenView(...) is called in your onCreate(...) method. Even if you used a valid View resource id such as R.id.infoname then x will be null because the content view hasn't been inflated yet.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Apart from the pointless use of final this should'nt cause problems as long as R.id.infoname is actually the resource id of an EditText.
x=(View) infoname.getText();
Not only will x be null but calling getText() on an EditText returns an Editable which is not a View nor is it possible to cast it to View. Even if you used getText().toString() which is the correct way to get the text from an EditText it still wouldn't be possible to cast a String to a View.
Also, as for this...
TextView x = setText(R.string.nfoname);
It would have to be...
TextView x = (TextView) findViewById(<some id>);
x.setText(getString(R.string.nfoname));