access the variable in activity in another class

后端 未结 4 2077
情话喂你
情话喂你 2020-12-20 01:05

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 FirstActivit

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 01:48

    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.

    Detail.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

    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

    public NewActivity extends Activity{
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Table t = new Table(this);
    
    }
    }
    

提交回复
热议问题