简体   繁体   中英

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 -

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) 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: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

First you are trying to get the date without setting it first. Consider calling the method setDate and set the date before using it. Or initialize it during declaration as

private Date date = new Date();

Next, I don't think you should not rely on the getApplicationContext() method.

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()

You're almost there! Just keep your Application class overload with a slight change:

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:

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. 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.

Hope this helps. Cheers

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