完成 ImageUploadTask() 任务后,该方法本身将返回 sResponse,这可能会触发 onPostExecute()。但是,我无法让 onPostExecute() 工作。
意图的代码是:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else if (subject.getText() == null) {
Toast.makeText(getApplicationContext(),
"Please enter subject title", Toast.LENGTH_SHORT).show();
} else if (msg == null) {
Toast.makeText(getApplicationContext(),
"Please enter message", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
ImageUploadTask() 是:
class ImageUploadTask extends AsyncTask <Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://203.117.178.181/test3/postdata2.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("userfile", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("subject", new StringBody(subject.getText()
.toString()));
entity.addPart("message", new StringBody(msg.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
onPostExecute() 的代码是:
@Override
protected void onPostExecute(String sResponse) {
super.onPostExecute(sResponse);
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
subject.setText("");
msg.setText("");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}}
提前谢谢=D