在 Android 应用程序中使用全局变量时遇到困难

发布于 2024-11-03 14:33:29 字数 1411 浏览 6 评论 0原文

嘿,我在声明、更改和使用全局变量时遇到问题。我尝试了整个“创建一个扩展应用程序的类并将变量放在那里”的事情,但我不确定如何实现它。这是我的类,其中包含变量。

    public class MyApp extends Application {

    public int listPos;

}

然后我尝试在这里访问和更改 int listPos 。

public class Browse extends ListActivity{
MyApp app = ((MyApp)getApplicationContext());

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String[] coffeeTypes = getResources().getStringArray(R.array.coffeeTypes);
  setListAdapter(new ArrayAdapter<String>(this, R.layout.listview, coffeeTypes));

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);

  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        app.listPos = position;
        startActivity(new Intent(Browse.this, CoffeeTypes.class));

    }
  });
}

然后

我尝试访问以下活动中的变量以确定 if else 语句的结果

public class CoffeeTypes extends Activity{
MyApp app = ((MyApp)getApplicationContext());

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  if(app.listPos == 0){
      Toast.makeText(this, "WEEEEEEE!0", Toast.LENGTH_LONG).show();
  }
  else if(app.listPos == 1){
      Toast.makeText(this, "RAWR!1", Toast.LENGTH_LONG).show();

有人知道我做错了什么吗?

Hey I am having trouble declaring, changing, and using a global variable. I tried the whole "make a class that extends your application and put variables there" thing but I'm not sure how to implement it. Here is my class with the variable in it.

    public class MyApp extends Application {

    public int listPos;

}

I then tried to access and change int listPos here.

public class Browse extends ListActivity{
MyApp app = ((MyApp)getApplicationContext());

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String[] coffeeTypes = getResources().getStringArray(R.array.coffeeTypes);
  setListAdapter(new ArrayAdapter<String>(this, R.layout.listview, coffeeTypes));

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);

  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        app.listPos = position;
        startActivity(new Intent(Browse.this, CoffeeTypes.class));

    }
  });
}

}

Then I tried to access the variable in the following activity to determine the outcome of an if else statement

public class CoffeeTypes extends Activity{
MyApp app = ((MyApp)getApplicationContext());

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  if(app.listPos == 0){
      Toast.makeText(this, "WEEEEEEE!0", Toast.LENGTH_LONG).show();
  }
  else if(app.listPos == 1){
      Toast.makeText(this, "RAWR!1", Toast.LENGTH_LONG).show();

Anyone have any idea what I am doing wrong?

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

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

发布评论

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

评论(4

陈甜 2024-11-10 14:33:34

您可以使用 soorya 的答案进行一些修改。我个人仍然会使用您的 myApp 类,但将 listPos 更改为静态并以这种方式访问​​它。通过这种方式,您可以使用 Application 类 onCreate 方法来初始化值(如果需要)(尽管在本例中不需要)或其他 Android 方法。

public class MyApp extends Application {

    public static int listPos;

}

//~~ Elsewhere:
MyApp.listPos = 5; //etc

但这不是处理您的问题类型的最佳方法。

您应该通过 Intent 传递列表位置信息(或单击的项目的 ID 或您处理数据的方式)。

不要使用全局变量来跟踪此信息,而是将其保留在 Intent 本地:

public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        //app.listPos = position;
        Intent intent = new Intent(Browse.this, CoffeeTypes.class);
        intent.putExtra("position", position);
        startActivity(intent);
        //startActivity(new Intent(Browse.this, CoffeeTypes.class));

    }

这将通过 Intent 将位置数据传递给新的 Activity。在您的 CoffeeTypes Activity 中,您应该从以下内容开始:

//in onCreate...
int incomingPosition = getIntent().getIntExtra("position",-1));
if(incomingPosition != -1) { //do stuff }

这将从传入的 Intent 中读取“位置”数据,以便您可以使用它。如果不添加任何内容,上面的-1就是默认值。

最后一个警告:您可能需要小心来回发送列表位置,具体取决于您的应用程序的设置方式,如果添加新项目/删除项目,列表位置可能不再引用您认为的项目。如果这些咖啡类型/无论您使用什么都有一个单独的唯一 ID,可能更适合避免上述情况,请考虑使用它。

You can use soorya's answer with some modifications. I would personally still use your myApp class but change listPos to static and access it that way. Doing it this way lets you use the Application class onCreate method to initialize values if needed (though it won't be needed in this example) or other Android methods.

public class MyApp extends Application {

    public static int listPos;

}

//~~ Elsewhere:
MyApp.listPos = 5; //etc

But this isn't the best way to handle your type of problem.

You should be passing the list position information (or the id of the item clicked or however you are handling your data) via the Intent.

Instead of having a global variable to track this information, keep it local to just the Intent:

public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        //app.listPos = position;
        Intent intent = new Intent(Browse.this, CoffeeTypes.class);
        intent.putExtra("position", position);
        startActivity(intent);
        //startActivity(new Intent(Browse.this, CoffeeTypes.class));

    }

This passes the position data to the new Activity via the intent. In your CoffeeTypes Activity you should start with something along the following:

//in onCreate...
int incomingPosition = getIntent().getIntExtra("position",-1));
if(incomingPosition != -1) { //do stuff }

This will read the "position" data from the incoming Intent so you can use it. The -1 above is the default value if nothing is added.

One final warning: you might want to be careful sending the list position back and forth, depending on how your application is set up if new items are added/items are deleted the list position might no longer refer to the item you thought it did. If these coffee types/whatever you are using have a separate unique ID that might be more appropriate to avoiding the above situation, consider using that instead.

忘你却要生生世世 2024-11-10 14:33:34

我不确定这是否是 android 操作系统的可见性问题,您是否能够创建一个可以充当变量的 getter 的公共函数?

int getListPos(){ return this.listpos; }

我知道您可以在上下文之间传递变量,您可能必须这样做。

也许让您移动的临时解决方法也可以创建可访问变量的静态类?

I'm not sure if it's a visibility issue with the android OS, are you able to make an public functions that may be able to act as getters for the variable?

int getListPos(){ return this.listpos; }

I know that you can pass variables between contexts, you may have to do that.

Perhaps a temporary workaround to get you moving could be creating a static class of accessible variables too?

贱人配狗天长地久 2024-11-10 14:33:34

创建一个像这样的类

class globalClass
{
       static int lastPos;
}

您可以使用设置值

globalClass.lastPos = value;

并获取函数是

int myVal = globalClass.lastPos;

Create a class like this

class globalClass
{
       static int lastPos;
}

You can set values using

globalClass.lastPos = value;

and get function is

int myVal = globalClass.lastPos;
谜兔 2024-11-10 14:33:34

我通过将变量设为私有来创建应用程序变量类,然后创建公共 get() 和 set() 方法来更改变量。你可以尝试一下,但看起来你做得对,从技术上讲,

它可能出错的原因之一是因为你是在 onCreate 而不是 onStartCommand 中实现这些内容。如果您使用活动周期的错误假设/知识来测试此函数,则可能会出错

i do Application variable classes by making the variables private, and then create public get() and set() methods to change the variables. you can try that, but it seems like you are doing it right, technically

one reason why it might be going wrong is because you are implementing the stuff in onCreate and not onStartCommand. if you are testing this function with the wrong assumptions/knowledge of the Activity cycle, it could go wrong

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文