我得到这个异常,我不知道为什么,这就是我拥有的类:一个启动一个服务的活动,它启动一个连接到数据库的 ScheduledExecutorService 类(这就是连接的原因)。
当我尝试通过我的服务进行连接时,我明白为什么会出现此异常,但现在我创建了一个新的类/任务来执行此操作,但我仍然遇到此异常。
我没有附加代码,因为它有很多代码,问题可能出在我管理这个系统的方式上,而不是代码本身,如果您想看到其他任何内容,请告诉我。
请参阅通过服务管理与 mysql 的连接以获取有关为什么 aThread
在这种情况下不合适的更多信息。
编辑 代码附件:这是我向数据库发送详细信息的第三类。
public class SendLocation
{
private String lastAddress;
private int id;
private Connection conn;
private PreparedStatement stmt;
private LocationService ls1;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public SendLocation(int id,LocationService ls1)
{
this.lastAddress = "";
this.id = id;
this.conn = null;
this.sqlConnect();
this.sqlInsertStatement();
this.ls1 = ls1;
}
public void send()
{
final Runnable sender = new Runnable()
{
public void run()
{
if(!lastAddress.equals(ls1.getAddress()) && !ls1.getAddress().equals(""))
{
lastAddress = ls1.getAddress();
try
{
stmt.setInt(1, id);
stmt.setString(2, lastAddress);
stmt.execute();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
};
final ScheduledFuture sendHandle =
scheduler.scheduleAtFixedRate(sender, 1, 1, TimeUnit.SECONDS);
scheduler.schedule(new Runnable()
{
public void run()
{
sendHandle.cancel(true);
}
}, 60 * 60, TimeUnit.SECONDS);
}
public boolean sqlConnect()
{
try {
Class.forName(Config.DRIVER).newInstance();
DriverManager.setLoginTimeout(100);
this.conn = DriverManager.getConnection(Config.URL+Config.DBNAME,
Config.USERNAME,Config.PASSWORD);
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void sqlInsertStatement()
{
try {
this.stmt = conn.prepareStatement
("INSERT INTO locations(id, location) VALUES (?,?)");
}catch (SQLException e1) {
e1.printStackTrace();
}
}
}
编辑
我将任务更改为线程这里是新代码:
public class SendLocation extends Thread
{
private String lastAddress;
private int id;
private Connection conn;
private PreparedStatement stmt;
private LocationService ls1;
private boolean run;
public SendLocation(int id,LocationService ls1)
{
this.lastAddress = "";
this.id = id;
this.conn = null;
this.sqlConnect();
this.sqlInsertStatement();
this.ls1 = ls1;
this.run = true;
}
public void run()
{
while(run)
{
if(!lastAddress.equals(ls1.getAddress()) && !ls1.getAddress().equals(""))
{
lastAddress = ls1.getAddress();
try
{
stmt.setInt(1, id);
stmt.setString(2, lastAddress);
stmt.execute();
sleep(1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void destroy()
{
this.run = false;
}
public boolean sqlConnect()
{
try {
Class.forName(Config.DRIVER).newInstance();
DriverManager.setLoginTimeout(100);
this.conn = DriverManager.getConnection(Config.URL+Config.DBNAME,
Config.USERNAME,Config.PASSWORD);
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void sqlInsertStatement()
{
try {
this.stmt = conn.prepareStatement
("INSERT INTO locations(id, location) VALUES (?,?)");
}catch (SQLException e1) {
e1.printStackTrace();
}
}
}
我现在怎么会得到 NetworkOnMainThread 异常?