Alanagh Alanagh - 1 month ago 13
Java Question

Using classes in android - working with Context and helper classes

I am still newbie to android, please could someone help.
I want to use methods from the Net class as follows:

package com.test;


import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

public class MyApp extends Activity {
/** Called when the activity is first created. */
private Net wifi;


TextView textStatus; @Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);


wifi=new Net(this);
textStatus = (TextView) findViewById(R.id.text);
textStatus.append("Your online status is ");

if (wifi.isOnline()){

textStatus.append("online "+wifi.getInfo());
}
else{
textStatus.append("offline "+wifi.getInfo());

}
}
}


and my Net class

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;



public class Net{
WifiManager wifi;
ConnectivityManager cm ;
NetworkInfo netInfo ;

public Net (Context ctx) {
cm = (ConnectivityManager) ctx.getSystemService(ctx.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
}

public boolean isOnline() {

netInfo = cm.getActiveNetworkInfo();

if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
else{
return false;
}

}
public NetworkInfo[] getName(){



NetworkInfo[] name=cm.getAllNetworkInfo();
return name;

}

public String getInfo(){


// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
return info.getSSID().toString();
}

}


I believe I should not be extending my Net class with Activity? I am getting source not found error when run the app.

Answer

I believe I should not be extending my Net class with Activity?

Correct!

Your 'Net' class is simply a 'helper' so can be simply defined as...

public class Net {

    public Net (Context ctx) {
        cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = cm.getActiveNetworkInfo();
    }

    // Your other methods here...
}

When you create your 'wifi' object, use wifi = new Net(this);

The Activity class in Android is used to provide a UI framework for visual/interactive elements such as buttons, textviews etc. etc. - basically anything the user needs to interact with. This isn't appropriate for your 'Net' class.

Comments