0

我知道这被问了好几次,但我不知道如何将更多数据加载到我的列表视图中。

我正在使用此代码调用列表视图的第一个数据,没关系,在加载数据后,我显示了一个按钮来加载更多结果,但没有显示任何新的列表视图:

编辑:现在它正在从服务器加载数据,但它没有将其附加到列表视图,而是用新内容替换内容,我该如何覆盖它?

编辑 2:我添加了 ListViewAdapter 的代码。感谢@aegean

public class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(MainActivity.this);
                // Set progressdialog title
                mProgressDialog.setTitle("Cargando reportes en tiempo real");
                // Set progressdialog message
                mProgressDialog.setMessage("Por favor espere");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions
                        .getJSONfromURL("http://www.videotrafico.com/api/timeline.php?page=1");

                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("datos");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject  = jsonarray.getJSONObject(i);
                        jsonobject1  = jsonobject.getJSONObject("reporte");
                        // Retrive JSON Objects
                        map.put("imagen", jsonobject.getString("imagen"));
                        map.put("quien", jsonobject.getString("quien"));
                        map.put("fecha", jsonobject.getString("fecha"));
                        map.put("reporte", jsonobject.getString("reporte"));
                        map.put("contenidopost", jsonobject1.getString("contenidopost"));
                        map.put("imgs", jsonobject1.getString("imgs"));
                        map.put("video", jsonobject1.getString("video"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {

                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.listview);
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(MainActivity.this, arraylist);

                Button btnLoadMore = new Button(MainActivity.this);
                btnLoadMore.setText("Cargar m‡s reportes");

                // Adding Load More button to lisview at bottom
                listview.addFooterView(btnLoadMore);


                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                //LoadMore button

                /**
                 * Listening to Load More button click event
                 * */
                btnLoadMore.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // Starting a new async task
                        new loadMoreListView().execute();
                    }
                });             
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }

这是加载更多按钮的类:

