加载图像时出现窗口泄漏错误

时间:2014-02-12 07:51:06

标签: android

    public class CaptureImage extends Activity {

private static final String TAG = "CaptureImage.java";

public static ArrayList<HashMap<String, String>> outlets = outlets = new ArrayList<HashMap<String, String>>();
final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;

int serverResponseCode = 0;
static String uploadFilePath = " ";
static String Path;
static int delete_image_id = 0;
TextView shift_display;
Uri imageUri = null;
static TextView imageDetails = null;

public static ImageView showImg = null;

CaptureImage CameraActivity = null;
Upload upload;
ProgressDialog dialog_upload = null;

// FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
static Cursor cursor = null;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_capture_image);
    CameraActivity = this;
    showImg = (ImageView) findViewById(R.id.showImg);
    upload = new Upload(CaptureImage.this);
    final Button photo = (Button) findViewById(R.id.photo);
    final Button upload = (Button) findViewById(R.id.upload);
    final Button selet_outlet = (Button) findViewById(R.id.outlet_names);
    photo.setOnClickListener(oclBtnOk);
    upload.setOnClickListener(oclBtnOk3);
    selet_outlet.setOnClickListener(oclBtnOk4);

}

@Override
public void onDestroy() {
    super.onDestroy();

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (imageUri != null) {
        outState.putString("cameraImageUri", imageUri.toString());
    }
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState.containsKey("cameraImageUri")) {
        imageUri = Uri
                .parse(savedInstanceState.getString("cameraImageUri"));
    }
}

OnClickListener oclBtnOk = new OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.i("VALUES", "It is Working");
        String fileName = "Camera_Example.jpg";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, fileName);
        values.put(MediaStore.Images.Media.DESCRIPTION,
                "Image capture by camera");

        imageUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

        /*************************** Camera Intent End ************************/

    }
};

OnClickListener oclBtnOk3 = new OnClickListener() {
    @Override
    public void onClick(View v) {

        if (showImg.getDrawable() == null) {
            Toast.makeText(CaptureImage.this, " Picture was not captured ",
                    Toast.LENGTH_SHORT).show();
        }

        else {
            upload_prescription();
        }

    }
};

OnClickListener oclBtnOk4 = new OnClickListener() {
    @Override
    public void onClick(View v) {

        if (showImg.getDrawable() == null) {
            Toast.makeText(CaptureImage.this, " Picture was not captured ",
                    Toast.LENGTH_SHORT).show();

        }

        else {

            // Intent intent = new Intent(CaptureImage.this,
            // Chanel_Display.class);
            // startActivity(intent);

        }

    }

};

public void upload_prescription() {
    dialog_upload = ProgressDialog.show(CaptureImage.this, "",
            "Uploading file...", true);
    new Thread(new Runnable() {
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {

                }
            });

            createDirectoryIfNeeded();
            copy();

            deleteImageFromGallery(delete_image_id + "");
            upload.uploadFile(uploadFilePath);

        }
    }).start();

}

