I'm working on an android app that will be able to switch between 3G and 4G manually by making a call and sending out a package simultaneously. When I end the call, the package will continue to send keeping the phone in 3G, but then when I push a button, it terminates the package.
I'm fine on most of the code, but I got the program to send the package from someone else and I'm a bit confused on how I get it running, specifically this one error I'm getting when I declare the field socket. I get an error message saying "Default constructor cannot handle exception type SocketException thrown by implicit super constructor. Must define an explicit constructor."
Here's my class file for the package:
package com.example.derpphone;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.TimerTask;
public class timer extends TimerTask {
DatagramSocket socket = new DatagramSocket();
@Override
public void run() {
if (socket != null) {
byte[] bytes = new byte[100];
SocketAddress serverAddress = new InetSocketAddress("131.179.176.74",
9998);
try {
DatagramPacket packet = new DatagramPacket(bytes,
bytes.length, serverAddress);
socket.send(packet);
} catch (Exception e) {
}
}
}
}
Change your code to:
DatagramSocket socket;
public timer() throws Exception {
socket = new DatagramSocket();
}
When you write:
DatagramSocket socket = new DatagramSocket();
without a default constructor, it is equivalent to:
DatagramSocket socket;
public timer() {
super();
socket = new DatagramSocket();
}
As DatagramSocket constructor throws an exception, this needs to be caught or declared.
it means that
DatagramSocket socket = new DatagramSocket();
could throw an SocketException, because default constructor DatagramSocket() declares so, It must be handled or re-throw back, and there is no way to handle it like this so you would nee a constructor around it
change it to
DatagramSocket socket;
public timer throws SocketException {
this.socket = new DatagramSocket();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With