将数据添加到自定义的BaseAdapter的ListView控件

将数据添加到自定义的BaseAdapter的ListView控件

本文介绍了如何将数据添加到自定义的BaseAdapter的ListView控件 - 机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建视图的评论,用户名和号码定制BaseAdapter类。这BaseAdapter接收来自AsyncTask的信息。该AsyncTask的,当用户到达列表视图的底部运行。问题是BaseAdapter惯于添加新数据。当我尝试添加新的数据将删除列表中的当前数据,然后添加新的数据。我希望它保留所有的数据,只是将数据添加到ListView的底部。所有这些类都在同一个活动。这是我目前的code。

 类CreateCommentLists扩展了BaseAdapter {
                语境ctx_invitation;
                的String [] listComments;
                的String [] listNumbers;
                的String [] listUsernames;


                公共CreateCommentLists(字符串[]评论的String []用户名,字符串[]号,DashboardActivity上下文)
                {
                    超();
                    ctx_invitation =背景;
                    listComments =意见;
                    listNumbers =用户名;
                    listUsernames =数字;

                }

                @覆盖
                公众诠释getCount将(){
                    如果(空== listComments)
                    {
                    返回0;
                    }

                    // TODO自动生成方法存根
                    返回listComments.length;
                }

                @覆盖
                公共对象的getItem(INT位置){
                    // TODO自动生成方法存根
                    返回listComments [位置]
                }

                @覆盖
                众长getItemId(INT位置){
                    // TODO自动生成方法存根
                    返回0;
                }

                @覆盖
                公共查看getView(最终诠释的立场,观点convertView,ViewGroup中父){
                    // TODO自动生成方法存根
                    视图V = NULL;
                    尝试
                    {
                        字符串充气= Context.LAYOUT_INFLATER_SERVICE;
                        LayoutInflater力=(LayoutInflater)ctx_invitation.getSystemService(充气);
                        V = li.inflate(R.layout.list_item,NULL);


                        TextView的评论查看=(TextView中)v.findViewById(R.id.listComment);
                        TextView的NumbersView =(TextView中)v.findViewById(R.id.listNumber);
                        TextView的usernamesView =(TextView中)v.findViewById(R.id.listPostedBy);
                        按钮usernameButton =(按钮)v.findViewById(R.id.listUsernameButton);
                       按钮numberButton =(按钮)v.findViewById(R.id.listNumberButton);

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




                       usernameButton.setOnClickListener(新View.OnClickListener(){

                           公共无效的onClick(视图查看){
                               意图I =新的意图(getApplicationContext(),ProfileActivity.class);
                               i.putExtra(usernameOfProfile,listUsernames [位置]);
                               startActivity(ⅰ);
                               完();
                           }
                       });

                       numberButton.setOnClickListener(新View.OnClickListener(){

                           公共无效的onClick(查看为arg0){
                               意图I =新的意图(getApplicationContext(),ProfileActivity.class);
                               i.putExtra(NumberProfile,listNumbers [位置]);
                               startActivity(ⅰ);
                               完();
                           }
                       });





                    }
                    赶上(例外五)
                    {
                        e.printStackTrace();
                    }
                    返回伏;
                }

            公共无效添加(字符串[]评论的String []用户名,
                    的String []号){
                listComments =意见;
                listNumbers =用户名;
                listUsernames =数字;
            }

            公众诠释getCount1(){
                如果(空== listComments)
                {
                返回0;
                }

                // TODO自动生成方法存根
                返回listComments.length;
            }

            公共对象getItem1(INT位置){
                // TODO自动生成方法存根
                返回listComments [位置]
            }

            众长getItemId1(INT位置){
                // TODO自动生成方法存根
                返回0;
            }

            公共查看getView1(最终诠释的立场,观点convertView,ViewGroup中父){
                // TODO自动生成方法存根
                视图V = NULL;
                尝试
                {
                    字符串充气= Context.LAYOUT_INFLATER_SERVICE;
                    LayoutInflater力=(LayoutInflater)ctx_invitation.getSystemService(充气);
                    V = li.inflate(R.layout.list_item,NULL);


                    TextView的评论查看=(TextView中)v.findViewById(R.id.listComment);
                    TextView的NumbersView =(TextView中)v.findViewById(R.id.listNumber);
                    TextView的usernamesView =(TextView中)v.findViewById(R.id.listPostedBy);
                    按钮usernameButton =(按钮)v.findViewById(R.id.listUsernameButton);
                   按钮numberButton =(按钮)v.findViewById(R.id.listNumberButton);

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




                   usernameButton.setOnClickListener(新View.OnClickListener(){

                       公共无效的onClick(视图查看){
                           意图I =新的意图(getApplicationContext(),ProfileActivity.class);
                           i.putExtra(usernameOfProfile,listUsernames [位置]);
                           startActivity(ⅰ);
                           完();
                       }
                   });

                   numberButton.setOnClickListener(新View.OnClickListener(){

                       公共无效的onClick(查看为arg0){
                           意图I =新的意图(getApplicationContext(),ProfileActivity.class);
                           i.putExtra(NumberProfile,listNumbers [位置]);
                           startActivity(ⅰ);
                           完();
                       }
                   });





                }
                赶上(例外五)
                {
                    e.printStackTrace();
                }
                返回伏;






              }




            最后CreateCommentLists mycmlist =新CreateCommentLists(注释,用户名,数字,DashboardActivity.this);

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

            lstComments.setAdapter(mycmlist);

最后ProgressDialog progDailog =新ProgressDialog(DashboardActivity.this);
            类loadComments扩展的AsyncTask< JSONObject的,字符串,JSONObject的> {



                @覆盖
                在preExecute保护无效(){
                    super.on preExecute();


                    progDailog.setIndeterminate(假);
                    progDailog.setCancelable(真正的);
                    。progDailog.getWindow()clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    progDailog.show();
                    progDailog.setContentView(R.layout.progress_circle);


                }

                @覆盖
                保护无效onProgressUpdate(字符串...值){
                    super.onProgressUpdate(值);

                }

                受保护的JSONObject doInBackground(JSONObject的... PARAMS){


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


                        返回json2;



                }

                @覆盖
                保护无效onPostExecute(JSONObject的json2){
                    尝试 {
                        如果(json2.getString(KEY_SUCCESS)!= NULL){
                            registerErrorMsg.setText();
                            字符串RES2 = json2.getString(KEY_SUCCESS);
                            如果(的Integer.parseInt(RES2)== 1){



                                JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
                                字符串评论[] =新的String [commentArray.length()];
                                的for(int i = 0; I< commentArray.length();我++){
                                    评论[I] = commentArray.getString(ⅰ);
                                }
                                JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
                                一串数字[] =新的String [numberArray.length()];
                                的for(int i = 0; I< numberArray.length();我++){
                                    号码[I] = numberArray.getString(ⅰ);
                                }
                                JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
                                字符串的用户名[] =新的String [usernameArray.length()];
                                的for(int i = 0; I< usernameArray.length();我++){
                                    用户名[I] = usernameArray.getString(ⅰ);
                                }



                                mycmlist.add(注释,用户名,数字);
                                mycmlist.notifyDataSetChanged();








                                } // end如果关键是== 1
                            其他{
                                //登记错误
                                registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
                            } //结束其他
                        }//万一
                    } //结束试

                    赶上(JSONException E){
                        e.printStackTrace();
                    } //结束抓
                    progDailog.dismiss();

                }


            }



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



            类EndlessScrollListener实现OnScrollListener {
                私人INT I = 0;
                私人诠释visibleThreshold = 5;
                私人诠释previousTotal = 0;
                私人布尔负荷=真;

                公共EndlessScrollListener(){
                }
                公共EndlessScrollListener(INT visibleThreshold){
                    this.visibleThreshold = visibleThreshold;
                }

                @覆盖
                公共无效onScroll(AbsListView观点,诠释firstVisibleItem,
                        INT visibleItemCount,诠释totalItemCount){


                       如果((firstVisibleItem + visibleItemCount)== totalItemCount){
                           新loadComments()执行();
                        mainListView.smoothScrollToPosition(0);

                    }


                }

                @覆盖
                公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){
                }
            }

            mainListView.setOnScrollListener(新EndlessScrollListener());
 