public void deleteImageFromGallery(String captureimageid) {

    Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    cursor = null;

    getContentResolver().delete(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            BaseColumns._ID + "=?", new String[] { captureimageid });

    String[] projection = { MediaStore.Images.ImageColumns.SIZE,
            MediaStore.Images.ImageColumns.DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };

    Log.i("InfoLog", "on activityresult Uri u " + u.toString());

    try {
        if (u != null) {
            cursor = CaptureImage.this.getContentResolver().query(imageUri,
                    projection, null, null, null);
        }
        if ((cursor != null) && (cursor.moveToLast())) {

            int i = getContentResolver().delete(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    BaseColumns._ID + "=" + cursor.getString(3), null);
            Log.v(TAG, "Number of column deleted : " + i);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

public void copy() {

    String sdCard = Environment.getExternalStorageDirectory().toString();
    uploadFilePath = sdCard + "/Capturetemp/" + getDate() + "_" + "AI"
            + ".jpg";

    File sourceLocation = new File(Path);
    File targetLocation = new File(uploadFilePath);
    Log.v(TAG, "sourceLocation: " + sourceLocation);
    Log.v(TAG, "targetLocation: " + targetLocation);

    try {

        // 1 = move the file, 2 = copy the file
        int actionChoice = 2;

        // moving the file to another directory
        if (actionChoice == 1) {

            if (sourceLocation.renameTo(targetLocation)) {
                Log.v(TAG, "Move file successful.");
            } else {
                Log.v(TAG, "Move file failed.");
            }

        }

        // we will copy the file
        else {

            // make sure the target file exists

            if (sourceLocation.exists()) {

                InputStream in = new FileInputStream(sourceLocation);
                OutputStream out = new FileOutputStream(targetLocation);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();

                Log.v(TAG, "Copy file successful.");

            } else {
                Log.v(TAG, "Copy file failed. Source file missing.");
            }

        }

    } catch (NullPointerException e) {
        // e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

@SuppressLint("SimpleDateFormat")
public String getDate() {

    Calendar c = Calendar.getInstance();
    SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
    String formattedDate1 = df1.format(c.getTime());

    return formattedDate1;

}

private void createDirectoryIfNeeded() {
    File direct = new File(Environment.getExternalStorageDirectory()
            + "/Capturetemp");

    if (!direct.exists()) {
        if (direct.mkdir()) {
            // directory is created;
        }

    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

        if (resultCode == RESULT_OK) {

            /*********** Load Captured Image And Data Start ***************/

            String imageId = convertImageUriToFile(imageUri, CameraActivity);

            // Create and excecute AsyncTask to load capture image

            new LoadImagesFromSDCard(CaptureImage.this).execute(""
                    + imageId);

            /*********** Load Captured Image And Data End ****************/

        } else if (resultCode == RESULT_CANCELED) {

            Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

        } else {

            Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

        }
    }

}

/************ Convert Image Uri path to physical path **************/

public static String convertImageUriToFile(Uri imageUri, Activity activity) {

    int imageID = 0;

    try {

        /*********** Which columns values want to get *******/
        String[] proj = { MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Thumbnails._ID,
                MediaStore.Images.ImageColumns.ORIENTATION };

        cursor = activity.getContentResolver().query(imageUri, proj, null,
                null, null);

        // Get Query Data

        int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media._ID);
        int file_ColumnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        // int orientation_ColumnIndex = cursor.
        // getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);

        int size = cursor.getCount();

        /******* If size is 0, there are no images on the SD Card. *****/

        if (size == 0) {

            // imageDetails.setText("No Image");
        } else {

            if (cursor.moveToFirst()) {

                imageID = cursor.getInt(columnIndex);
                delete_image_id = imageID;

                Path = cursor.getString(file_ColumnIndex);

            }

        }

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Return Captured Image ImageID ( By this ImageID Image will load from
    // sdcard )

    return "" + imageID;
}

public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {

    private ProgressDialog Dialog;
    CaptureImage context;

    Bitmap mBitmap;

    public LoadImagesFromSDCard(CaptureImage context) {
        this.context = context;

    }

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(context);
        Dialog.show();

    }

    // Call after onPreExecute method
    @Override
    protected Void doInBackground(String... urls) {

        Bitmap bitmap = null;
        Bitmap newBitmap = null;
        Uri uri = null;

        try {

            uri = Uri.withAppendedPath(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
                            + urls[0]);

            /************** Decode an input stream into a bitmap. *********/
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));

            if (bitmap != null) {

                /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

                newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
                        true);
                // SaveIamge(newBitmap);
                bitmap.recycle();
                if (newBitmap != null) {

                    mBitmap = newBitmap;
                }
            }
        } catch (IOException e) {
            // Error fetching image, try to recover

            /********* Cancel execution of this task. **********/
            cancel(true);
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void unused) {

        if (mBitmap != null) {
            context.showImg.setImageBitmap(mBitmap);
        Dialog.dismiss();
        }

        if (Dialog.isShowing()) {


        }

    }

}

}

我尝试上面的代码显示从SD卡检索图像它工作正常。但是当图像加载到屏幕上时它返回以下错误。这里我使用进度对话框在图像加载期间显示。

 le.androidchathunservice.CaptureImage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@424c0c50 that was originally added here


      02-12 13:15:24.093: E/WindowManager(12019): android.view.WindowLeaked: Activity com.example.androidchathunservice.CaptureImage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@424c0c50 that was originally added here

        02-12 13:15:24.093: E/WindowManager(12019):     at android.app.Dialog.show(Dialog.java:277)
        02-12 13:15:24.093: E/WindowManager(12019):     at com.example.androidchathunservice.CaptureImage$LoadImagesFromSDCard.onPreExecute(CaptureImage.java:418)

2 个答案:

答案 0 :(得分:1)

你应该改变这个......

 CaptureImage context;

 Context context;

 public LoadImagesFromSDCard(CaptureImage context) {
    this.context = context;

}

public LoadImagesFromSDCard(Context context) {
    this.context = context;

}

修改

  @Override
  protected void onPostExecute(Void unused) {
     super.onPostExecute();

    if (Dialog.isShowing()&& Dialog!=null) {

        Dialog.dismiss();
        Dialog = null;
    }

    if (mBitmap != null) {
        context.showImg.setImageBitmap(mBitmap);

    }
}

答案 1 :(得分:0)

当您点击onPostExecute()时,您创建对话框的CaptureImage活动是否已经完成。如果是这种情况,那么尝试解除对话框肯定会泄漏窗口