如何将数据添加到 listView 的自定义 BaseAdapter - Android

Posted

技术标签:

【中文标题】如何将数据添加到 listView 的自定义 BaseAdapter - Android【英文标题】:How to add data to custom BaseAdapter for listView - Android 【发布时间】:2013-08-23 06:37:15 【问题描述】:

我有一个自定义 BaseAdapter 类,它为 cmets、用户名和数字创建视图。此 BaseAdapter 从 An AsyncTask 接收此信息。当用户到达 listView 的底部时,AsyncTask 运行。问题是 BaseAdapter 不会添加新数据。当我尝试添加新数据时,它会删除列表中的当前数据,然后添加新数据。我希望它保留所有数据,并将数据添加到 listView 的底部。所有这些类都在同一个活动中。这是我当前的代码。

class CreateCommentLists extends BaseAdapter
                Context ctx_invitation;
                String[] listComments;
                String[] listNumbers;
                String[] listUsernames;


                public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
                
                    super();
                    ctx_invitation = context;
                    listComments = comments;
                    listNumbers = usernames;
                    listUsernames = numbers;

                

                @Override
                public int getCount() 
                    if(null == listComments)
                    
                    return 0;
                       

                    // TODO Auto-generated method stub
                    return listComments.length;
                

                @Override
                public Object getItem(int position) 
                    // TODO Auto-generated method stub
                    return listComments[position];
                

                @Override
                public long getItemId(int position) 
                    // TODO Auto-generated method stub
                    return 0;
                

                @Override
                public View getView(final int position, View convertView, ViewGroup parent) 
                    // TODO Auto-generated method stub
                    View v = null;
                    try
                    
                        String inflater = Context.LAYOUT_INFLATER_SERVICE;
                        LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
                        v = li.inflate(R.layout.list_item, null);


                        TextView commentView = (TextView)v.findViewById(R.id.listComment);
                        TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
                        TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
                        Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
                       Button numberButton = (Button)v.findViewById(R.id.listNumberButton);

                        commentView.setText(listComments[position]);
                        NumbersView.setText(listNumbers[position]);
                        usernamesView.setText(listUsernames[position]);




                       usernameButton.setOnClickListener(new View.OnClickListener() 

                           public void onClick(View view) 
                               Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
                               i.putExtra("usernameOfProfile",listUsernames[position]);
                               startActivity(i);
                               finish();
                           
                       );

                       numberButton.setOnClickListener(new View.OnClickListener() 

                           public void onClick(View arg0) 
                               Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
                               i.putExtra("NumberProfile",listNumbers[position]);
                               startActivity(i);
                               finish();
                           
                       );





                    
                    catch(Exception e)
                    
                        e.printStackTrace();
                    
                    return v;
                

            public void add(String[] comments, String[] usernames,
                    String[] numbers) 
                listComments = comments;
                listNumbers = usernames;
                listUsernames = numbers;
            

            public int getCount1() 
                if(null == listComments)
                
                return 0;
                   

                // TODO Auto-generated method stub
                return listComments.length;
            

            public Object getItem1(int position) 
                // TODO Auto-generated method stub
                return listComments[position];
            

            public long getItemId1(int position) 
                // TODO Auto-generated method stub
                return 0;
            

            public View getView1(final int position, View convertView, ViewGroup parent) 
                // TODO Auto-generated method stub
                View v = null;
                try
                
                    String inflater = Context.LAYOUT_INFLATER_SERVICE;
                    LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
                    v = li.inflate(R.layout.list_item, null);


                    TextView commentView = (TextView)v.findViewById(R.id.listComment);
                    TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
                    TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
                    Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
                   Button numberButton = (Button)v.findViewById(R.id.listNumberButton);

                    commentView.setText(listComments[position]);
                    NumbersView.setText(listNumbers[position]);
                    usernamesView.setText(listUsernames[position]);




                   usernameButton.setOnClickListener(new View.OnClickListener() 

                       public void onClick(View view) 
                           Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
                           i.putExtra("usernameOfProfile",listUsernames[position]);
                           startActivity(i);
                           finish();
                       
                   );

                   numberButton.setOnClickListener(new View.OnClickListener() 

                       public void onClick(View arg0) 
                           Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
                           i.putExtra("NumberProfile",listNumbers[position]);
                           startActivity(i);
                           finish();
                       
                   );





                
                catch(Exception e)
                
                    e.printStackTrace();
                
                return v;






               




            final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);

            lstComments = (ListView)findViewById(android.R.id.list);

            lstComments.setAdapter(mycmlist);

