jjzjj

android - 自定义 adapter.notifyDataSetChanged() 不工作

coder 2023-12-09 原文

我正在使用 ListView 的自定义适配器来显示图像和标题。 在我的应用程序中,我添加和删除了列表中的项目,我必须在界面上显示这些更改。 在数据发生任何变化时,我从数据库中获取所有列表并将其存储在适配器列表中,然后调用 adapter.notifyDataSetChanged();但界面没有显示任何变化。 另一方面,当我直接从适配器中添加或删除项目时,它会正确响应。 我使用了简单的适配器和那个适配器。notifyDataSetChanged();工作正常,但对于定制它没有响应。 我还在 stackoverflow 上尝试了很多解决方案,但没有一个有效。 喜欢 Updating the list view when the adapter data changes

Android List view refresh

Adapter.notifyDataSetChanged() is not working

notifyDataSetChange not working from custom adapter

我这样做如下 在创建

enter code here

            product_data = new ArrayList<Product>();
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        value = extras.getInt("list_id");
    }
    product_data = db.getAllProductsstatus(value, 1);
    Collections.reverse(product_data);

    adapter = new ProductAdopter(this, 
            R.layout.listview_item_row, product_data, 2);
    ListView listView1 = (ListView)findViewById(R.id.listView1);
    listView1.setAdapter(adapter);
    registerForContextMenu(listView1);

并在 onMenuItemSelected 中

enter code here
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

      int menuItemIndex = item.getItemId();
      String listItemName = adapter.getItem(info.position)._name;
      int id = adapter.getItem(info.position)._id;

         if(menuItemIndex == 0)
        {

            db.deleteProduct(adapter.getItem(info.position));

            product_data = db.getAllProducts(value);
            Collections.reverse(product_data);
            //adapter.remove(adapter.getItem(info.position));
            adapter.notifyDataSetChanged();
        }
        else if(menuItemIndex == 1){
            String name ;
            if (adapter.getItem(info.position)._status == 0){
                popall("bar code", "no bar code entered");                  
            }
            else {
            popall("bar code", adapter.getItem(info.position)._bar_code);
            }
        }
        else if (menuItemIndex == 2){
            adapter.getItem(info.position)._status = 0;
            adapter.getItem(info.position)._bar_code = "0";
            db.updateProduct(adapter.getItem(info.position));
                product_data = db.getAllProductsstatus(value, 1);
            adapter.notifyDataSetChanged();

            popall("alert", "successfully done");
        }
      return true;
}

下面给出了我自定义的适配器类

public class ProductAdopter extends ArrayAdapter<Product> {
    Context context; 
    int layoutResourceId;    
    List<Product> data = null;
    int source;
    public ProductAdopter(Context context, int layoutResourceId, List<Product> product_data, int source) {
        // TODO Auto-generated constructor stub
        super(context, layoutResourceId, product_data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = product_data;
        this.source = source;
    }
   // public ProductAdopter(MainActivity context2, int listviewItemRow, List<Product> product_data) {
        // TODO Auto-generated constructor stub
    //}
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ProductHolder holder = null;

        if(row == null && source == 1)
        {
            LayoutInflater inflater = ((MainActivity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ProductHolder();
            holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
            holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

            row.setTag(holder);
        }
        if(row == null && source == 2)
        {
            LayoutInflater inflater = ((purchased)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ProductHolder();
            holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
            holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

            row.setTag(holder);
        }
        if(row == null && source == 3)
        {
            LayoutInflater inflater = ((Skiped)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ProductHolder();
            holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
            holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

            row.setTag(holder);
        }


        else
        {
            holder = (ProductHolder)row.getTag();
        }

        Product product = data.get(position);
        holder.txtTitle.setText(product.getName());
        if(product.icon.equals("no")){
            holder.imgIcon.setImageResource(R.drawable.blank);
        }
        else{
            File imgFile = new  File(product.icon);
            if(imgFile.exists()){

                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                Bitmap resized = Bitmap.createScaledBitmap(myBitmap, 70, 70, true);

                holder.imgIcon.setImageBitmap(resized); 
                myBitmap.recycle();
            }           
        }

        return row;
    }
    static class ProductHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
    }

}

最佳答案

问题是在您的 onMenuItemSelected() 中有这一行:

product_data = db.getAllProducts(value);

当您在 onCreate() 中创建适配器时,您为它提供了对 product_data 的引用。那时您对 product_data 的更改将传播到适配器中,因为它引用了您的列表。

但是一旦您将新列表分配给您的 product_data 变量(就像您在 onMenuItemSelected() 中所做的那样),适配器现在就会引用旧列表,而您的 product_data 现在指向一个新列表。因此您的适配器不知道您在新列表中所做的更改。

不要重新分配变量,而是尝试清除它并像这样复制您的项目:

product_data.clear();
product_data.addAll(db.getAllProducts(value));

另一方面,如果您从数据库中读取数据,则应考虑使用 CursorAdapter

这是一个简单的教程: http://blog.cluepusher.dk/2009/11/16/creating-a-custom-cursoradapter-for-android/

关于android - 自定义 adapter.notifyDataSetChanged() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16282643/

有关android - 自定义 adapter.notifyDataSetChanged() 不工作的更多相关文章

  1. 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

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. 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

  4. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  9. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  10. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

随机推荐