我正在使用 HttpPost 方法通过 Web 服务器从 android 设备发送消息。当响应返回时,设备应该使用我使用过一百万次的格式更新车载数据库,
if(postMessage(theMessage).trim().equals("OK")){
DatabaseHelper helper = new DatabaseHelper(ShareDialog.this);
database = helper.getWritableDatabase();
strSharedWith = strSharedWith + theNameEncoded+ "|~|";//my delimiter;
String strFilter = "listTitle= '" + listTitle + "'";
ContentValues values = new ContentValues();
values.put("sharedWith", strSharedWith);
int numRows = database.update("listdata", values, strFilter, null);
database.close();
Toast.makeText(getBaseContext(), numRows + "", Toast.LENGTH_SHORT).show();//Toasts "1"
一切似乎都正常:消息被发送到另一台设备,响应从 Web 服务器返回,Toast 消息表明一行已更新......但值仍然为空。有人看到我错过了什么吗?谢谢
编辑:我发现如果在调用 AsyncTask 之前移动查询工作正常......对我来说似乎很奇怪查询没有执行,因为我知道 if 块是(因为有一个 else 块显然是未执行)。冒着让自己尴尬的风险,我发布了 AsyncTask 的代码;我知道使用
while (something.equals("")){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
是不好的做法,但这就是我将帖子发送到服务器的方式。我现在看到我最好清理我的第二个线程使用情况,所以如果有人可以这样做(并告诉我在哪里更新本地数据库),我会将其标记为已回答。哦,旁注:使用 execSQL 生成异常的建议是因为我的管道分隔符不正确转义——我使用的格式避免了这种情况。好的,红着脸:
if(postMessage(theNameEncoded).trim().equals("OK")){
//was making my database update here, which didn't work
m_adapter.notifyDataSetInvalidated();
loadAdapter();
setListAdapter(m_adapter);
}else{
//alert dialog
}
public String postMessage(String toWhom){
//get stuff from database
strToPost = (assembled from the database call);
new MyAsyncTask().execute(strToPost);
while (privateStatus.equals("")){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (privateStatus.indexOf("OK")>-1){
//the return from the webserver, OK on success
return "OK";
}else{
return "Not a friend";
}
而且, asyncTask
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
protected void onPreExecute() {
//progress dialog started
}
protected Double doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.my-domain.com/list_post.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("listSent", strToPost));
nameValuePairs.add(new BasicNameValuePair("fromUser", myName));
nameValuePairs.add(new BasicNameValuePair("toUser", sharingListWith));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
status = httpclient.execute(httppost, new BasicResponseHandler());
while (status.equals("")){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setStatus(status);
//exception catching
protected void onPostExecute(Double result){
pDialog.dismiss();
}
}
public String setStatus (String theStatus){
if(!theStatus.equals(null)){
privateStatus = theStatus;
}
return null;
}
我知道。并且,其中两个同时{sleep}的东西。任何关于如何正确地将来自网络服务器的响应合并到辅助线程中的建议将不胜感激。