Java 静态变量还是通过Bundle传递变量?

Java 静态变量还是通过Bundle传递变量?,java,android,android-intent,static,bundle,Java,Android,Android Intent,Static,Bundle,假设我有一个ListView,并在列表上设置了一个Listener。传递变量的最佳方式是什么 静态变量: public static String example; // onItemClick Intent intent = new Intent(Main.this, Details.class); Main.example = "example"; startActivity(intent); // in onCreate of Details String example = Main

假设我有一个ListView,并在列表上设置了一个Listener。传递变量的最佳方式是什么

静态变量:

public static String example;

// onItemClick
Intent intent = new Intent(Main.this, Details.class);
Main.example = "example";
startActivity(intent);

// in onCreate of Details
String example = Main.example;
捆绑:

// onItemClick
Intent intent = new Intent(Main.this, Details.class);
intent.putExtra("example","example");
startActivity(intent);

// in onCreate of Details
Bundle extras = getIntent().getExtras();
String example = extra.getString("example");
// or
Intent intent = getIntent();
String example = intent.getStringExtra("example");

如果希望变量在整个应用程序中使用,那么使用静态变量或单例类(即将getter setter模型类设置为单例)
静态变量不容易被垃圾收集,所以除非需要,否则不要使用它
如果要将数据从一个活动发送到另一个活动(而不是通过应用程序),请使用bundle。

除了使用
静态变量外,最好使用
意图。当您不想在应用程序中长期使用静态变量时,请使用静态变量。因为它占用内存,不容易收集垃圾。

所以,最好使用“Intent”将变量传递给其他活动。

使用此代码。它可能会对您有所帮助

 public  String example;

    // onItemClick
    Intent intent = new Intent(Main.this, Details.class);
    intent.putExtra("id",example);
    startActivity(intent);


    // on Details activtiy
    Intent intent =getIntent().getStringExtra("id")

至于我,我会使用bundle选项。我的意思是,如果您只需要将某些内容从第一个活动传递到第二个活动,那么为什么要创建一个静态变量,它比您需要的更活跃?顺便说一句,显然存在一个单行解决方案:
String-example=getIntent().getStringExtra(“example”)
。这对我来说似乎干净多了。@Scadge这是我需要的大开眼界的东西,谢谢!欢迎光临。但无论如何,我建议您阅读一些关于在活动之间传递变量的内容,可能与第一条评论中给出的内容类似。请小心使用静态变量,因为Android可能会对它们进行垃圾收集,特别是当设备内存不足时。@s1m3n Android可能不会对它们进行垃圾收集,它只是终止并重新启动应用程序的进程。