So I am quite new to Android, and have limited previous Java experience, so please bear with me. I am trying to create an object of type WifiManager in an Android App, and I have the line I found several other people recommend to create a WifiManager object verbatum:
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
in my program. Now Eclipse has underlined the mContext.GetSystemService etc part with the error Type mismatch, cannot convert from object to WifiManager
Now I have tried recasting the return using:
(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
This will compile, but results in a java.lang.NullPointerException when executed
Any thoughts on this would be greatly appreciated!
UPDATE*
SO I have setup the
Context mContext;
in my main class
Then I am trying to use a broadcast to find the address of a SQL server on my network. The code is kinda messy since I am just in the phase where I am trying to get just transmitting the broadcast to work. But here is the function.
public void findSQL()
{
int PORT = 1433;
try
{
byte buff[] = new byte[1024];
DatagramSocket sock = new DatagramSocket(PORT);
sock.setBroadcast(true);
// Create and send the broadcast packet
DatagramPacket dp = new DatagramPacket(buff, 7, getBroadcastAddress(), PORT);
sock.send(dp);
DatagramPacket dp1 = new DatagramPacket(buff, buff.length);
sock.receive(dp1);
sock.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
System.out.println(dhcp.toString());
if(dhcp==null)
return InetAddress.getByAddress(null);
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
{
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
}
return InetAddress.getByAddress(quads);
}
SECOND EDIT*
Earlier in my code I have defined:
@SuppressWarnings("unused")
class MSSQL_DB
{
Context mContext;
public void dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("Connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
I am afraid the whole concept of what “context” actually does, how to declare it correctly, and how to use its methods is what I must not be fully understanding yet.
Most probably ur mContext is null.. If not
Please post more logs of exception.. and post more code …