我当前的代码成功上传了图像,但仍然没有显示Toast消息Image uploaded successfully.如何在成功上传图像后显示Toast消息?
这是我的代码
public void onClick(View v) {
dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
new Thread() {
public void run() {
try {
//Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show();
if(imageUpload(globalUID, largeImagePath)) {
Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error uploading image", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}.start();
Run Code Online (Sandbox Code Playgroud)
这是imageUpload方法
public boolean imageUpload(String uid, String imagepath) {
boolean success = false;
//Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Bitmap bitmapOrg = BitmapFactory.decodeFile(imagepath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("uid", uid));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(response != null) {
Toast.makeText(getApplicationContext(), "File uploaded successfully", Toast.LENGTH_LONG).show();
success = true;
}
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
dialog.dismiss();
return success;
}
Run Code Online (Sandbox Code Playgroud)
您试图在非UI线程中显示Toast,因此无法看到Toast
完成任务后使用 Handler来显示Toast.its,以便更好地使用AsyncTask.
使用AsyncTask,添加你的 imageUpload code in DoinBackground(...) method and return boolean to onPostExxecute(),and You can display Toast in OnPostExecute Method.
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |