使用全局变量

发布于 2024-11-17 01:57:09 字数 2901 浏览 2 评论 0原文

我知道这个问题已经被问了一百万次,因为我做了一些研究并发现了很多关于这个问题的线索。我尝试使用这些线程中的答案,但遇到了一些麻烦。

我希望设置一些可以在所有活动中使用的变量。

我创建了一个 GlobalVariables.java 类,如下所示(其中的值目前仅用于测试目的):

import android.app.Application;

public class GlobalVariables extends Application {

int holeAmount;

public int getHoles(){
    return holeAmount;
  }
  public void setHoles(String s){
    holeAmount = 30;
  }

}

在我的主要活动中,一切都在发生,我有以下内容:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GlobalVariables global = ((GlobalVariables)getApplicationContext());
    int totalHoles = global.getHoles();

在“GlobalVariables global = ... “行我收到以下错误:

Multiple markers at this line
- GlobalVariables cannot be resolved 
 to a type
- GlobalVariables cannot be resolved 
 to a type

我尝试按照此处的说明进行操作,但显然我做错了一些事情。 > 如何在 Android 中声明全局变量?

任何帮助将不胜感激!

谢谢!



第二次尝试:

EasyPar.java(错误@ EasyParHelperActivity)

package com.movi.easypar;

import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class EasyPar extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

(initialize all my buttons and textviews)
}

public void someMethod() {
    EasyParHelperActivity.helper.setHoles(30);
    int holes = EasyParHelperActivity.helper.getHoles();
}

(the rest of my button functions, etc.)

EasyParHelperActivity(没有错误)

package com.movi.easypar;

import android.app.Application;

public class EasyParHelperActivity extends Application {

public static EasyParHelper helper = new EasyParHelper();

}

EasyParHelper.java(没有错误) )

package com.movi.easypar;

public class EasyParHelper {

private int holeAmount = 0;

public int getHoles() {
    return holeAmount;
}

public void setHoles(int holes) {
    holeAmount = holes;
}
}

我想要的只是用户能够在第一个屏幕上单击按钮“18”或“9”,并且应用程序能够在其他时间使用该值无论它做什么。所以我需要在屏幕 1 中设置它,在屏幕 2 中我需要检索该值。

I know this question has been asked a million times because I have done some research and have found many threads on this. I have tried to use the answers in those threads but I am having a bit of trouble.

I am looking to set a few variables that I can use across all of my activities.

I created a GlobalVariables.java class which looks like the following (the value in there is just for testing purposes as of now):

import android.app.Application;

public class GlobalVariables extends Application {

int holeAmount;

public int getHoles(){
    return holeAmount;
  }
  public void setHoles(String s){
    holeAmount = 30;
  }

}

in my main activity where everything is happening I have the following:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GlobalVariables global = ((GlobalVariables)getApplicationContext());
    int totalHoles = global.getHoles();

and on the "GlobalVariables global = ..." line I am getting the following error:

Multiple markers at this line
- GlobalVariables cannot be resolved 
 to a type
- GlobalVariables cannot be resolved 
 to a type

I tried to follow the instructions here but clearly I am doing something incorrectly. > How to declare global variables in Android?

Any help would be greatly appreciated!

Thanks!



SECOND ATTEMPT:

EasyPar.java (Errors @ EasyParHelperActivity)

package com.movi.easypar;

import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class EasyPar extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

(initialize all my buttons and textviews)
}

public void someMethod() {
    EasyParHelperActivity.helper.setHoles(30);
    int holes = EasyParHelperActivity.helper.getHoles();
}

(the rest of my button functions, etc.)

EasyParHelperActivity (No Errors)

package com.movi.easypar;

import android.app.Application;

public class EasyParHelperActivity extends Application {

public static EasyParHelper helper = new EasyParHelper();

}

EasyParHelper.java (No Errors)

package com.movi.easypar;

public class EasyParHelper {

private int holeAmount = 0;

public int getHoles() {
    return holeAmount;
}

public void setHoles(int holes) {
    holeAmount = holes;
}
}

All i want is for the user to be able to click a button "18" or "9" on the first screen, and for the application to be able to use that value other times throughout whatever it does. So I need to set it in screen 1, and in screen 2 i need to retrieve that value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

遮了一弯 2024-11-24 01:57:09

如下创建一个“助手”类...

package com.my.application

public class MyAppHelper {

