Strange behaviour while setting imageview bitmap in android

I was developing an app which saves the image uri taken from camera first in a sqlite3 db and then retrieve it back to set it to an imageview. I had the well known out of memory error in vm. I tried various ways found in various other questions like: 1)

So you

either need to encourage the imageView to recycle the previous bitmap - possibly with setImageView("")
or get the bitmap from the URI and use setImageBitmap(android.graphics.Bitmap) instead; then you can do

setImageBitmap(null) and bitmap.recycle().

2)

((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();

3)

protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unbindDrawables(findViewById(R.id.showDataViewRoot));
        System.gc();

    }

Strangely none of them quite worked,and the error kept on appearing. Mostly because the error came during the first attempt to display image itself(so no chance for recycling i guess). When searching I found following link: http://www.vogella.com/articles/AndroidCamera/article.html#example Taking the cue from there I did following change:

imageView.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(path)));

Compelete modified code for my ShowData.java(with commented previous attempts). The code for setting image in fillImage():

package org.dheeraj.imnci;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class ShowData extends Activity {
    private Spinner spinnerId;
    private DbHelper dbHelper;
    private SQLiteDatabase dbReader;
    private Cursor cursor;
    private ArrayList<String> idList;
    private ArrayAdapter<String> adapter;
    private String id;
    private TableLayout dataTable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_data);
        dbHelper = new DbHelper(this);
        spinnerId = (Spinner) findViewById(R.id.spinnerData);
        dataTable = (TableLayout) findViewById(R.id.tableShowData);
        fillSpinner();

    }

    private void fillData(String id) {
        String tableNames[] = { "mother_reg", "anc_02", "anc_03", "anc_04",
                "tt1", "tt2", "ttb", "abortions", "po", "pnc", "ifa" };
        for (String table : tableNames) {
            getDataFromTable(table, id);
        }
    }

    private void getDataFromTable(String table, String id) {
        // TODO Auto-generated method stub

        getTableTitle(table);
        getTableColumns(table, id);
    }

    private void getTableColumns(String table, String id) {
        // TODO Auto-generated method stub
        SQLiteDatabase dbReader;
        Cursor cursor;
        TableRow colRow;
        TextView labelView;
        TextView valueView;
        String label;
        String value;

        dbReader = dbHelper.getReadableDatabase();
        try {
            if (table.equals("mother_reg"))
                cursor = dbReader.query(table, null, "mid=" + id, null, null,
                        null, null, null);
            else
                cursor = dbReader.query(table, null, "ID=" + id, null, null,
                        null, null, null);

            Log.d("getTableColumns", table);
            if (cursor.moveToFirst()) {
                do {
                    Log.d("in cursor", "" + cursor.getColumnCount());
                    for (int i = 0; i < cursor.getColumnCount(); i++) {
                        label = cursor.getColumnName(i);
                        value = cursor.getString(i);

                        labelView = new TextView(this);
                        valueView = new TextView(this);
                        colRow = new TableRow(this);

                        labelView.setText(label);
                        valueView.setText(value);
                        colRow.addView(labelView);
                        colRow.addView(valueView);
                        dataTable.addView(colRow);
                    }

                } while (cursor.moveToNext());

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

    private void getTableTitle(String table) {
        // TODO Auto-generated method stub
        TableRow tabRow;
        TextView tv;
        String title = table.replace('_', ' ').toUpperCase();
        tabRow = new TableRow(this);
        tv = new TextView(this);
        tv.setText(title);
        tv.setTextSize(20);
        tabRow.addView(tv);
        dataTable.addView(tabRow);
    }

    private void fillImage(String id) {
        // TODO Auto-generated method stub

        ImageView imageView;
        boolean picFound;

        SQLiteDatabase dbReader;
        Cursor cursor;

        String path = null;

        imageView = (ImageView) findViewById(R.id.showDataImage);

        picFound = false;
        dbReader = dbHelper.getReadableDatabase();
        try {
            String tableName = "pictures";
            String[] columns = { "mid", "uri" };
            Log.d("id value", "" + id);
            cursor = dbReader.query(tableName, columns, "mid=" + id, null,
                    null, null, null, null);
            Log.d("gotCursor", "foundcursor");
            if (cursor.moveToFirst()) {

                Log.d("in cursor", "" + cursor.getColumnCount());
                path = cursor.getString(cursor.getColumnIndex("uri"));
                Log.d("show_data:imagepath", path);
                if (path != null)
                    picFound = true;
                // imgUri = Uri.parse(new File(path).toString());
                /*
                 * bmpImage = BitmapFactory.decodeFile(path);
                 * 
                 * 
                 * 
                 * scaledBmp = Bitmap.createScaledBitmap(bmpImage, 100, 150,
                 * true); bmpImage.recycle(); bmpImage = null;
                 */

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

        if (!picFound)
            imageView.setImageResource(R.drawable.default_user);
        else {
            // Log.d("inimageview", imgUri.toString());

            try {
                imageView.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(path)));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        // LayoutParams lv = new LayoutParams(200, 300);
        // imgRow.setLayoutParams(lv);

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unbindDrawables(findViewById(R.id.showDataViewRoot));
        System.gc();

    }

    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unbindDrawables(findViewById(R.id.showDataViewRoot));
        System.gc();
    }

    void fillSpinner() {
        dbReader = dbHelper.getReadableDatabase();
        String columns[] = { "mid" };

        try {
            cursor = dbReader.query("mother_reg", columns, null, null, null,
                    null, "mid DESC");
            if (cursor.moveToFirst()) {
                idList = new ArrayList<String>();
                do {
                    idList.add(cursor.getString(cursor.getColumnIndex("mid")));
                } while (cursor.moveToNext());
                cursor.close();

                adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, idList);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerId.setAdapter(adapter);
                spinnerId
                        .setOnItemSelectedListener(new OnItemSelectedListener() {

                            @Override
                            public void onItemSelected(AdapterView<?> arg0,
                                    View arg1, int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                id = arg0.getItemAtPosition(arg2).toString();
                                // dataTable.removeAllViews();
                                unbindDrawables(dataTable);
                                fillImage(id);
                                fillData(id);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> arg0) {
                                // TODO Auto-generated method stub

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

What I can't understand is that how it worked. Does taking inputstream somehow reduces size as compared to direct usage of file as in imageview.setimageuri(Uri.parse(path)) or it uses some kind of buffer? Just want to know what went wrong. Kindly do tell if more information regarding the code of my app is needed. But this strange memory issue has really baffled me and I am really confused with so many ways mentioned in different threads. More information about my app: target api: 1.6 mid SDK version: 4

Edit 1: I am quite sorry but this method also failed after some trials with ShowData. Following is the screen shot of Logcat: Now i am really very confused. Just how to show a simple image saved by camera in sdcard in my imageview? My sincere thanks in advance for any kind help.

Edit 2: Tried some more change in fillimage view method:

        try {
            if(((BitmapDrawable)imageView.getDrawable())!=null)
            ((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();



            imageView.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(path)));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Its working smoothly for now except once it gave following error: I really want to go to the root of this matter now. Kindly provide any guidance. I am quite sorry for so many edits but I wanted to keep informing about any further progress.

Answers


If you want to show single image fullscreen then start activity with Intent.ACTION_VIEW:

Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/jpeg");
startActivity(i);

If you want to show thumbnails then reduce size of those images by subsampling, just add this option to BitmapFactory: http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize

EDIT 1:

There is good doc: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

EDIT 2: According to your second problem:

Bitmap oldBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
imageView.setImageDrawable(null); //this should help
oldBitmap.recycle();
imageView.setImageBitmap(newBitmap);

Need Your Help

How to assign a css class to echo $output

php css output echo styling

How can I assign a CSS class to echo $output

"Access 2002 vs SQL Server 200*" as DB for sharepoint

sql sql-server sharepoint ms-access

I work with a team that has a sharepoint site currently runnning and its lists are linked to an access DB. My question is really on the investment level, what would be the reasons to upgrade DB to