Search code examples
androidandroid-layoutandroid-toolbarandroid-menu

Android toolbar icon handling with SQLite


I need hint to setup toolbar menu. How to change toolbar icon automatically when an Intent is open. I am using SQLite to save data for bookmarked posts. If user already bookmarked the post then toolbar icon will be change else icon will be same.

enter image description here

Let's take an example, in this image here is a bookmark button (Star) when I clicked on it data will save in Bookmark table. After that I Closed that post. Now I again open that post which is bookmarked but this time their is change in toolbar menu icon like this :

enter image description here

To perform this function data is loaded from bookmark table.

In my app no need to hold a post and show this toolbar. When someone click on post an intent is open. Toolbar of that intent will used for this functionality. Toolbar of post is here : https://i.sstatic.net/HWMF5.png and selected icon will change when clicked by user. Thanks in advance


Solution

  • Found solution : initialize an int before onCreate like this :

    int bkmark;
    

    than in onCreate get data from SQLite before initializing toolbar and check is this post is bookmarked or not.

    if data is available

    bkmark = 1;
    

    else

    bkmark = 0;
    

    In onCreateOptionsMenu I am using two menu like this

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
        if(bkmark == 0){//bkmark is not available
             getMenuInflater().inflate(R.menu.posts, menu);
        }else{//bkmark is available
             getMenuInflater().inflate(R.menu.postb, menu);
        }
        return true;
    }
    

    In onOptionsItemSelected

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id==R.id.bkm){
             if(bkmark == 1){
                 //delete data from bookmark table here
                 item.setIcon(R.drawable.ic_bookmark);//changing the icon
                 bkmark = 0;
             }else{
                 //insert data in bookmark table here
                 item.setIcon(R.drawable.ic_bookmarked);//changing the icon
                 bkmark = 1;
             }
        }
        return super.onOptionsItemSelected(item);
    }
    

    Hope this post help you if you are looking something like this !