final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
            class loadComments extends AsyncTask<JSONObject, String, JSONObject> 



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


                    progDailog.setIndeterminate(false);
                    progDailog.setCancelable(true);
                    progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    progDailog.show();
                    progDailog.setContentView(R.layout.progress_circle);


                 

                @Override
                protected void onProgressUpdate(String... values) 
                    super.onProgressUpdate(values);

                 

                protected JSONObject doInBackground(JSONObject... params) 


                    JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);


                        return json2;



                

                @Override
                protected void onPostExecute(JSONObject json2) 
                    try   
                        if (json2.getString(KEY_SUCCESS) != null)  
                            registerErrorMsg.setText("");
                            String res2 = json2.getString(KEY_SUCCESS);
                            if(Integer.parseInt(res2) == 1) 



                                JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
                                String comments[] = new String[commentArray.length()];
                                for ( int i=0; i<commentArray.length(); i++ ) 
                                    comments[i] = commentArray.getString(i);
                                
                                JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
                                String numbers[] = new String[numberArray.length()];
                                for ( int i=0; i<numberArray.length(); i++ ) 
                                    numbers[i] = numberArray.getString(i);
                                
                                JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
                                String usernames[] = new String[usernameArray.length()];
                                for ( int i=0; i<usernameArray.length(); i++ ) 
                                    usernames[i] = usernameArray.getString(i);
                                



                                mycmlist.add(comments,usernames,numbers);
                                mycmlist.notifyDataSetChanged();








                                //end if key is == 1
                            else
                                // Error in registration
                                registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
                            //end else
                        //end if
                     //end try

                    catch (JSONException e)  
                        e.printStackTrace();
                    //end catch    
                    progDailog.dismiss();

                


            



            mainListView = (ListView) findViewById(android.R.id.list);



            class EndlessScrollListener implements OnScrollListener 
                private int i = 0;
                private int visibleThreshold = 5;
                private int previousTotal = 0;
                private boolean loading = true;

                public EndlessScrollListener() 
                
                public EndlessScrollListener(int visibleThreshold) 
                    this.visibleThreshold = visibleThreshold;
                

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) 


                       if ((firstVisibleItem + visibleItemCount) == totalItemCount) 
                           new loadComments().execute();
                        mainListView.smoothScrollToPosition(0);

                    


                

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) 
                 
            

            mainListView.setOnScrollListener(new EndlessScrollListener());

【问题讨论】:

我在您的 BaseAdapter 实现中没有看到 add 方法... add方法应该是什么? 对于线路:mycmlist.add(comments,usernames,numbers); 那个方法在哪里?我在您发布的代码中没有看到它。或者,也许我只是个盲人。 :P 它不存在,我没有创建一个大声笑。这一定是它根本不起作用的原因。 add 方法应该是什么?它是如何工作的? 好吧,如果没有 add 方法,那么您的代码在尝试编译时必须抛出错误。它根本不应该运行。 【参考方案1】:

你试试这个:

public class Comment 
String username;
String content;
String number;
 

类适配器:

public class CommentAdapter extends BaseAdapter 
private List<Comment> listComment;
private Context context;

public CommentAdapter(List<Comment> listComment, Context context) 
    super();
    this.listComment = listComment;
    this.context = context;


@Override
public int getCount() 

    return listComment.size();


@Override
public Comment getItem(int position) 
    return listComment.get(position);


@Override
public long getItemId(int arg0) 
    return 0;


