jjzjj

java - 删除后按后退按钮更新购物车计数

coder 2023-12-05 原文

我有两个 Activity ,一个是 UserActivity,另一个是 CartActivity 我在 UserActivity 中显示产品列表。单击按钮 AddtoCart 我将产品添加到购物车。我面临这个问题:

当我添加单击按钮 AddtoCart 时,操作栏中有一个购物车图标,我有一个 textview 的自定义布局,在该购物车图标上显示购物车计数器。每当我单击 AddtoCart 按钮时,该计数器就会更新。现在我转到 CartActivity 并从购物车中删除一些产品。当我现在按下后退按钮返回到 UserActivity 时,计数器 TextView 不会更新。

我已经阅读了一些关于按下后退进行更新的方法,如此处的问题 Back button and refreshing previous activity 所示。 .答案中给出的两种方法是覆盖 UserActivityOnResume() 方法或通过启动结果 Activity 。

我想当我按下后退按钮并从Counter TextView 中的原始产品数量并更新 TextView 。

这是 UserActivity 的部分代码,我只有在这段代码中有更新购物车计数器的功能,当我点击一个按钮时调用。 onActivityResult() 的代码也在评论中,我从上面给出的 SO 问题链接的答案中尝试过。不成功:

    public class UserActivity extends AppCompatActivity{
            private int cartindex = 0;
            private TextView counterTV = null;
            
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_user);
              
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
            }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 1) {
//
//            if(resultCode == RESULT_OK){
//                  Intent intent = getIntent();
//                  Integer deletecounter = intent.getIntExtra("DeleteCounter",0);
//                  if(deletecounter>0){
//                      UpdateCartCount(Integer.parseInt(counterTV.getText().toString())-deletecounter);
//                  }
//            }
//        }
//    }
            
        @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.user, menu);
                final View menu_list = menu.findItem(R.id.action_hawk).getActionView();
                counterTV = (TextView) menu_list.findViewById(R.id.cartcounter);
                UpdateCartCount(cartindex);
                new MyMenuItemStuffListener(menu_hotlist, "Show message") {
                    @Override
                    public void onClick(View v) {
                        Intent intent= new  Intent(UserActivity.this,CartActivity.class);
                        intent.putExtra("ProductTitle",pname);
                        intent.putExtra("ProductUrl",purl);
                        intent.putExtra("ProductPrice",pprice);
                        intent.putExtra("BargainPrice",bargainprice);
                        UserActivity.this.startActivity(intent);
                    }
                };
                return true;
    }
    //Function to update cart count
            public void UpdateCartCount(final int new_number) {
                    cartindex = new_number;
                    if (counterTV == null) return;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (new_number == 0)
                                counterTV.setVisibility(View.INVISIBLE);
                            else {
                                counterTV.setVisibility(View.VISIBLE);
                                counterTV.setText(Integer.toString(new_number));
                            }
                        }
                    });
                }

这是 CartActivity 的代码:

    public class CartActivity extends AppCompatActivity {
    
        private List<Product> mCartList;
        private ProductAdapter mProductAdapter;
        private static List<Product> cart;
        private static Integer deletecounter= 0;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_cart);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            mCartList = getCart();
    
    
            Intent intent = getIntent();
            String ProductTitle = intent.getStringExtra("ProductTitle");
            String ProductUrl = intent.getStringExtra("ProductUrl");
            String ProductPrice = intent.getStringExtra("ProductPrice");
            String BargainPrice = intent.getStringExtra("BargainPrice");
            Product product = new Product(ProductTitle, ProductUrl, ProductPrice, BargainPrice);
            mCartList.add(product);
            // Make sure to clear the selections
            for (int i = 0; i < mCartList.size(); i++) {
                mCartList.get(i).selected = false;
            }
    
            // Create the list
            final ListView listViewCatalog = (ListView) findViewById(R.id.cart_list_view);
            mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true, CartActivity.this);
            listViewCatalog.setAdapter(mProductAdapter);
    
            listViewCatalog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
    
                    Product selectedProduct = mCartList.get(position);
                    if (selectedProduct.selected)
                        selectedProduct.selected = false;
                    else
                        selectedProduct.selected = true;
    
                    mProductAdapter.notifyDataSetInvalidated();
    
                }
            });
            FloatingActionButton Delete = (FloatingActionButton) findViewById(R.id.fab);
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Loop through and remove all the products that are selected
                    // Loop backwards so that the remove works correctly
    
                    for (int i = mCartList.size() - 1; i >= 0; i--) {
    
                        if (mCartList.get(i).selected) {
                            mCartList.remove(i);
                            deletecounter++;
                        }
                    }
