![](/img/trans.png)
[英]How can I store a value in my global variable and use it inside any method anywhere in activity
[英]How can I use my global variable inside an Adapter class? Android
嗨,我正在嘗試使用Global Variable
傳遞一個值。 我創建了一個類文件,將其擴展為Application
,然后將其添加到我的Manifest
。
public class MyApplication extends Application {}
之后,我創建了一個擴展到BaseExpandableListAdapter
的Adapter Class
,我搜索了如何設置和獲取我創建的全局變量並找到了這個
((MyApplication) getActivity().getApplication()).setMy_id(my_id);
並能夠獲得我使用它的價值
Integer my_id = ((MyApplication) getActivity().getApplication()).getMy_id();
在我的Fragments
,我可以使用我的getMy_id()
方法,但是當將它放入BaseExpandableListAdapter
,我在 getActivity() 中遇到錯誤。 我已經嘗試過使用this
但它仍然說Cannot resolve method getApplication()
,有沒有其他方法可以獲取我的全局變量的值。
我這樣做是因為我試圖將Cursor
用於我的ListView
。 我想創建一個Expandable ListView
,其中數據來自我的數據庫,而我的Cursor
有一個參數,因為它是WHERE
條件,我的全局變量中的數據將被使用。
我將它用作全局變量的原因是因為我在不同的Fragments
中使用此數據,其中它不是靜態的,它更改其值取決於所選項目。
先感謝您。
我不太確定你想要達到什么目標,但無論你在做什么,對我來說似乎都是 hacky! 根據回答您的問題, getApplication()
需要一個上下文,所以當您這樣做時
((MyApplication) getActivity().getApplication())
您實際上是在使用活動的(getActivity()) 上下文。 並且您不能在Adapter
類中調用getActivity()
。 嘗試將活動的上下文從活動傳遞到構造函數中的適配器,例如。
MyAdapter myAdapter = new MyAdapter(this); //This line will be in your activity, and this will be the instance of your activity
你的適配器構造函數看起來像
public MyAdapter(Context context){
//Use this context to get the application instance, something like
Integer my_id = ((MyApplication) context.getApplication()).getMy_id();
}
您的類中需要有一個構造函數來擴展 BaseExpandableListAdapter。 定義的構造函數應該接收一個 Context 類型的參數。 這是例子——
private Context mContext;
public YourExpandableListAdapter(Context context) {
mContext = context;
Integer my_id = ((MyApplication) context.getApplicationContext()()).getMy_id();
}
現在在您的活動中創建一個這樣的實例 -
YourExpandableListAdapter ob = new YourExpandableListAdapter(this);
這應該有效。
對我來說,以上都沒有奏效。 嘗試這個:
((MyApplication) context.getApplicationContext()).getMy_id();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.