【发布时间】:2012-06-23 10:16:21
【问题描述】:
我当前的代码成功上传了图片,但仍然没有显示 Image uploaded successfully 的 Toast 消息。图片上传成功后如何显示 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();
这里是 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;
}
【问题讨论】:
-
在
Toast中尝试使用Activityname.this而不是getApplicationContext() -
使用 MyActivity.this 后仍然没有显示 Toast 消息
-
尝试添加一些日志以查看是否正在输入 Toast 行。 if(response != null) { Log.d("TAG", "response not null");如果不是,那么问题不在于 Toast。
-
@NunoGonçalves 在添加 Log 后,如您所述,它在 logcat 中显示
response not null