8

I insert Uri image into SQLite by using below code:

Register

private void insertData( String name,String pass, Uri image) throws SQLiteException {
        database = mdb.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(MyDatabaseHelper.KEY_NAME,    name);
        cv.put(MyDatabaseHelper.KEY_PASSWORD, pass);
        try {
            database = mdb.getWritableDatabase();
            InputStream iStream = getContentResolver().openInputStream(image);
            byte[] inputData = Utils.getBytes(iStream);
            cv.put(MyDatabaseHelper.KEY_IMAGE,inputData);
        }catch(IOException ioe)
        {
            Log.e(TAG, "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
        }
        database.insert(MyDatabaseHelper.TABLE_USER, null, cv);
        Toast.makeText(getApplicationContext(),"Database Created",Toast.LENGTH_SHORT).show();
        database.close();
    }

As I getting Database Created, I assume database was successfully created and data were inserted.

In Login , I want the image retrieved from SQLite based on user name .

name = (EditText) findViewById(R.id.name);

name.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

     @Override
    public void afterTextChanged(Editable editable) {
        String personName = name.getText().toString();
        database = mdb.getWritableDatabase();
        String selectQuery = " SELECT " + MyDatabaseHelper.KEY_IMAGE + " FROM " + MyDatabaseHelper.TABLE_USER + " WHERE " + MyDatabaseHelper.KEY_NAME + " = ' " + personName + " ' ";
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            byte[] blob = cursor.getBlob(cursor.getColumnIndex("Image"));
            Log.e("A", blob+"");
            cursor.close();
            mdb.close();
            imageView.setImageBitmap(getRoundedBitmap(Utils.getImage(blob)));
        }
        else
        {
            Toast.makeText(getApplication(),"NULL",Toast.LENGTH_SHORT).show();
        }
    }
});

    public Bitmap getRoundedBitmap(Bitmap bitmap){
    Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setShader(shader);
    paint.setAntiAlias(true);
    Canvas c = new Canvas(circleBitmap);
    c.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
    return circleBitmap;
   }

MyDatabaseHelper

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String DATABASE_NAME="mm.db";
    public static final String TABLE_USER="User";
    public static final String KEY_NAME="Name";
    public static final String KEY_PASSWORD="Password";
    public static final String KEY_IMAGE="Image";
    public static final String ID="id";

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_USER + " ( " + ID + " INTEGER PRIMARY KEY ,Name TEXT,Password TEXT,Image BLOB )");
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) {
        Log.w(MyDatabaseHelper.class.getName(), "Upgrading database from version" + oldVersion + "to" + newVersion + ",which will destroy all old data");
        db.execSQL("Drop TABLE IF EXISTS " + TABLE_USER);
        onCreate(db);
    }

    public MyDatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME,null,1);
    }
}

Utils

public class Utils {

    public static byte[] getImageBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }

    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }
}

After the user type his/her name on EditText, which named name, the image not retrieving, but displaying Null message to me ! What's wrong here ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
John Joe
  • 12,412
  • 16
  • 70
  • 135

1 Answers1

5

For an EditText the afterTextChanged() will be called every time when there is a text change detected by the TextWatcher() i.e every character typed in the EditText is a textChange event.

Because of this, even before the entire username is typed the afterTextChanged() is called for multiple times and thus the null cursor. However, as soon as the username is completely typed the cursor should provide with the proper row, in your case, the image blob.

As you mentioned, its a login page, so there must be a password editText along with the username editText.

A better way which i would suggest is detecting focus change of the username EditText using setOnFocusChangeListener(). Fire the Sql query as soon as the user completes typing the username and the focus is now on password editText.

name = (EditText) findViewById(R.id.name);

name.setOnFocusChangeListener(new OnFocusChangeListener() {          
    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus) {               //Fire Query when focus is lost
            String personName = name.getText().toString();
            database = mdb.getWritableDatabase();
            String selectQuery = " SELECT " + MyDatabaseHelper.KEY_IMAGE + " FROM " + MyDatabaseHelper.TABLE_USER + " WHERE " + MyDatabaseHelper.KEY_NAME + " = ' " + personName + " ' ";
            Cursor cursor = database.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
                byte[] blob = cursor.getBlob(cursor.getColumnIndex("Image"));
                Log.e("A", blob+"");
                cursor.close();
                mdb.close();
                imageView.setImageBitmap(getRoundedBitmap(Utils.getImage(blob)));
            }
            else
            {
                Toast.makeText(getApplication(),"NULL",Toast.LENGTH_SHORT).show();
            }
        }
});

Let us know if this works.

Darshan Miskin
  • 844
  • 14
  • 25
  • I finished typing the name, but the image still not displaying, and I didn't get the `null` also – John Joe Sep 21 '16 at 17:02
  • What if I want the image displayed after user finish typing his name, is it possible ? – John Joe Sep 21 '16 at 17:04
  • this code will work when, the name `editText` has lost focus, not when the user finishes typing. The code which you are originally using should also work when the user has completed typing the entire username, prior to that it will keep on showing toast as "NULL". – Darshan Miskin Sep 21 '16 at 17:18
  • I added `else { Toast.makeText(getApplication(), "Focus", Toast.LENGTH_SHORT).show(); }` after `if(!hasFocus)`. Everytime I launch my app, it will display focus.. – John Joe Sep 21 '16 at 17:28
  • of course it will display that toast, by default your editText gets the focus when the app launches. If you have a password edtText, click on it, then the DB query will fire. – Darshan Miskin Sep 21 '16 at 17:35