【问题标题】:Using Global Variables使用全局变量
【发布时间】:2011-06-25 20:42:30
【问题描述】:

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

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

我创建了一个 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

我尝试按照此处的说明进行操作,但显然我做错了什么。 > How to declare global variables in 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 中我需要检索该值。

【问题讨论】:

  • 您能否发布应用程序的整个代码或出现错误的最小应用程序?我有强烈的感觉,这是一个非常简单的错误(例如导入一个名为 GlobalVariables 的不同类)或更简单的错误。
  • 完成(名称有所改变......但本质上,一切都应该相同。)
  • 我真的很抱歉 Rob,我检查了 4 次代码,但我无法发现问题:(
  • 我也是,对于像我这样的新人来说真的很沮丧。我只是不明白为什么它看不到它:(

标签: android variables global


【解决方案1】:

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

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

【讨论】:

  • 我试过这个,但我得到了 - GlobalVariables 无法解析为一个类型(我把 GlobalVariables.getHoles(); 放在我的主类中,这是为什么?)我想从 GlobalValues 中获取值.java 到 MainApplication.java
  • 我的主类扩展了 Activity,这会是个问题吗?此外,当我创建一个新类(右键单击我的包 > 新建 > 类)并创建 MyAppHelper 并尝试将其更改为受保护时,它会抛出一个错误,指出类 EasyParHelper 的非法修饰符;只允许公开的、抽象的和最终的
  • @Rob:我的错 - 助手类应该是公共的,不受保护,我会编辑。不,您的主类扩展 Activity 并不重要。只要确保您的扩展应用程序和您的活动都在同一个包中,您甚至不需要导入应用程序类。我经常使用“助手”,这就是我的做法。
  • 没有运气...为了确保我们在同一页面上.. 一个文件是 src > com.my.application > MainApplication.java,另一个是 src > com.my.application > MyAppHelper.java,然后在 MyAppHelper 我有你的顶级代码框,在 MainApplication.java 我有 public class MainApplication extends Activity implements OnClickListener { public static MyAppHelper helper = new MyAppHelper(); (然后是其余内容)如果是这种情况,我仍然会收到以下错误:MyAppHelper cannot be resolve to a type
  • 我还在清单中添加了以下内容
【解决方案2】:

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

【讨论】:

  • 我已经将 GlobalVariables 添加到清单中,这样应该很好。要导入它,我应该能够:“import GlobalVariables;”
  • 是同一个包吗?我建议在 Eclipse 中关闭并打开项目(或刷新)。有时一些编译错误可能来自糟糕的 Eclipse 刷新。
  • 当我尝试将其添加到导入列表时,即使我添加了 import com.my.application.GlobalVariables;它说无法解决导入 com.my.applicaiton.GlobalVariables。这是因为它的扩展应用程序而不是偶然的活动吗?
  • 不。您必须在 GlobalVariables 中有编译错误。顺便说一句 - 以不同的方式命名 - 以 Application (MyApplication, GlobalVariablesApplication) 或 smth 结尾。这是使用的约定
  • GlobalVariables.java 中没有错误,似乎编译得很好 :( 在 MainApplication.java 中虽然是我得到错误的地方。似乎有些人看不到 GlobalVariables.java原因
【解决方案3】:

首先要做的事……

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

根据我的经验,几乎 99% 的时间都使用全局变量,这是因为程序员的懒惰,而他们试图实现的任何目标都可以通过使用编程最佳实践的方式完成。

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

如果不知道更多关于你试图在你的课程之间传递什么,除了我提供的内容之外,我无法提供任何其他建议。但是,我相当肯定您可以在不使用任何全局变量的情况下实现您正在寻找的东西。

【讨论】:

  • 如果出现问题,我理解您所说的重大混乱。但是,我要避免的是,如果我更改一件事,则必须多次编辑每个变量。相反,我宁愿在 1 个地方更改它,并让它更改正在使用它的整个应用程序。对于可能导致问题的值,我可能不会使用全局变量。
  • 那么我会明确建议为此使用字符串资源文件。例如,我使用 SharedPreferences 并且对于键/值对中的键,我使用字符串资源,因为它是全局可用的。因此它看起来像 this.mSharPref.getInt(this.getString(R.string.somevalue), 0);
  • @Rob btw 虽然所有其他答案都是可行的,但我认为如果您为此使用字符串首选项,您会发现它 WAY 更简单并且WAY 更易于维护。它还有一个好处是让 Android 做它的工作,你做你的......例如。对象创建/释放。
【解决方案4】:

如果你这样做了会怎样

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

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

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


也只是为了确保你有

package com.my.application;

GlobalVariables的开头,不是吗?不要在你的 sn-p 中看到它。

【讨论】:

  • 我确实有包 com.my.application;一开始,GlobalVariables.java 文件完全没有错误。不幸的是,我尝试了你上面提到的,但仍然没有骰子:(我只是在这一行得到多个标记 - GlobalVariables 无法解析为类型 - GlobalVariables 无法在任何地方解析为类型
【解决方案5】:

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

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2017-01-09
    • 2020-03-05
    • 2021-05-16
    相关资源
    最近更新 更多