简体   繁体   中英

How do i Inherit the methods from a class and use them in another activity

I have a LoginActivity that checks if user is connected to the internet. And it works perfectly. But now I feel like my activities are full of too much code and would like to separate the internet checker from the Login Activity but im struggling to perform the method calls.

This is what I've tried:

InternetChecker class:

public class InternetChecker  {


public void checkNet(){

        if(connected()){
            Snackbar.make(findViewById(R.id.activity_login), "Your Internet Connection is Great",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE","User is connected");

        }else{
            Snackbar.make(findViewById(R.id.activity_login), "Your You are not Connected to the internet",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE","User is not connected");
        }

    }

    private boolean connected(){
        ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
    }
}

In this class I am getting an error on findViewById in the method checkNet(); in the private boolean connected(){ .

So I solved this by using extends AppCompatActivity in my InternetChecker class, the errors ( findViewbyId disappeared). I am just wondering if this is the correct convention and if not what should i extend?

But my main question is: In my LoginActivity which is meant to inherit the InterneChecker methods:

I have initialized the InternetChecker Class:

public class LoginActivity extends AppCompatActivity {

        private InternetChecker internetChecker = new InternetChecker();

Then I tried using InternetChecker inside a method named checkInternet which is in my LoginActivity class:

private void checkInternet(){
            InternetChecker = new InternetChecker();
        }

But i am getting the error expression expected on this line:

InternetChecker = new InternetChecker();

so i tried the following:

InternetChecker checkNet = new InternetChecker();

There are no errors this time, but CheckNet has a warning: variable checkNet is never used and when i run the app, the app does not call the InternetChecker methods and check if user is connected to the internet.

Please guide me on how I can inherit the methods in the class InternetChecker , and apply them to LoginActivity ?

NB: My Manifest has permissions set already:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

This is mySolution based on a combination of the answers below

I created a BaseActivity:

public class BaseActivity extends AppCompatActivity {
    public void checkNet(){

            if(connected()){
                Snackbar.make(findViewById(R.id.activity_login), "Your Internet Connection is Great",
                        Snackbar.LENGTH_LONG)
                        .setAction("Action", null).setActionTextColor(Color.RED).show();
                Log.i("TRUE","User is connected");

            }else{
                Snackbar.make(findViewById(R.id.activity_login), "Your You are not Connected to the internet",
                        Snackbar.LENGTH_LONG)
                        .setAction("Action", null).setActionTextColor(Color.RED).show();
                Log.i("TRUE","User is not connected");
            }
        }
    private boolean connected(){
        ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
    }
}

Then extended the BaseActivity in LoginActivity

public class LoginActivity extends BaseActivity {

I then created a method inside LoginActivity that calls checkNet :

private void checkInternet(){
    checkNet();
}

Then called this method in my LoginActivity's onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    checkInternet();

But if there are better ways to this than what I've done here, I would appreciate the answer so I can mark is as the correct answer.

The correct way would be to make a MiscUtils class

public class MiscUtils{
public static isConnected(Context context){
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
}

Now let all your activities extend a BaseActivity, which would extend the AppCompatActivity,

In the BaseActivity,

public class BaseActivity extends AppCompatActivity{

    public void showNoInternetMessage(View view){
     Snackbar.make(view, "Your You are not Connected to the internet",
                        Snackbar.LENGTH_LONG)
                        .setAction("Action", null).setActionTextColor(Color.RED).show();
                Log.i("TRUE","User is not connected");
    }
    }

Now from all your activities [Since they extend the BaseActivity], you can just call

if(MiscUtils.isConnectedToInternet(this)){
}else{
showNoInternetMessage(//Any view id from this activity);
}

You can make InternetChecket inherint from AppCompatActivity and then make your activity inherit from InternetChecker :

public class InternetChecker  extends AppCompatActivity{


public void checkNet(){



        if(connected()){
            Snackbar.make(findViewById(R.id.activity_login), "Your Internet Connection is Great",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE","User is connected");

        }else{
            Snackbar.make(findViewById(R.id.activity_login), "Your You are not Connected to the internet",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE","User is not connected");
        }

    }

private boolean connected(){
    ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}

and then:

public class LoginActivity extends InternetChecker

Now all methods in InternetChecker will be available to you in LoginActivity. And InternetChecker can call findViewById because it inherits this method from AppCompatActivity .

You can also make InternetChecker an utility class which is more common and I personally recommend:

public class InternetChecker{

private Context mContext;
public InternetChecker(Context context){
    mContext = context;
}
private boolean connected(){
    ConnectivityManager connectivityManager=(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}

And then whenever you want to check connectivity you just do within an activity:

InternetChecker checker = new InternetChecker(this);

if(checker.connected()){
//connected
}

Instead of keeping it inside an activity, you can create a common class(Common.java). There create this method as a static method.

public static boolean connected(Activity activity){
    ConnectivityManager connectivityManager=(ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}

Wherever you need this method call it like below.

Common.connected(activity);

There are 2 ways 1.You need to pass reference of your view in checkNet(View view) method and use this code

   public class InternetChecker {


    public void checkNet(View view,Activity activity) {


        if (connected(activity)) {
            Snackbar.make(view.findViewById(R.id.activity_login), "Your Internet Connection is Great",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE", "User is connected");

        } else {
            Snackbar.make(view.findViewById(R.id.activity_login), "Your You are not Connected to the internet",
                    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).setActionTextColor(Color.RED).show();
            Log.i("TRUE", "User is not connected");
        }

    }

    private boolean connected(Activity activity) {
        ConnectivityManager connectivityManager = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}
  1. Use interface for interaction

    public class InternetChecker {

     public void checkNet(snckbarInterFace snckbarInterFace,Activity activity ) { if (connected()) { snckbarInterFace.showConnected(); } else { snckbarInterFace.showNoConnected(); } } 

    }

and from your Login activity call method like this

  View rootView = getWindow().getDecorView().getRootView();
    new InternetChecker().checkNet(rootView);

Create a separate class which just checks for internet connection. And if you want to show snack bar then show in individual activity.

Code of Internet connection class:

public class InternetConnection
{
    private Context con;
    private static InternetConnection ic = null;

    public static synchronized InternetConnection getInstanceInternet(Context con)
    {
        if (ic == null)
        {
            ic = new InternetConnection(con);
        }

        return ic;
    }

    private InternetConnection(Context con)
    {
        this.con = con;
    }

    public boolean isNetworkAvailable()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

Usage of Above class: Create a global object of the class and initialize it in on create of the activity. Then just check for it like this:

if (internetConnection.isNetworkAvailable())
{
    /// internet is avalable
}
else
{
    /// internet not available
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM