简体   繁体   English

使用全局变量?

[英]Using global variables?

I am trying to use a global variable that will call in the current date. 我正在尝试使用将在当前日期调用的全局变量。 I have got the date going on a button click but I need to use the date for a calculation hence why I'm turning it into a global variable. 我已经单击了按钮,但要使用该日期进行计算,因此为什么要将其转换为全局变量。 I have tried a method and it isn't reading the date, the app crashes. 我尝试了一种方法,但没有读取日期,应用程序崩溃了。 If anyone could help it would be greatly appreciated 如果有人可以帮助,将不胜感激

Global Class - 全球舱-

public class GlobalClass extends Application{

private Date date;

public Date getDate(){
    return date;
}
public void setDate(Date DDate){
    date = DDate;
}

CreateLine.Java (main java class, where I am trying to call the global variables - CreateLine.Java(主Java类,在这里我试图调用全局变量-

public class CreateLine extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.create_line);
    myDb = new DatabaseHelper(this);


    GlobalClass globalVariable = (GlobalClass) getApplicationContext();
    globalVariable.setShippers20(28);
    final int shippers20 = globalVariable.setShippers20();

    GlobalClass globalVariable1 = (GlobalClass) getApplicationContext();
    globalVariable1.setShippers30(27);
    final int shippers30 = globalVariable.setShippers30();

    GlobalClass globalVariable2 = (GlobalClass) getApplicationContext();
    globalVariable2.setShippers20(10);
    final int time10 = globalVariable.setTime10();

    GlobalClass globalVariable3 = (GlobalClass) getApplicationContext();
    globalVariable3.getDate();
    Date Date = globalVariable3.getDate()

        }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd HH:mm");
    datedisplay.setText(dateFormat.format(Date));
}

STACKTRACE 堆栈跟踪

10-30 14:22:51.010 13812-13812/com.almac.tracker E/AndroidRuntime: FATAL EXCEPTION: main Process: com.almac.tracker, PID: 13812 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.almac.tracker/com.almac.tracker.CreateLine}: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6540) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 10-30 14:22:51.010 13812-13812 / com.almac.tracker E / AndroidRuntime:致命例外:主进程:com.almac.tracker,PID:13812 java.lang.RuntimeException:无法启动活动ComponentInfo {com。 almac.tracker / com.almac.tracker.CreateLine}:java.lang.NullPointerException:尝试在android.app.ActivityThread.performLaunchActivity()上的空对象引用上调用虚拟方法'long java.util.Date.getTime()'。 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)上的ActivityThread.java:2817)android.app.ActivityThread $ H.handleMessage(ActivityThread.java)上android.app.ActivityThread.-wrap11(未知源:0) :1593),位于android.os.Handler.dispatchMessage(Handler.java:105),位于android.os.Looper.loop(Looper.java:164),位于android.app.ActivityThread.main(ActivityThread.java:6540),位于Java com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)上的.lang.reflect.Method.invoke(本机方法)com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 767) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at java.util.Calendar.setTime(Calendar.java:1749) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:981) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:974) at java.text.DateFormat.format(DateFormat.java:341) at com.almac.tracker.CreateLine.onCreate(CreateLine.java:343) at android.app.Activity.performCreate(Activity.java:6980) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread 原因:java.lang.NullPointerException:尝试在java.text的java.util.Calendar.setTime(Calendar.java:1749)的空对象引用上调用虚拟方法'long java.util.Date.getTime()'。 com.almac.tracker.CreateLine上的java.text.DateFormat.format(DateFormat.java:341)上的.SimpleDateFormat.format(SimpleDateFormat.java:981)在java.text.SimpleDateFormat.format(SimpleDateFormat.java:974)在com.almac.tracker.CreateLine处。 android.app.Activity.performCreate(Activity.java:6980)上的onCreate(CreateLine.java:343)android.app.ActivityThread.performLaunchActivity(ActivityThread.java)上android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)上:2770)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)在android.app.ActivityThread.-wrap11(未知源:0)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1593)在android.os.Handler.dispatchMessage(Handler.java:105)在android.os.Looper.loop(Looper.java:164)在android.app.ActivityThread.main(ActivityThread) .java:6540) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 10-30 14:22:51.084 13812-13817/com.almac.tracker I/zygote: Do full code cache collection, code=105KB, data=79KB 10-30 14:22:51.085 13812-13817/com.almac.tracker I/zygote: After code cache collection, code=74KB, data=42KB .java:6540),位于com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240),位于com.android.internal.os.ZygoteInit的java.lang.reflect.Method.invoke(本机方法) .main(ZygoteInit.java:767)10-30 14:22:51.084 13812-13817 / com.almac.tracker I / zygote:执行完整的代码缓存收集,代码= 105KB,数据= 79KB 10-30 14:22: 51.085 13812-13817 / com.almac.tracker I /合子:代码缓存收集后,代码= 74KB,数据= 42KB

First you are trying to get the date without setting it first. 首先,您尝试获取日期而不先设置日期。 Consider calling the method setDate and set the date before using it. 考虑使用方法setDate并设置日期,然后再使用它。 Or initialize it during declaration as 或者在声明时将其初始化为

private Date date = new Date();

Next, I don't think you should not rely on the getApplicationContext() method. 接下来,我认为您不应该依赖getApplicationContext()方法。

If you want to use global variables accessible from all classes, use static fields. 如果要使用可从所有类访问的全局变量,请使用静态字段。

public class GlobalClass {
    private static Date date = new Date();
    public static Date getDate(){
        return date;
    }
    public static void setDate( Date DDate ){
        date = DDate;
    }
}

Then you can set or get the date from any class using GlobalClass.setDate() or GlobalClaas.getDate() 然后,您可以使用GlobalClass.setDate()GlobalClaas.getDate()从任何类设置或获取日期

You're almost there! 你快到了! Just keep your Application class overload with a slight change: 只需稍作更改即可保持Application类重载:

public class GlobalClass extends Application{

    private Date date;

    public Date getDate(){
        return date == null ? new Date() : this.date;
    }
    public void setDate(Date DDate){
        this.date = DDate;
    }
}

Now to use it you need to do this inside your Activity: 现在要使用它,您需要在Activity中执行以下操作:

public class CreateLine extends AppCompatActivity {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd HH:mm");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_line);

        myDb = new DatabaseHelper(this);


        // set date in your global variable
        ((GlobalClass) getApplication()).setDate(new Date());

        // get date value previously set
        Date mDate = ((GlobalClass) getApplicatio()).getDate();

        datedisplay.setText(dateFormat.format(mDate));

    }           

}

This may work for you. 这可能对您有用。

Just a few reminders : 只是一些提醒

1 - Your overriding your Application class, you need to cast it everytime you need to set or get date. 1-覆盖您的Application类,您需要在每次需要设置或获取日期时进行强制转换。 2 - when outside of your Activities classes (if more than one) you need to have a context so you can get the Application object and then get or set the Date value: ((GlobalClass) ((Activity) mContext).getApplication()).getDate() , where mContext is an Activity and you also need to cast it to Activity type. 2-在Activity类之外(如果有多个),则需要具有上下文,以便可以获取Application对象,然后获取或设置Date值: ((GlobalClass) ((Activity) mContext).getApplication()).getDate() ,其中mContext是一个Activity,还需要将其强制转换为Activity类型。

Hope this helps. 希望这可以帮助。 Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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