如何将ArrayAdapter更改为全局并在另一个类中清除它?

时间:2015-06-02 15:10:02

标签: android

我有ArrayAdapter声明。我想清除它并添加一些其他数据。 那么如何将其更改为全局?

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);
}

另一个班级

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);
        }
    }
}

我无法在第二节课中使用mForecastArray

2 个答案:

答案 0 :(得分:2)

全局变量总是容易出错,从长远来看会产生问题。

您可以在listener中定义一个AsyncTask来说明方法updateAdapter,这个听众将由您的Fragment ForecastFragment实施。所以,一旦你有了

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
    }
}

答案 1 :(得分:0)

创建自定义应用程序,请参阅此link

在自定义应用程序的ArrayList中创建静态onCreate。 您可以在应用程序的任何位置访问ArrayList