解决方案

您试试这个:

 公共类注释{
字符串的用户名;
字符串的内容;
串号;
 }
 

类适配器:

 公共类CommentAdapter扩展了BaseAdapter {
私人列表<注释> listComment;
私人上下文的背景下;

公共CommentAdapter(名单<注释> listComment,上下文语境){
    超();
    this.listComment = listComment;
    this.context =背景;
}

@覆盖
公众诠释getCount将(){

    返回listComment.size();
}

@覆盖
公开征求意见的getItem(INT位置){
    返回listComment.get(位置);
}

@覆盖
众长getItemId(INT为arg0){
    返回0;
}

@覆盖
公共查看getView(INT位置,查看convertView,ViewGroup中父){
    视图V = convertView;
    如果(V == NULL){
        LayoutInflater mInflater =(LayoutInflater)上下文
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        V = mInflater.inflate(R.layout.comment_item,NULL);
    }

    最后的TextView textViewUsername =(TextView中)V
            .findViewById(R.id.comment_Username);
    最后的TextView textViewNumber =(TextView中)V
            .findViewById(R.id.comment_number);
    最后的TextView textViewContent =(TextView中)V
            .findViewById(R.id.comment_Content);

    最终字符串username = listComment.get(位置).getUsername();
    最终的串号= listComment.get(位置).getNumber();
    字符串的内容= listComment.get(位置).getContent();

    textViewUsername.setText(用户名);
    textViewNumber.setText(数);

    textViewContent.setText(内容);
    返回伏;
}

}
 

当你需要新的注释添加到列表中。只要创建新的注释,并添加到listComment(listComment.add(newComment)),在这之后,调用adapter.notifyDataSetChanged();

I have a custom BaseAdapter class that creates views for comments, usernames, and numbers. This BaseAdapter receives this information from An AsyncTask. The AsyncTask runs when the user reaches the bottom of the listView. The problem is the BaseAdapter wont add new data. When I try to add new data it deletes the current data in the list and then adds the new data. I want it to keep all the data and just add data to the bottom of the listView. All of these classes are in the same Activity. Here is my current code.

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());
解决方案

You try this :

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

Class Adapter:

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

}

When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();

这篇关于如何将数据添加到自定义的BaseAdapter的ListView控件 - 机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:15