Android 访问另一个类中活动中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22759644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:25:18  来源:igfitidea点击:

access the variable in activity in another class

android

提问by Siva

In my application I need a variable from one activity to another activity without using any intent. So I have declared that variable as static and used as FirstActivity.abut this is returning so null, Hence I have created a class that extends application and declared that variable there still I am getting null. no clue how to achieve this.

在我的应用程序中,我需要一个从一个活动到另一个活动的变量,而不使用任何意图。因此,我已将该变量声明为静态并用作,FirstActivity.a但这返回的是空值,因此我创建了一个扩展应用程序的类,并在那里声明了该变量,但我仍然得到空值。不知道如何实现这一目标。

Googled a lot but everyone are suggesting either to use static or extend Application class, unfortunately both are not working for me.

谷歌搜索了很多,但每个人都建议使用静态或扩展 Application 类,不幸的是两者都不适合我。

Application class:

应用类:

public class ApplicationClass extends Application{

    private String StockName;

    public String getStockName() {
        return StockName;
    }

    public void setStockName(String stockName) {
        StockName = stockName;
    }



}

Setting the variable in one activity as:

将一项活动中的变量设置为:

public class Detail extends Activity{

ApplicationClass ac;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockdetail);
        ac=new ApplicationClass();

        ac.setStockName(getIntent().getExtras().getString("StockName"));
}

Retriving the variable in another class as:

检索另一个类中的变量为:

public class Table {

    Context c1;

    Cursor c;
    ApplicationClass ac=new ApplicationClass();

public String selectdate="Select " + column1 + " as _id, " + column2 + " From " + tablename + " Where " + column3 + " = " 
                                + ac.getStockName();

I'm not sure how to achieve this.

我不确定如何实现这一目标。

Edit

编辑

public class Detail extends Activity{

public static sname;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockdetail);

        sname=getIntent().getExtras().getString("StockName");
}

public class Table {

        Context c1;

        Cursor c;

    public String selectdate="Select " + column1 + " as _id, " + column2 + " From " + tablename + " Where " + column3 + " = " 
                                    + Detail.sname;

采纳答案by Joel Fernandes

[Edited]

[编辑]

Since you're saying that there is a value returned from this line getIntent().getExtras().getString("StockName"), then try this code:

既然你说有一个从这一行返回的值getIntent().getExtras().getString("StockName"),那么试试这个代码:

public class Detail extends Activity{

public static String stringValue; //make it public and static

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockdetail);

        stringValue = getIntent().getExtras().getString("StockName");
}

Now access the static object in Table class:

现在访问 Table 类中的静态对象:

   public class Table {
        Context c1;
        Cursor c;

      public String selectdate="Select " + column1 + " as _id, " + column2 + " From " + tablename + " Where " + column3 + " = " + Detail.stringValue;

}

This should work properly. Make sure you're accessing the stringValuevariable after the Detailactivity is created.

这应该可以正常工作。确保在创建活动stringValue后访问变量Detail

[Original Answer]

[原答案]

Try this:

尝试这个:

public class Detail extends Activity{

public static ApplicationClass ac; //make it public and static

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockdetail);
        ac=new ApplicationClass();

        ac.setStockName(getIntent().getExtras().getString("StockName"));
}

Now access the static object in Tableclass:

现在访问Table类中的静态对象:

public class Table {

    Context c1;

    Cursor c;

public String selectdate="Select " + column1 + " as _id, " + column2 + " From " + tablename + " Where " + column3 + " = " 
                                + Detail.ac.getStockName();
}

P.S. To access the static object/variable, follow this syntax:

PS 要访问静态对象/变量,请遵循以下语法:

Class_Name.Object_Name.Method_Name();

回答by Kiran Kumar

You should define your subclassed application class in your manifest. And you should never call "new ApplicationClass()". You can get a reference to ApplicationClass instance using activity's getApplication() method.

您应该在清单中定义子类应用程序类。并且您永远不应该调用“new ApplicationClass()”。您可以使用活动的 getApplication() 方法获取对 ApplicationClass 实例的引用。

Detail.java:

详情.java:

public class Detail extends Activity{

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stockdetail);
    ApplicationClass app = (ApplicationClass)getApplication();
    app.setStockName("blah");
}
}

Table.java

表.java

public class Table {
public String selectDate;
public Table(Activity a)
{
    ApplicationClass ac=(ApplicationClass)a.getApplication();
    selectdate="Select " + column1 + " as _id, " + column2 + " From " + tablename + " Where " + column3 + " = " 
                            + ac.getStockName();
}

Instantiate Table.java

实例化Table.java

public NewActivity extends Activity{

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Table t = new Table(this);

}
}

回答by Lavekush Agrawal

Try this.

尝试这个。

Step 1: Create a static Bundle object in Application class.( ApplicationClass.java)

第一步:在Application类中创建一个静态的Bundle对象。(ApplicationClass.java)

E.g :

例如:

     public static Bundle mMyAppsBundle = new Bundle():

Step 2:

第2步:

Set key values pair in that bundle from anywhere. like this:

从任何地方设置该包中的键值对。像这样:

   ApplicationClass.mMyAppsBundle.putString("key","value");

Step 3:

第 3 步:

Now you can get these values from anywhere like this way:

现在您可以像这样从任何地方获取这些值:

   String str = ApplicationClass.mMyAppsBundle.getString("key");

Please apply null check before using bundle objects for safety points of view.

为了安全起见,请在使用包对象之前应用空检查。

回答by RMachnik

Try to initialize firstly your class. But what I see you want to have some application context that is accessible via application. For that porpouse you can simply use that method but data try to keep in SharedPreferences. So simply when you get sth from ApplicationClassyou simply get it firstly from shared preferences and return. :) And each time when you need your ApplicationClass you initialize it and there methods run shared preferences to get data.

尝试首先初始化您的课程。但是我看到您想要一些可通过应用程序访问的应用程序上下文。对于那个海豚,您可以简单地使用该方法,但数据尝试保留在SharedPreferences. 所以简单地当你从ApplicationClass你那里得到某样东西时,首先从共享的偏好中得到它然后返回。:) 每次当你需要你的 ApplicationClass 时,你都会初始化它,并且有方法运行共享首选项来获取数据。

public class Detail extends Activity{

ApplicationClass ac = new ApplicationClass();

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockdetail);
        ac=new ApplicationClass();

        ac.setStockName(getIntent().getExtras().getString("StockName"));
}

Shared preferences context class.

共享首选项上下文类。

public ApplicationClassWithSharedPreferences{
   private Context context;
   public ApplicationClassWithSharedPreferences(Context c){
       context = c;
   }

   public String getSomeValueFromContext(){
      SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
      String highScore = sharedPref.getString("KEY", "DEFAULT");
      return highScore;

   }

}