草庐IT

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

coder 2023-12-27 原文

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

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

最佳答案

你试试这个:

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

}

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

关于android - 如何将数据添加到 listView 的自定义 BaseAdapter - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18348123/

有关android - 如何将数据添加到 listView 的自定义 BaseAdapter - Android的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  5. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