Skip to content Skip to sidebar Skip to footer

How Can I Change Arrayadapter To Global And Clear It In Another Class?

I have a ArrayAdapter declaration. I want to clear it and add some other data. So how can I change it to global? public class ForecastFragment extends Fragment { private ArrayA

Solution 1:

Global variables are always error prone and create issues in the long run.

You can have a listener defined in your AsyncTask that would have say a method updateAdapter and this listener would be implemented by your FragmentForecastFragment. So once you you have

publicclassFetchWeatherTaskextendsAsyncTask<String, Void, String[]>{

    FetchListener listener;

    publicFetchWeatherTask(FetchListener listener) {
        this.listener = listener;
    }

    publicinterfaceFetchListener {
        publicvoidupdateAdapter(String[] arr);
    }

    protectedvoidonPostExecute(String[] strings) {
        //if (strings!=null){//  mForecastArray.clear();//for (String dayForecast : strings){               //mForecastArray.add(dayForecast);//}// just call your listener's update method
        listener.updateAdapter(strings);
    }
}

Inside ForecastFragment:

publicclassForecastFragmentextendsFragmentimplementsFetchWeatherTask.FetchListener {

    @OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // say if you are starting your AsyncTask herenewFetchWeatherTask(this).execute();
    }

    publicvoidupdateAdapter(String[] arr) {
        if (arr!=null){
            mForecastArray.clear();

        // use arr to re populate your mForecastArray
    }
}

Solution 2:

create your custom application refer this link

create static ArrayList in onCreate of your custom application. You can access that ArrayList anywhere in application.

Post a Comment for "How Can I Change Arrayadapter To Global And Clear It In Another Class?"