javaandroidadapterexpandablelistadapter

How can I use my global variable inside an Adapter class? Android


Hi i'm trying to pass a value by using Global Variable. I have created a class file where it is extended to Application and then add it on my Manifest.

public class MyApplication extends Application {}

After that I had created an Adapter Class which is extended to BaseExpandableListAdapter, I've search on how to set and get the global variable i've created and found this

((MyApplication) getActivity().getApplication()).setMy_id(my_id);

and to be able to get the value I use this

Integer my_id = ((MyApplication) getActivity().getApplication()).getMy_id();

In my Fragments, I can use my getMy_id() method but when putting it inside the BaseExpandableListAdapter, I'm having an error in getActivity(). I already tried using this but still it says Cannot resolve method getApplication(), is there any other way to get the value of my global variable.

I'm doing this because I'm trying to use Cursor for my ListView. I wanted to create a Expandable ListView where the data is from my database and my Cursor have a parameter for it's WHERE condition where my data in my global variable will be used.

The reason why I'm using it as a global variable because I use this data in different Fragments where it is not static it changes its value depends on the selected item.

Thank you in advance.


Solution

  • You need to have a constructor in your class that extends BaseExpandableListAdapter. The defined constructor should receive a parameters of Context type. Here is the example -

    private Context mContext;
    
    public YourExpandableListAdapter(Context context) {
        mContext = context;
        Integer my_id = ((MyApplication) context.getApplicationContext()()).getMy_id();
    }
    

    Now create an instance like this in your activity -

    YourExpandableListAdapter ob = new YourExpandableListAdapter(this);
    

    This should work.