@Override
public View getView(int position, View convertView, ViewGroup parent) 
    View v = convertView;
    if (v == null) 
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = mInflater.inflate(R.layout.comment_item, null);
    

    final TextView textViewUsername = (TextView) v
            .findViewById(R.id.comment_Username);
    final TextView textViewNumber = (TextView) v
            .findViewById(R.id.comment_number);
    final TextView textViewContent = (TextView) v
            .findViewById(R.id.comment_Content);

    final String username = listComment.get(position).getUsername();
    final String number= listComment.get(position).getNumber();
    String content = listComment.get(position).getContent();

    textViewUsername.setText(username);
    textViewNumber.setText(number);

    textViewContent.setText(content);
    return v;



当您需要向列表添加新评论时。只需创建新评论并添加到 listComment(listComment.add(newComment)),然后调用 adapter.notifyDataSetChanged();

【讨论】:

但在 Asynctask 中,它将多个 cmets、用户名和数字收集到字符串中。每次运行 asynctask 时创建多个 cmets 时,它不会创建 1 条新评论 您可以在AsyncTask内多次调用listComment(listComment.add(newComment))【参考方案2】:
package com.example.baseadapter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements OnItemClickListener 
    public static final String[] title = new String[] 
            "image 1", "image 2", "image 3", "image 4"
    ;

    public static final Integer[] images = 
            R.drawable.aa, R.drawable.bb, R.drawable.cc, R.drawable.cc, R.drawable.dd
    ;

    ListView listview;

    List<RowItem> rowItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < title.length; i++) 
            RowItem item = new RowItem(images[i], title[i]);
            rowItems.add(item);
        
        listview = (ListView)findViewById(R.id.listview);
        customBaseAdapter cba = new customBaseAdapter(this, rowItems);
        listview.setAdapter(cba);
        listview.setOnItemClickListener(this);

    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
        Toast.makeText(getApplicationContext(), "item selected", Toast.LENGTH_LONG).show();
    

    public class customBaseAdapter extends BaseAdapter 
        Context context;

        List<RowItem> rowItem;

        public customBaseAdapter(Context context, List<RowItem> listItem) 
            this.context = context;
            rowItem = listItem;
            Log.d("const", "const");
        

        @Override
        public int getCount() 
            Log.d("count", "count");
            return rowItem.size();
        

        @Override
        public Object getItem(int arg0) 
            Log.d("item", "item");
            return rowItem.get(arg0);
        

        @Override
        public long getItemId(int position) 
            Log.d("const", "item id");
            return rowItem.indexOf(getItem(position));
        

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
            Log.d("const", "getview");
            LayoutInflater inflater = (LayoutInflater)context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            RowItem rowitem = (RowItem)getItem(position);
            TextView textForTitle;
            ImageView imgForImage;
            convertView = inflater.inflate(R.layout.inflate, null);
            textForTitle = (TextView)convertView.findViewById(R.id.textview);
            imgForImage = (ImageView)convertView.findViewById(R.id.imageview);
            textForTitle.setText(rowitem.getTitle());
            imgForImage.setImageResource(rowitem.getImageId());

            return convertView;
        
    

    public class RowItem 
        int imageId;

        String title;

        public RowItem(int imageId, String title) 
            this.imageId = imageId;
            this.title = title;
        

        public int getImageId() 
            return imageId;
        

        public void setImageId(int imageId) 
            this.imageId = imageId;
        

        public String getTitle() 
            return title;
        

        public void setStringTitle(String title) 
            this.title = title;
        

        @Override
        public String toString() 
            return title;
        
    


【讨论】:

请添加一些说明,说明此代码如何解决问题,并正确格式化。 所有这些代码都以这种格式为我工作....如果您有任何理解问题,请告诉我,我会帮助您。

以上是关于如何将数据添加到 listView 的自定义 BaseAdapter - Android的主要内容,如果未能解决你的问题,请参考以下文章

Android:将数据添加到 ArrayAdapter 时可见的 ListView 图像闪烁

将动画添加到 ListView 以展开/折叠内容

如何删除android中的自定义列表视图项?

片段中的自定义列表适配器

ListView 中的自定义复选框

Android中项目的自定义ListView点击问题