Search code examples
javaandroidclipboardmanager

Declare a variable inside an if statement and have it known to following method calls


I'm writing something in Android and in order to tailor for an older SDK, I need to change what a variable becomes. I'm using ClipboardManager which has different versions based on SDK. The issue is to create this variable easily, I have to do it in an if, and my code won't compile after due to the variable not being detected.

Example:

if(android.os.Build.VERSION.SDK_INT >= 11){
    final android.content.ClipboardManager clipboard = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
} else {
    final android.text.ClipboardManager clipboard = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
}
if (clipboard.hasPrimaryClip()) {
    // Do stuff
}

Because the instance of clipboard depends on the SDK, if (clipboard.hasPrimaryClip()) complains at me.

Is there any way to do this other than making two variables and checking for null?


Solution

  • Declare it as a class member

    ClipboardManager clipboard;
    

    Then

    if(android.os.Build.VERSION.SDK_INT >= 11){
    clipboard = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
    }else {
     clipboard = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
    }
     if (clipboard.hasPrimaryClip()) {
    // Do stuff
    }
    

    Eidt to the edited question

       if(android.os.Build.VERSION.SDK_INT >= 11){
         final android.content.ClipboardManager clipboard =  (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
           if (clipboard.hasPrimaryClip()) {
            // Do stuff
            doSomething(); 
           }
       } else {
         final android.text.ClipboardManager clipboard =(ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
          if (clipboard.hasPrimaryClip()) {
            // Do stuff
            doSomething(); 
           }
       }
    

    Then

     public void doSomething()
     {
    
     }