0

I know storing images in the database has to be a "BLOB" but I cant seem to get it to work. Here is my current code, please tell me what to add in what sections to get the image function to work:

Register Function:

  /**
  * Function to  Register
  **/
public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("fname", fname));
    params.add(new BasicNameValuePair("lname", lname));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("uname", uname));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
    return json;
}

DB Handler:

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "MyUsers";

// Login table name
private static final String TABLE_LOGIN = "login";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRSTNAME = "fname";
private static final String KEY_LASTNAME = "lname";
private static final String KEY_EMAIL = "email";
private static final String KEY_USERNAME = "uname";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_FIRSTNAME + " TEXT,"
            + KEY_LASTNAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_USERNAME + " TEXT,"
            + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String fname, String lname, String email, String uname, String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_FIRSTNAME, fname); // FirstName
    values.put(KEY_LASTNAME, lname); // LastName
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_USERNAME, uname); // UserName
    values.put(KEY_UID, uid); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection

}


/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user.put("fname", cursor.getString(1));
        user.put("lname", cursor.getString(2));
        user.put("email", cursor.getString(3));
        user.put("uname", cursor.getString(4));
        user.put("uid", cursor.getString(5));
        user.put("created_at", cursor.getString(6));
    }
    cursor.close();
    db.close();
    // return user
    return user;
}






/**
 * Getting user login status
 * return true if rows are there in table
 * */
public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}


/**
 * Re crate database
 * Delete all tables and create them again
 * */
public void resetTables(){
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

}

Register:

/**
 * Defining Process dialog
 **/
    private ProgressDialog pDialog;

    String email,password,fname,lname,uname;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.uname);
        inputPassword = (EditText) findViewById(R.id.pword);
           fname = inputFirstName.getText().toString();
           lname = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            uname= inputUsername.getText().toString();
            password = inputPassword.getText().toString();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Registering ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {


    UserFunctions userFunction = new UserFunctions();
    JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);

        return json;


    }

 /**
 *  JSON Response node names.
 **/

private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";

The perfect answer would include what needs to be added to which section. Any help would be greatly appreciated

BenMorel
  • 34,448
  • 50
  • 182
  • 322
SlopTonio
  • 1,105
  • 1
  • 16
  • 39
  • Have you considered just saving the actual file in a directory and save the file path in the DB instead? – Becs Carter Dec 18 '13 at 03:21
  • Unfortunately I need the image stored on the database so other users can retrieve the image – SlopTonio Dec 18 '13 at 03:24
  • 1
    convert image into string using Base64 then store string in db. – Ketan Ahir Dec 18 '13 at 03:52
  • would the user need to select the image from the gallery ? or can he take a new photo ? and also do you have to send the picture in the registration parameter ? @SlopTonio – Rakeeb Rajbhandari Dec 18 '13 at 03:57
  • I already have a function which the user can either select an image from the gallery or take one with the camera. Yes I need the picture to be sent to the registration parameter – SlopTonio Dec 18 '13 at 04:56

2 Answers2

0

I think you should encode your image with Base64

String imageEncoded = encodeTobase64(mBitmap);

store it in DB, then decode the string to retrieve your image.

Bitmap beforeScaleDown = decodeBase64(imageEncoded);
Jackie
  • 307
  • 2
  • 14
  • Can u show me the functions to store the image into the db using the code I have – SlopTonio Dec 18 '13 at 04:56
  • Just add another field in DB, such as 'avatar'. Then in your addUser method, pass param String imageEncoded. then params.add(new BasicNameValuePair("avatar", imageEncoded)); – Jackie Dec 18 '13 at 06:46
0

You can store images into database. for this you have to make one column with datatype BLOB. then after you can retrieve it from database. for your guidance see this example.

But here one of my friend said that it is not good to store images into database. he suggests me to store into sdcard rather than database. see this link or this for your convenience.

Community
  • 1
  • 1
Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
  • Those links do not give any reason, except performance, but [measurements indicate the database is better for typical image sizes](http://www.sqlite.org/intern-v-extern-blob.html). – CL. Dec 18 '13 at 09:16