在Android中从一个类获取字符串到另一个类?

时间:2014-06-27 10:05:56

标签: android string getter-setter

我需要从项目的一个类到另一个类

获取字符串变量

在First类中,我创建了一个字符串类型变量,它是Global,如下所示: 类的名称是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;
 }

通过这样做它崩溃了。我在firstclass中做了另一件事

public String getStringPublically() {
       return firstClassVar;
    }

并且为了访问它我正在做的另一个类

   secondClassVar =getVar.getStringPublically();

通过这样做,它也会崩溃应用程序。

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

5 个答案:

答案 0 :(得分:2)

试试这个..

传递值

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

<强>的GetValues:

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)

答案 1 :(得分:1)

在头等舱和第二等舱中使用public static String firstClassVar;使用secondClassVar=FirstClass.firstClassVar;

答案 2 :(得分:1)

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

答案 3 :(得分:0)

尝试使用putExtra和getExtra with Intent

答案 4 :(得分:0)

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

  public firstclass getVar = new firstclass();

在第二课