1

I am unable to fetch the image from the database, please look at my databasehelper (that is my fetchimg(String i) and MainActivity (that is showmeth(View w)) class.

What I am actually doing here is firstly capturing the image with camera, then it is temporary pasted on 1st ImageView and after i click on save button it gets saved in the database(No problem yet). But when i click show button then it must show the image in a 2nd ImageView by taking reference id as a textview's id but it is not showing the image, that is showmeth(View w) unable to fetch the image from database.

My MainActivity

package com.example.expnewbutton;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Uri fileUri;
    Bitmap img;
    TextView t1;
    databasehelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = (TextView) findViewById(R.id.text);
        helper = new databasehelper(this);
    }

    public void cammethod(View w) {
        try {
            PackageManager packageManager = getPackageManager();
            boolean doesHaveCamera = packageManager
                    .hasSystemFeature(PackageManager.FEATURE_CAMERA);

            if (doesHaveCamera) {
                // start the image capture Intent
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // Get our fileURI
                // fileUri = getOutputMediaFile();

                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent, 100);

            }
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(),
                    "There was an error with the camera.", Toast.LENGTH_LONG)
                    .show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                if (intent == null) {
                    // The picture was taken but not returned
                    Toast.makeText(
                            getApplicationContext(),
                            "The picture was taken and is located here: "
                                    + fileUri.toString(), Toast.LENGTH_LONG)
                            .show();
                } else {
                    // The picture was returned
                    Bundle extras = intent.getExtras();
                    img = (Bitmap) extras.get("data");
                    ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
                    imageView1.setImageBitmap((Bitmap) extras.get("data"));
                }
            }
        }

    }

    public void insertimg(View w) {
        long a = 0;
        String id = t1.getText().toString();
        try {
            helper.deleterecord(id);
            a = helper.insert(id, img);

            if (a >= 1) {
                Toast.makeText(getBaseContext(),
                        a + "Record Successfully Saved", 30).show();
            } else {

                Toast.makeText(getBaseContext(), "Not Saved", 30).show();

            }
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), "there is error", 5).show();
        }
    }

    public void showmeth(View w) {
        String i = null;
        boolean flag = false;

        i = t1.getText().toString();
        try {
            flag = helper.fetchimg(i);
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), "database exception", 10).show();
        }

        if (flag == true) {
            Toast.makeText(getBaseContext(),
                    "Here your image save on imageview", 10).show();
            ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
            imageView2.setImageBitmap(helper.bmp);
        } else {
            Toast.makeText(getBaseContext(), "Add a Pic first", 50).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

My Database File:

package com.example.expnewbutton;

import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

public class databasehelper extends SQLiteOpenHelper {

    final static String databasename = "Image";
    final static int databaseversion = 1;
    Bitmap bmp = null;

    public databasehelper(Context ctx) {
        super(ctx, databasename, null, databaseversion);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {

            Log.d("tag4545", "database");
            db.execSQL("create table mypic(id text,pic BLOB)");

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("drop table if Exists mypic");
        // db.execSQL("drop table if Exists emer");
        onCreate(db);

    }

    public long insert(String id, Bitmap img) {

        SQLiteDatabase base = getWritableDatabase();
        byte[] data = getBitmapAsByteArray(img); // this is a function
        ContentValues value = new ContentValues();
        value.put("id", id);
        value.put("pic", data);

        long a = base.insert("mypic", null, value);

        return a;
    }

    public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray();
    }

    public boolean fetchimg(String i) {

        SQLiteDatabase base = getReadableDatabase();
        Cursor cs = null;
        try {
            cs = base.query("mypic", new String[] { "pic" }, "id=?",
                    new String[] { "i" }, null, null, null);

            /*
             * String qu= "select pic from mypic where id"+i;
             * 
             * Cursor cs=null; try{ cs =base.rawQuery(qu, null); }
             * catch(Exception e) { return false; }
             */
            if (cs != null) {
                cs.moveToFirst();
                byte[] imgbyte = cs.getBlob(0);
                cs.close();
                bmp = BitmapFactory.decodeByteArray(imgbyte, 0, imgbyte.length);
                return true;
            }

            else {
                return false;

            }
        }

        catch (Exception e) {
            return false;
        }
    }

    public void deleterecord(String pe_id) {
        SQLiteDatabase base = getWritableDatabase();
        base.delete("mypic", "id=?", new String[] { pe_id });
    }

}

My xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gb2"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        android:layout_toRightOf="@+id/textView2"
        android:onClick="cammethod"
        android:text="Cam" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="46dp"
        android:layout_toRightOf="@+id/button1"
        android:onClick="insertimg"
        android:text="Save" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button2"
        android:layout_alignParentRight="true"
        android:layout_marginRight="22dp"
        android:text="Photo"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text"
        android:layout_toRightOf="@id/imageView1"
        android:onClick="showmeth"
        android:text="show" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView1" />

</RelativeLayout>

Please help me in code, I need it soon. Thank you.

So the problem may be with database query(I tried query with both methods which i hidden or which is not hidden) or may be with using BLOB in my code. Please help me to find error

1 Answer 1

2

You are passing the string "i" where you need to pass the value of i.

You should change your query to:

    cs = base.query("mypic", new String[] { "pic" }, "id=?",
            new String[] { String.valueOf(i) }, null, null, null);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you,Mr. HalR for your response yes that was the problem. But can you please tell me that Why this code line is running without getting value from string "pe_id" in deleterecord(String pe_id) of my databasehelper class. code line:"base.delete("mypic", "id=?", new String[] { pe_id });"
That command looks correct, but only if pe_id contains the correct value. Perhaps pe_id is not what you think it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.