public class loadMoreListView extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                // Showing progress dialog before sending http request
                mProgressDialog = new ProgressDialog(
                        MainActivity.this);
                mProgressDialog.setMessage("Cargando más reportes");
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }

            protected Void doInBackground(Void... unused) {
                    // increment current page
                        current_page += 1;

                         arraylist = new ArrayList<HashMap<String, String>>();
                            // Retrieve JSON Objects from the given URL address
                            jsonobject = JSONfunctions
                                    .getJSONfromURL("http://www.videotrafico.com/api/timeline.php?page="+current_page);

                            try {
                                // Locate the array name in JSON
                                jsonarray = jsonobject.getJSONArray("datos");

                                for (int i = 0; i < jsonarray.length(); i++) {
                                    HashMap<String, String> map = new HashMap<String, String>();
                                    jsonobject  = jsonarray.getJSONObject(i);
                                    jsonobject1  = jsonobject.getJSONObject("reporte");
                                    // Retrive JSON Objects
                                    map.put("imagen", jsonobject.getString("imagen"));
                                    map.put("quien", jsonobject.getString("quien"));
                                    map.put("fecha", jsonobject.getString("fecha"));
                                    map.put("reporte", jsonobject.getString("reporte"));
                                    map.put("contenidopost", jsonobject1.getString("contenidopost"));
                                    map.put("imgs", jsonobject1.getString("imgs"));
                                    map.put("video", jsonobject1.getString("video"));
                                    // Set the JSON Objects into the array
                                    arraylist.add(map);
                                }
                            } catch (JSONException e) {
                                Log.e("Error", e.getMessage());
                                e.printStackTrace();
                            }

                return (null);
            }


            protected void onPostExecute(Void unused) {

                listview = (ListView) findViewById(R.id.listview);
                // closing progress dialog
                // get listview current position - used to maintain scroll position
                int currentPosition = listview.getFirstVisiblePosition();

                // Appending new data to menuItems ArrayList
                /*adapter = new ListViewAdapter(
                        MainActivity.this,
                        arraylist);
                listview.setAdapter(adapter);
                */
                ListViewAdapter myExistingAdapter = null;

                        if(listview.getAdapter() instanceof WrapperListAdapter) {
                            myExistingAdapter = (ListViewAdapter)((WrapperListAdapter)listview.getAdapter()).getWrappedAdapter();
                        } else if (listview.getAdapter() instanceof ListViewAdapter) {
                            myExistingAdapter = (ListViewAdapter)listview.getAdapter();
                        }
                        myExistingAdapter.setItems();
                        myExistingAdapter.notifyDataSetChanged();
                // Setting new scroll position
                listview.setSelectionFromTop(currentPosition + 1, 0);
                mProgressDialog.dismiss();
            }
        }
    public class ListViewAdapter extends BaseAdapter {

        // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        ImageLoader imageLoader;
        HashMap<String, String> resultp = new HashMap<String, String>();
        String coment;
        public String img;
        public int imga;
        public ListViewAdapter(Context context,
                ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
            imageLoader = new ImageLoader(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            // Declare Variables
            TextView quien;
            ImageView imagen;
            TextView reporte;
            TextView fecha;
            VideoView video;
            ImageView imgs;

            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View itemView = inflater.inflate(R.layout.listview_item, parent, false);
            // Get the position
            resultp = data.get(position);

            // Locate the TextViews in listview_item.xml
            // Locate the ImageView in listview_item.xml
            imagen = (ImageView) itemView.findViewById(R.id.imagen);
            fecha = (TextView) itemView.findViewById(R.id.fecha);
            quien = (TextView) itemView.findViewById(R.id.quien);
            reporte = (TextView) itemView.findViewById(R.id.reporte);
            video = (VideoView) itemView.findViewById(R.id.videos);
            imgs = (ImageView) itemView.findViewById(R.id.imgs);
            // Capture position and set results to the TextViews
         // Capture position and set results to the ImageView
            // Passes flag images URL into ImageLoader.class
            imageLoader.DisplayImage(resultp.get(MainActivity.IMAGEN), imagen);
            fecha.setText(resultp.get(MainActivity.FECHA));
            reporte.setText(resultp.get(MainActivity.CONTENIDOPOST));
            quien.setText(resultp.get(MainActivity.QUIEN));

            if (resultp.get(MainActivity.VIDEO).length() != 0){
                imageLoader.DisplayImage(resultp.get(MainActivity.IMGS), imgs);

                final String videoplayer = resultp.get(MainActivity.VIDEO);

                if (resultp.get(MainActivity.CONTENIDOPOST).length() == 0){
                    reporte.setVisibility(View.GONE);
                }

                imgs.setVisibility(View.VISIBLE);

                imgs.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(videoplayer));
                        context.startActivity(intent);
                    }
                });

            }

            if (resultp.get(MainActivity.IMGS).length() != 0 && resultp.get(MainActivity.VIDEO).length() <= 5){
                imageLoader.DisplayImage(resultp.get(MainActivity.IMGS), imgs);
                final String imagenview = resultp.get(MainActivity.IMGS);
                imgs.setVisibility(View.VISIBLE);
                if (resultp.get(MainActivity.CONTENIDOPOST).length() == 0){
                    reporte.setVisibility(View.GONE);
                }
                imgs.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        /*
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setDataAndType(Uri.parse(imagenview), "image/*");
                        context.startActivity(intent);
                        */
                        Intent intentBrowseFiles = new Intent(Intent.ACTION_VIEW);
                        intentBrowseFiles.setDataAndType(Uri.parse(imagenview), "image/*");
                        //intentBrowseFiles.setFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentBrowseFiles);

                    }
                });

            }
            return itemView;
        }
    }

我做错了什么?提前致谢!

4

1 回答 1

3

现在它正在从服务器加载数据,但它没有将其附加到列表视图,而是用新内容替换内容,我该如何覆盖它?

因为您正在创建一个新适配器:

adapter = new ListViewAdapter(MainActivity.this, arraylist);

尝试将新项目添加到现有适配器。

listview = (ListView) findViewById(R.id.listview);
ListViewAdapter myExistingAdapter = null

if(listview.getAdapter() instanceof WrapperListAdapter) {
    myExistingAdapter = (ListViewAdapter)((WrapperListAdapter)listview.getAdapter()).getWrappedAdapter();
} else if (listview.getAdapter() instanceof ListViewAdapter) {
    myExistingAdapter = (ListViewAdapter)listview.getAdapter();
}
myExistingAdapter.addItems(items);
myExistingAdapter.notifyDataSetChanged();

注意:要使用类似 setItems() 的方法,我假设您有一个方法来设置数组适配器的项目。

在您的 ListViewAdapter 类下编写一个方法来更新适配器内的项目:

public void addItems(ArrayList itemToAdd) {
    if(data != null) {
         data.addAll(itemToAdd);  
    } else {
         data = itemToAdd;
    }
}

顺便说一句,我建议您阅读更多关于 listView 和适配器的内容。因为你的实现不是很好。你必须重用你的观点。在此处查看示例

于 2013-11-02T18:13:59.287 回答