    private int holeAmount = 0;

    public int getHoles() {
        return holeAmount;
    }

    public void setHoles(int holes) {
        holeAmount = holes;
    }
}

然后为您的应用程序类执行以下操作...

package com.my.application

public class MyApplication extends Application {

    public static MyAppHelper helper = new MyAppHelper();

}

要访问助手中的 get/set 方法,您只需调用...

package com.my.application

public class MyActivity extends Activity {

    // Normal onCreate(...) etc here

    public void someMethod() {
        MyApplication.helper.setHoles(30);
        int holes = MyApplication.helper.getHoles();
    }
}

Create a 'helper' class as follows...

package com.my.application

public class MyAppHelper {

    private int holeAmount = 0;

    public int getHoles() {
        return holeAmount;
    }

    public void setHoles(int holes) {
        holeAmount = holes;
    }
}

Then for your Application class do the following...

package com.my.application

public class MyApplication extends Application {

    public static MyAppHelper helper = new MyAppHelper();

}

To get access to the get/set methods in the helper you can simply call...

package com.my.application

public class MyActivity extends Activity {

    // Normal onCreate(...) etc here

    public void someMethod() {
        MyApplication.helper.setHoles(30);
        int holes = MyApplication.helper.getHoles();
    }
}
缪败 2024-11-24 01:57:09

您需要导入全局变量。此外,您还需要将 GlobalVariables 的完整类名放入清单中应用程序的 name 属性中,如下所述:
http://developer.android.com/guide/topics/manifest /application-element.html#nm

You need to import GlobalVariables. Also you need to put the full class name of GlobalVariables in application's name attribute in manifest as described here:
http://developer.android.com/guide/topics/manifest/application-element.html#nm

人疚 2024-11-24 01:57:09

首先,

您应该深入考虑是否以及为什么需要全局变量。全局变量只能作为最后的手段使用。此外,如果您最终确实需要使用全局变量,您需要将它们记录下来,因为毫无疑问,如果您的应用程序变得复杂,您将失去对其中一个或多个变量的跟踪。追踪他们是一个严重的PIA!

根据我的经验,几乎 99% 的全局变量被使用都是因为程序员的懒惰,无论他们想要实现什么目标,都可以通过使用编程最佳实践的方式来完成。

这是一个例子:
https://groups.google.com/forum/#!topic/android -developers/yfI89IElhs8

在不了解更多关于您试图在班级之间传递的内容的情况下,除了我所提供的之外,我无法提供任何其他建议。但是,我相当肯定您可以在不使用任何全局变量的情况下实现您正在寻找的目标。

First things first...

You should to deeply consider if and why you might need a global variable. Global variables should only be used as a last resort. Furthermore if you do end up needing to use global variable(s) you need to document them to death because make no mistake, if your app gets complex you WILL lose track of one or more of them. Tracking them down is a severe PIA!!!

It has been my experience that almost 99% of the time global variables are used it is because of programmer laziness and whatever they were trying to achieve could have been done in a way that used programming best practices.

Here is an example:
https://groups.google.com/forum/#!topic/android-developers/yfI89IElhs8

Without knowing more about what you are attempting to pass between your classes, I cannot offer any other advice other than what I've provided. However, I am fairly POSITIVE that you can achieve what you are looking for without using any global variables.

柠北森屋 2024-11-24 01:57:09

该怎么办?

GlobalVariables global = ((GlobalVariables)getApplication());

如果您从文档中不清楚您是否从 getApplicationContext() 或其他一些实现收到实际的应用程序对象, 从代码来看,绝对不是这样的。

但是,出于您的目的,您希望获取您的 Application 对象,该对象将是您的 GlobalVariables。并确保它在清单中正确注册。


另外只是为了确保您

package com.my.application;

GlobalVariables 的开头有,不是吗?在您的代码片段中看不到它。

What if you do

GlobalVariables global = ((GlobalVariables)getApplication());

From docs it's not clear you receive actual application object from getApplicationContext() or some other implementation. And from code it definitely does not appear so.

For your purposes, however you want to get your Application object which would be your GlobalVariables. And make sure that it's properly registered in manifest.


Also just to make sure, that you have

package com.my.application;

At the beginning of GlobalVariables, don't you? Don't see it in your snippet.

救赎№ 2024-11-24 01:57:09