// THIS IS THE CODE I USED TO RETURN DATA TO PREVIOUS ACTIVITY BUT UserActivity STARTS AUTOMATICALLY AFTER DELETION OF SELECTED PRODUCTS AS SOON AS I CLICK THE DELETE BUTTON EVEN WHEN THERE ARE PRODUCTS IN THE CART.
 //                  if(deletecounter!=0) {
//                    Intent i = new Intent(HawkActivity.this, UserActivity.class);
//                    startActivityForResult(i, 1);
//                    Intent returnIntent = new Intent();
//                    returnIntent.putExtra("DeleteCounter", deletecounter);
//                    setResult(RESULT_OK, returnIntent);
//                }
                    mProductAdapter.notifyDataSetChanged();
                    Snackbar.make(view,"Selected items deleted successfully",Snackbar.LENGTH_SHORT).show();
                }
            }
            );
        }
        public static List<Product> getCart() {
            if(cart == null) {
                cart = new Vector<Product>();
            }
    
            return cart;
        }
    }

当我使用在两个 Activity 中被注释掉的代码时,即使用 start Activity 作为结果方法时,会发生这种情况: 当我点击删除按钮时,项目被删除但 CartActivity 自动关闭。即使购物车中有产品,带有计数器 TextView 的 UserActivity 也显示为“0”值。

请告诉我您需要从代码中获得的任何其他信息。欢迎使用在删除 CartActivity 中的某些项目后按下后退按钮更新购物车计数器的任何其他方法。感谢您的帮助。

最佳答案

使用

invalidateOptionsMenu();

onActivityResult 中再次填充菜单。

你的 UserActivity 代码应该是这样的:

public class UserActivity extends AppCompatActivity {
    private int cartindex = 0;
    private TextView counterTV = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {

            if (resultCode == RESULT_OK) {
                Intent intent = getIntent();
                Integer deletecounter = intent.getIntExtra("DeleteCounter",0);
                if (deletecounter>0) {
                    cartindex=Integer.parseInt(counterTV.getText().toString())-deletecounter;
                    invalidateOptionsMenu();
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.user, menu);
        final View menu_list = menu.findItem(R.id.action_hawk).getActionView();
        counterTV = (TextView) menu_list.findViewById(R.id.cartcounter);
        UpdateCartCount(cartindex);
        new MyMenuItemStuffListener(menu_hotlist, "Show message") {
            @Override
            public void onClick(View v) {
                Intent intent= new  Intent(UserActivity.this,CartActivity.class);
                intent.putExtra("ProductTitle",pname);
                intent.putExtra("ProductUrl",purl);
                intent.putExtra("ProductPrice",pprice);
                intent.putExtra("BargainPrice",bargainprice);
                UserActivity.this.startActivity(intent);
            }
        };
        return true;
    }

    //Function to update cart count
    public void UpdateCartCount(final int new_number) {
        cartindex = new_number;
        if (counterTV == null) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (new_number == 0)
                    counterTV.setVisibility(View.INVISIBLE);
                else {
                    counterTV.setVisibility(View.VISIBLE);
                    counterTV.setText(Integer.toString(new_number));
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        if (CartActivity.cart.size()!=0) {
            cartindex=CartActivity.cart.size(); 
            invalidateOptionsMenu();
            super.onRestart()
        }

关于java - 删除后按后退按钮更新购物车计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34411960/

有关java - 删除后按后退按钮更新购物车计数的更多相关文章

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

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby-on-rails - Ruby on Rails 计数器缓存错误 - 2

    尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby - 使用多个数组创建计数 - 2

    我正在尝试按0-9和a-z的顺序创建数字和字母列表。我有一组值value_array=['0','1','2','3','4','5','6','7','8','9','a','b','光盘','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','','u','v','w','x','y','z']和一个组合列表的数组,按顺序,这些数字可以产生x个字符,比方说三个list_array=[]和一个当前字母和数字组合的数组(在将它插入列表数组之前我会把它变成一个字符串,]current_combo['0','0','0']

  10. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

随机推荐