1

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 ArrayAdapter<String> mForecastArray;
    // ...
    List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
    mForecastArray = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastArray);
}

Another class

public class FetchWeatherTask extends AsyncTask<String, Void, String[]>{
    protected void onPostExecute(String[] strings) {
        if (strings!=null){
            mForecastArray.clear();
        for (String dayForecast : strings){
            mForecastArray.add(dayForecast);
        }
    }
}

I couldn't use mForecastArray in the second class

Mithun
  • 2,075
  • 3
  • 19
  • 26
  • Create a singleton class where your arraylist is, and use set/get methods to do what do you want with it. – Carnal Jun 02 '15 at 15:21

2 Answers2

2

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 Fragment ForecastFragment. So once you you have

public class FetchWeatherTask extends AsyncTask<String, Void, String[]>{

    FetchListener listener;

    public FetchWeatherTask(FetchListener listener) {
        this.listener = listener;
    }

    public interface FetchListener {
        public void updateAdapter(String[] arr);
    }

    protected void onPostExecute(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:

public class ForecastFragment extends Fragment implements FetchWeatherTask.FetchListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // say if you are starting your AsyncTask here
        new FetchWeatherTask(this).execute();
    }

    public void updateAdapter(String[] arr) {
        if (arr!=null){
            mForecastArray.clear();

        // use arr to re populate your mForecastArray
    }
}
Mithun
  • 2,075
  • 3
  • 19
  • 26
0

create your custom application refer this link

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

N J
  • 27,217
  • 13
  • 76
  • 96