[英]how to declare null value to integer in android
I want to know how I should declare a Integer with Null Value in Android.我想知道我应该如何在 Android 中声明一个带有 Null 值的整数。 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; int
是 Java 中的原始类型; hence you cannot set it to null
(it is not an object).因此你不能将它设置为null
(它不是一个对象)。
if getEamt
is an int
, you cannot initialize it to a String
.如果getEamt
是int
,则不能将其初始化为String
。 If you really want to set an integer to null
you need to use the Integer
class.如果您真的想将整数设置为null
,则需要使用Integer
类。
如果您想对 int 类型使用某种“默认”或初始化值,您可以考虑从 1 开始计数并将 0 或负 int 解释为默认值。
You have probably miss understand what null
is.您可能没有理解null
是什么。
In the example you have posted you use empty string ""
.在您发布的示例中,您使用空字符串""
。 So you can initialize String instances to avoid NullPointerException
.因此,您可以初始化 String 实例以避免NullPointerException
。 In case you do not initialize (assign at declaration) any value you have null
value by default for Object types.如果您没有初始化(在声明时分配)任何值,则默认情况下对象类型的值为null
。
String message;
is equal to String message = null;
等于String message = null;
What your are doing by String message = ""
is that you set a reference to empty string.您通过String message = ""
所做的是设置对空字符串的引用。
The null
is applicable only for Object types not primitive ones . null
仅适用于 Object 类型而不适用于原始类型。 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
.一般来说,您应该避免使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.