我不明白为什么变量AUX和resultado不返回它们的相同值...我想保留该值以将它们返回到另一个类。你能帮帮我吗?
我的课程是:
public class CriarConexao extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver conectado");
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/savetime", "root", "root");
resultado = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from ingresso");
//ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
resultado = rs.getString(1);
}
AUX = resultado ;
System.out.println("Auxiliar 1: " + AUX + " e " + resultado);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("ERRO: " + e.toString());
}
return response;
}
@Override
protected void onPostExecute(String resultado) {
AUX = resultado ;
System.out.println("Auxiliar 2: "+AUX + " e " + resultado);
}
}
logcat:
06-20 05:00:47.475: I/System.out(1592): Auxiliar 1: 1234 e 1234
06-20 05:00:47.475: I/System.out(1592): Auxiliar: e
答案 0 :(得分:1)
因为您的doInBackground
函数返回response
变量值为空。所以将AUX
添加到response
。试试这个
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver conectado");
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/savetime", "root", "root");
resultado = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from ingresso");
//ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
resultado = rs.getString(1);
}
AUX = resultado ;
response = AUX; // Add here
System.out.println("Auxiliar 1: " + AUX + " e " + resultado);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("ERRO: " + e.toString());
}
return response;
}
答案 1 :(得分:0)
在你的doInBackground方法中,你正在初始化一个响应字符串,但你从来没有为它分配AUX或者resultado,这就是为什么postExecute resultado是空的(因为它有相同的名字并不是它是相同的变量)。由于您尝试返回多个String,因此需要调整asynctask以返回包含要返回的两个值的数组或映射