user1662334
user1662334

Reputation: 669

How to use boolean value returned by a method

I just want to know how to use a boolean value returned from a method.This is the method which is returning the value:

 public  boolean hasConnection() {
            ConnectivityManager cm = (ConnectivityManager) MCQ.this.getBaseContext().getSystemService(
                Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetwork != null && wifiNetwork.isConnectedOrConnecting()) {
              return true;
            }

            NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mobileNetwork != null && mobileNetwork.isConnectedOrConnecting()) {
              return true;
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
              return true;
            }

            return false;
          }

This is the method where i want to use this value:

public void setScrollViewLayoutMarginBottom()
     {
         Resources resources = this.getResources();
          DisplayMetrics metrics = resources.getDisplayMetrics();

          Boolean b = hasConnection();

         if(b == true)
         {
             px = 90 * (metrics.densityDpi/160f); 
         }
         else
             px = 60 * (metrics.densityDpi/160f); 


         layoutParams.bottomMargin = (int) px;
            layoutParams.setMargins(0, 0, 0, (int) px);
            sv.setLayoutParams(layoutParams);
     }

Please help me.Thanks in advance.

Upvotes: 0

Views: 459

Answers (2)

NCode
NCode

Reputation: 2808

You dont' need to save the return value in a variable, just use it directly. if(booleanValue == true) will be true or false, so just remove the == true, it's obsolete

     if(hasConnection()) {
         px = 90 * (metrics.densityDpi/160f); 
     } else {
         px = 60 * (metrics.densityDpi/160f); 
     }

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502236

You're already using the return value, although you're boxing it into a Boolean instead of just using boolean for no particular reason - and you're explicitly comparing it with true, which is unusual.

I'd probably use a conditional operator instead, actually:

int scale = hasConnection() ? 90 : 60;
px = scale * (metrics.densityDpi / 160f);

Upvotes: 5

Related Questions