ArrayAdapter 已更改但未反映在 UI

ArrayAdapter is changed but not reflected in UI

我一直在研究 ListView 和 ArrayAdapter。现在我在更改 ArrayAdapter 时卡住了。

我正在使用 AsyncTack 来更新 UI 元素,即 ListView,ListView 的适配器最初是在 onCreate() 方法中设置的,但我即将在 onPostExecute( ) AsyncTask 的方法。

下面是代码

ListView mListView = (ListView)findViewById(R.id.dataListView);
vAdapter = new ArrayAdapter(getActivity(), R.layout.list_item_data,strings);
mLisstView.setAdapter(vAdapter);

异步任务

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


        public getDataFromServer() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String[] doInBackground(String... parm) {
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.

            if(parm.length == 0){
                return null;
            }

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String getJsonStr = null;

            try {
                final String FORECAST_BASE_URL="http://myUrlToServer?";
                final String QUERY_PARAM ="query";
                final String FORMAT_PARAM ="mode";
                final String UNITS_PARAM ="units";

                Uri baseUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                            .appendQueryParameter(QUERY_PARAM,parm[0])
                            .appendQueryParameter(FORMAT_PARAM, format)
                            .appendQueryParameter(UNITS_PARAM,units)
                            .build();

                Log.v("build Url: ",baseUri.toString());
                URL url = new URL(baseUri.toString());

                // Create the request and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                getJsonStr = buffer.toString();
            } catch (IOException e) {                
                return null;
            } finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("Found in trouble", "Error closing stream", e);
                    }
                }
            }
            try {
                return getWeatherDataFromJson(getJsonStr,numDays);
            }catch(JSONException ex){
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] strings) {
            super.onPostExecute(strings);

            for(String s : strings)
                Log.v("@ onPostExecute",s);

            vAdapter = new ArrayAdapter(getActivity(), R.layout.list_item_data,strings);
            vAdapter.notifyDataSetChanged();

            /*if(strings != null){
                vAdapter.clear();
                for(String dayForecast : strings){
                    vAdapter.add(dayForecast);
                }
            }*/

        }
    }

注意:onPostExecute() 方法中的注释代码在逻辑上也是正确的,但在 vAdapter.clear()

时会生成 UnsupportedOperationException 异常

你可以这样做:

onPostExecute() 应该如下所示:

@Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);

   for(String s : strings)
      Log.v("@ onPostExecute",s);

    vAdapter.clear();
    vAdapter.addAll(strings);
    vAdapter.notifyDataSetChanged();
}

就是这样。

我终于找到了解决办法。 我在 onCreate() 方法中创建适配器并尝试将适配器清除为 vAdapter.clear() 时使用了数组,这是不可能的。所以要做到这一点,我只需用 List

更改数组

在 onCreate() 方法中

String[] mArray = {"element1","element2",.....};
List<String> mList = new ArrayList<String>(Arrays.asList(mArray));
vAdapter = new ArrayAdappter(getActivity(),R.layout.list_item_data,mList);

在 onPostExecute() 方法

vAdapter.clear();
vAdapter.addAll(strings);

谢谢大家。