Reputation: 1
I want to know how I should declare a Integer with Null Value in Android. Here is my code:
btnload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getDate, getEpayee, getEcategory;
int getEamt;
getDate= "";
getEamt=""; //This Eamt variable is of integer type and
//this gives me a error.
getEpayee ="";
getEcategory="";
Upvotes: 0
Views: 9409
Reputation: 13223
int
is a primitive type in Java; hence you cannot set it to null
(it is not an object).
if getEamt
is an int
, you cannot initialize it to a String
. If you really want to set an integer to null
you need to use the Integer
class.
Upvotes: 5
Reputation: 30875
You have probably miss understand what null
is.
In the example you have posted you use empty string ""
. So you can initialize String instances to avoid NullPointerException
. In case you do not initialize (assign at declaration) any value you have null
value by default for Object types.
String message;
is equal to String message = null;
What your are doing by String message = ""
is that you set a reference to empty string.
The null
is applicable only for Object types not primitive ones. How ever each primitive has a wrapper class that allow null.
You can do this
Integer value = null;
You can not do this
int value = null;
In general you should avoid the null
. Usage of primitive assure that you will never pass a null.
As in your code the declaration are local you should declare them just before usage with valid value instead of create a section of initialization and then a block of usage.
btnload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
conductPaymentTransaction()
}
private void conductPaymentTransaction()
{
Date date = getDate();
EPayee paye = getEPayee()
ECategory category = getECategory();
int ammount = getAmmount();
//...
}
Note: you should not store your data structure in form of plain string.
Upvotes: 0
Reputation:
If you want to use some kind of "default" or initialization value with the int type, you might consider starting to count at 1 and interpret 0 or a negative int as the default value.
Upvotes: 0