我所设置的,对我来说一直在解决的就是创建一个公共类,然后使用调用它的任何类的上下文来初始化它。我在链接找到了这个。这实际上让我可以访问系统服务之类的东西。然后我继续定义了一些类变量,让我可以在类中调用和调用。但为了实际处理变量的存储,我使用了 SharedPrefences。
这种设置的好处是,在访问每个变量之前,我不必继续设置共享首选项的代码。我刚刚通过公开课做到了。
现在请记住,我在这方面完全是新手,我不确定这是最好的方法,或者即使这是否应该以这种方式完成。但我还是决定分享我一直在做的事情。这是一些代码:

    package com.example.someapp;

    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;

    public class GlobalThing {

Context me;
SharedPreferences appdata;

public GlobalThing(Context me) {
    this.me = me;
    appdata = me.getApplicationContext().getSharedPreferences(
            "ApllicationData", 0);
}

public boolean alarmRunning() {
    boolean b;
    Intent i = new Intent(me, AlarmThing.class);
    b = (PendingIntent.getBroadcast(me, 0, i, PendingIntent.FLAG_NO_CREATE) != null);
    if (b) {
        return true;
    } else {
        return false;
    }
}

public void timeIn(long time){
    SharedPreferences.Editor timeVar = appdata.edit();
    timeVar.putLong("time delay", time);
    timeVar.commit();
}
public long timeOut(){
    return appdata.getLong("time delay", 0);
}
     }

上面是实际的全局类。这不会在清单或任何内容中声明。

然后,要访问此类中的变量,我将在活动中编写类似这样的代码:

      public class SmokeInterface extends Activity implements OnClickListener {

GlobalThing gt;
boolean bool;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_smoke_interface);
          gt = new GlobalThing(this);
                setalarm();
      }

并访问这样的变量:

        private void setAlarm() {
    bool = gt.alarmRunning();
    if (bool) {
        Toast.makeText(this, "Alarm is already running.",
                Toast.LENGTH_SHORT).show();
    } else {
        AlarmManager m = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, AlarmThing.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, 10);
        m.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
    }
}

或这样...

    gt.timeIn(60);//write time in (long) to shared prefrences
    long l = gt.timeOut();//read time out (long) from shared prefrences

What I have set up, and that has been working out for me is to just create a public class and then initialize it with the context from whatever class had called it. I found this at this link. This actually let me get access to things like the system services. I then went ahead and defined some class variables that let me call in and out of the class. But to actually handle the storage of the variables, I employed SharedPrefrences.
The nice thing about this setup was that I didn't have to keep setting up the code for the shared prefrences before I accessed each variable. I just did it through the public class.
Now keep in mind, I'm a complete novice at this stuff, and I'm not sure that this is the best approach, or even if this should be done in this way at all. But I decided to share what I've been doing all the same. So here's some code:

    package com.example.someapp;

    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;

    public class GlobalThing {

Context me;
SharedPreferences appdata;

public GlobalThing(Context me) {
    this.me = me;
    appdata = me.getApplicationContext().getSharedPreferences(
            "ApllicationData", 0);
}

public boolean alarmRunning() {
    boolean b;
    Intent i = new Intent(me, AlarmThing.class);
    b = (PendingIntent.getBroadcast(me, 0, i, PendingIntent.FLAG_NO_CREATE) != null);
    if (b) {
        return true;
    } else {
        return false;
    }
}

public void timeIn(long time){
    SharedPreferences.Editor timeVar = appdata.edit();
    timeVar.putLong("time delay", time);
    timeVar.commit();
}
public long timeOut(){
    return appdata.getLong("time delay", 0);
}
     }

Above is the actual global class. This doesn't get declared in the manifest or anything.

Then to access the variables in this class I would code something like this in an activity:

      public class SmokeInterface extends Activity implements OnClickListener {

GlobalThing gt;
boolean bool;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_smoke_interface);
          gt = new GlobalThing(this);
                setalarm();
      }

And access the variables like this:

        private void setAlarm() {
    bool = gt.alarmRunning();
    if (bool) {
        Toast.makeText(this, "Alarm is already running.",
                Toast.LENGTH_SHORT).show();
    } else {
        AlarmManager m = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, AlarmThing.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, 10);
        m.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
    }
}

or this...

    gt.timeIn(60);//write time in (long) to shared prefrences
    long l = gt.timeOut();//read time out (long) from shared prefrences
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文