简体   繁体   中英

how to declare null value to integer in android

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="";

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.

如果您想对 int 类型使用某种“默认”或初始化值,您可以考虑从 1 开始计数并将 0 或负 int 解释为默认值。

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.

您可以将值设置为零。

int value = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM