Evan Dyson
Evan Dyson

Reputation: 195

Network check from options menu in Android

I know that onCreateOptionsMenu is only called once on an activity, but is it possible to set a network check on onOptionsItemSelected?

I have tried using ConnectivityManager network checks when an item is selected, but it always returns true... I'm not sure if it is set when the onCreateOptionsMenu is called and then locking in the network state.

Here is my code:

public void refreshCheck(){

try
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if(cm == null)
        isAvailable = false;
    else
        isAvailable = cm.getActiveNetworkInfo().isAvailable();
}
catch(Exception e){}

if(isAvailable == true)
{   

    listDataPopulate();    

}
else
{
    Toast refresherror = Toast.makeText(this, "Connection interrupted. Unable to refresh.", duration);
    refresherror.show();    
}       

}

@Override
public boolean onCreateOptionsMenu(Menu menu){

MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.news_menu, menu);
return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item){

switch(item.getItemId())
{
case R.id.aboutMenuItem:
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setTitle("About App").setMessage("About this app....").setNeutralButton("OK", null).show();
break;
case R.id.refreshNewsMenuItem:

    refreshCheck();

break;
default:
}
{

}
return super.onOptionsItemSelected(item);
}

Upvotes: 0

Views: 112

Answers (1)

FoamyGuy
FoamyGuy

Reputation: 46856

put your logic checking (and the reaction to what you find) inside of onPrepareOptionsMenu() instead.

That method gets called each time the options menu is opened, instead of just the first time. This way it will check each time the user opens the options whether or not it has connection, and thus should show the refresh option.

Upvotes: 1

Related Questions