我在我的android的AsyncTask中使用HttpURLConnection从MySQL(android + jsp + MySQL)获取数据。 当我开始'A活动'时,第一个就是OK。我可以开始doInBackground。但是当我接下来开始'A活动'时,当我反复开始'A活动'时,我无法启动doInBackgound。
每当我反复开始'A活动'时,我想开始doInBackground 。 因为我在doInBackground中从MySQL获取数据。
我曾经“task.cancel(true)”,但这不起作用。
我是android的nuwbe,请告诉我如何反复启动doInBackground。
谢谢你。背后是我的代码。
创建代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_inventory);
...........
connectJSP = new getInventoryFromMySQL();
connectJSP.execute();
...........
}
onBackPressed代码
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
connectJSP.cancel(true);
super.onBackPressed();
}
}
AsyncTask代码
private class getInventoryFromMySQL extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... sId) {
String sResult = "Error";
try {
//URL setting and access
URL url = new URL("http://-----.com/*****.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//setting
conn.setRequestMethod("POST");
// connection values
String sendBicycleName = bicycleName;
String sendBicycleYear = bicycleYear;
//StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("sendBicycleName").append("=").append(sendBicycleName).append("&");
buffer.append("sendBicycleYear").append("=").append(sendBicycleYear);
//put data into JSP
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(buffer.toString());
osw.flush();
//get data from JSP
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
String str;
//fit the order with JSP(garbage values)
reader.readLine(); reader.readLine(); reader.readLine(); reader.readLine();
//get data from JSP
for(;;) {
if((str = reader.readLine()) != null && (str != "") && (str != " ") && (str != "null")) {
mysqlStoreId[countInventory] = str;
for(int c=0; c<5; c++) {
for(int s=0; s<8; s++) {
str = reader.readLine();
mysqlInventory[countInventory][c][s] = Integer.parseInt(str);
}
}
countInventory++;
} else if(str == null && str == "null") {
//finish for if values equals null
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sResult;
}
}
答案 0 :(得分:0)
我找到了答案。我查看了所有代码的日志。 问题是&#39; doInBackground&#39;有错误。 (;;)&#39;中没有别的东西。所以AsyncTack会在onCancelled()&#39;上进行。但是我没有写过“onCancelled()&#39;代码。
当我添加onCancelled()时,我可以取消(true)并重新启动Asynctask。
感谢!