+ -

Pages

Tuesday, 4 February 2014

Error in openSearch and openSettings methods

If you're beginning to learn Android using official Android Guide, you're going to have a hard time. That's what I am having right now.

While making the Action Bar, the guide says to use openSearch() for to trigger search action and openSettings() to go to settings. I thought it's re-defined functions and I'd not have to do anything with this. How could that would be? But no, that's not true.

Error Screenshot :


To get rid of these errors, you need to make functions for these two actions.

Apparently, these methods are just examples that Google put in to show how you would use a switch statement. You can put anything you want in there, but I think the point is to make function calls from a switch statement, instead of putting the code of a function in the statement, to keep code clean.

So, you got to declare your own methods like this:

private void  openSearch(){
    //your code here
}

private void  openSettings(){
    //your code here
}

To get this action bar to work, we need to do something with '//your code here'. What that could be? 

To open settings, you can use 
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
this should do it for opening the settings.

To open search, it depends upon what we need to do with that and where it must take us after searching and what it is searching for. As there is nothing like this as of now, I am more interested in just checking if the button is working.

To see if the button is working, you can splash a toast notification to see something appear : 

private void openSearch() {
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}
This will show the text "Search button pressed" upon pressing the Search icon. So summing it up, I have used the following :

private void  openSearch(){
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}

private void  openSettings(){
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}

Note: You might need to import the Toast package which can be done by Ctrl+Shift+O. I already had it imported somehow.

Now everything works smooth as butter! 
As you can see those errors are gone now :

Here is how it looks now:

Search icon : 
Settings : 

5 Learning Android - from the scratch: Error in openSearch and openSettings methods If you're beginning to learn Android using official Android Guide, you're going to have a hard time. That's what I am having rig...

2 comments:

  1. Annoying that the let us, newcomers, to strugle with it. One would expect the examples to be complete/

    ReplyDelete
  2. Annoying that the let us, newcomers, to strugle with it. One would expect the examples to be complete/

    ReplyDelete

>