【问题标题】:Get string from one class to another class in Android?在Android中从一个类到另一个类获取字符串?
【发布时间】:2014-06-27 10:05:56
【问题描述】:

我需要从我的项目的一个类中获取字符串变量到另一个类,

在第一堂课中,我创建了一个字符串类型变量,即全局变量,如下所示: 班级名称是firstclass

 public String  firstClassVar;

我在这个方法中给它赋值

public String requestForServerData(String strURL) throws IOException, UnknownHostException, IllegalArgumentException, Exception {
//additional code 
 firstClassVar   = myObject.getString("values");
//additional code
}

现在在二等舱,我正在做这样的事情:

  public firstclass getVar;

  public void method{
      String secondClassVar;
             secondClassVar=getVar.firstClassVar;
 }

这样做会崩溃。我在头等舱做了另一件事,那就是

public String getStringPublically() {
       return firstClassVar;
    }

为了访问它,我正在这样做的另一个类

   secondClassVar =getVar.getStringPublically();

这样做也会导致应用程序崩溃。

现在我对 Android 有点陌生,不知道从另一个类访问字符串的基本方法。

【问题讨论】:

  • 你可以在调用时将String传递给方法。或者将字符串存储在存储的首选项中并从第二个位置检索。 stackoverflow.com/a/12074219/940834 如果适用,您也可以将变量设为静态。并直接访问它。或者从另一个类中引用该类的实例来访问它的变量
  • 检查对静态变量的更改并在其他类中将其称为 classname.its_name。像“公共静态字符串 firstClassVar”。
  • @Doomsknight 我会尝试并告诉你。

标签: android string getter-setter


【解决方案1】:

在第一类使用public static String firstClassVar;,在第二类使用secondClassVar=FirstClass.firstClassVar;

【讨论】:

  • 最简单的方法。谢谢
【解决方案2】:

试试这个..

传递值:

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

获取值:

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

如果是片段

发送:

Fragment fragment = new Fragment();
 Bundle bundle = new Bundle();
 bundle.putInt(key, value);
 fragment.setArguments(bundle);

检索:

Bundle bundle = this.getArguments();
 int myInt = bundle.getInt(key, defaultValue)

【讨论】:

    【解决方案3】:

    您可以使用 SharedPreferences 在您想要的任何类中设置/获取值。 Here is a good topic about it

    【讨论】:

      【解决方案4】:

      尝试使用带有 Intent 的 putExtra 和 getExtra

      【讨论】:

      • 我正在使用片段,并且在片段中调用意图存在问题..所以我无法在片段中调用意图
      【解决方案5】:

      应用程序崩溃,因为 vetVar 未初始化。试试

        public firstclass getVar = new firstclass();
      

      二等舱

      【讨论】:

        猜你喜欢
        • 2017-03-25
        • 1970-01-01
        • 2015-10-10
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        相关资源
        最近更新 更多