PNG image -> SQLite DB -> imageview

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

hany

Postby hany » Thu Apr 29, 2010 5:19 am

Very very Thanks for you.
hany
Junior Developer
Junior Developer
 
Posts: 19
Joined: Sat Mar 13, 2010 6:35 am

Top

PND image & SQLite DB

Postby hany » Sat May 01, 2010 12:49 pm

padde wrote:I found some minutes thanks to a canceled meeting :D
I changed the sample to a ListActivity and show a sample of presenting
the data from the database in a list.
If i understand it right thats what you want.

First the class representing a fruit:
Fruit.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.fruitsdbsample;
  2.  
  3. import android.graphics.Bitmap;
  4.  
  5. public class Fruit {
  6.     private Bitmap bmp;
  7.     private String name;
  8.     private int kcal;
  9.     private int vitaminc;
  10.  
  11.     public Fruit(Bitmap b, String n, int k, int v) {
  12.         bmp = b;
  13.         name = n;
  14.         kcal = k;
  15.         vitaminc = v;
  16.     }
  17.    
  18.     public Bitmap getBitmap() { return bmp; }
  19.     public String getName() { return name; }
  20.     public int getKcal() { return kcal; }
  21.     public int getVitaminC() { return vitaminc; }
  22. }
  23.  
Parsed in 0.033 seconds, using GeSHi 1.0.8.4

Nothing changed here...

Next is the class helping us handling the DB:
DBhelper.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.fruitsdbsample;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4.  
  5. import android.content.ContentValues;
  6. import android.content.Context;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteOpenHelper;
  9. import android.graphics.Bitmap;
  10. import android.provider.BaseColumns;
  11.  
  12. public class DBhelper {
  13.     public static final String KEY_ID = BaseColumns._ID;
  14.     public static final String KEY_NAME = "name";
  15.     public static final String KEY_KCAL = "kcal";
  16.     public static final String KEY_VC = "vitaminc";
  17.     public static final String KEY_IMG = "image";
  18.    
  19.     private DatabaseHelper mDbHelper;
  20.     private SQLiteDatabase mDb;
  21.    
  22.     private static final String DATABASE_NAME = "FruitDB";
  23.     private static final int DATABASE_VERSION = 1;
  24.    
  25.     public static final String FRUITS_TABLE = "fruits";
  26.  
  27.     private static final String CREATE_FRUITS_TABLE = "create table "+FRUITS_TABLE+" ("
  28.                                          +KEY_ID+" integer primary key autoincrement, "
  29.                                          +KEY_IMG+" blob not null, "
  30.                                          +KEY_NAME+" text not null unique, "
  31.                                          +KEY_KCAL+" integer not null, "
  32.                                          +KEY_VC+" integer not null);";
  33.                                              
  34.     private final Context mCtx;
  35.     private boolean opened = false;
  36.    
  37.  
  38.     private static class DatabaseHelper extends SQLiteOpenHelper {
  39.         DatabaseHelper(Context context) {
  40.             super(context, DATABASE_NAME, null, DATABASE_VERSION);
  41.         }
  42.    
  43.         public void onCreate(SQLiteDatabase db) {
  44.             db.execSQL(CREATE_FRUITS_TABLE);
  45.         }
  46.    
  47.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  48.             db.execSQL("DROP TABLE IF EXISTS "+FRUITS_TABLE);
  49.             onCreate(db);
  50.         }
  51.     }
  52.    
  53.     public void Reset() {
  54.         openDB();
  55.         mDbHelper.onUpgrade(this.mDb, 1, 1);
  56.         closeDB();
  57.     }
  58.    
  59.     public DBhelper(Context ctx) {
  60.         mCtx = ctx;
  61.         mDbHelper = new DatabaseHelper(mCtx);
  62.     }
  63.    
  64.     private SQLiteDatabase openDB() {
  65.         if(!opened)
  66.             mDb = mDbHelper.getWritableDatabase();
  67.         opened = true;
  68.         return mDb;
  69.     }
  70.    
  71.     public SQLiteDatabase getHandle() { return openDB(); }
  72.    
  73.     private void closeDB() {
  74.         if(opened)
  75.             mDbHelper.close();
  76.         opened = false;
  77.     }
  78.  
  79.     public void createFruitEntry(Fruit fruit) {
  80.         openDB();
  81.         ByteArrayOutputStream out = new ByteArrayOutputStream();
  82.         fruit.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
  83.         ContentValues cv = new ContentValues();
  84.         cv.put(KEY_IMG, out.toByteArray());            
  85.         cv.put(KEY_NAME, fruit.getName());
  86.         cv.put(KEY_KCAL, fruit.getKcal());
  87.         cv.put(KEY_VC, fruit.getVitaminC());
  88.         mDb.insert(FRUITS_TABLE, null, cv);
  89.         closeDB();
  90.     }
  91. }
  92.  
Parsed in 0.043 seconds, using GeSHi 1.0.8.4

Nothing essential changed here...

Following class is new and defines how to bind the data to the Views.
Out of the box SimpleCursorAdapter supports TextView and ImageView but
images have to be in form of a image ressource or a URI. Therefore we need
this class to override default binding and/or define how to bind to other view types.
FruitViewBinder.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.fruitsdbsample;
  2.  
  3. import android.database.Cursor;
  4. import android.graphics.BitmapFactory;
  5. import android.view.View;
  6. import android.widget.ImageView;
  7. import android.widget.RatingBar;
  8. import android.widget.SimpleCursorAdapter;
  9.  
  10. public class FruitViewBinder implements SimpleCursorAdapter.ViewBinder {
  11.         public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
  12.                
  13.                 if(view instanceof ImageView) {
  14.                         ImageView iv = (ImageView) view;
  15.                         byte[] img = cursor.getBlob(columnIndex);
  16.                         iv.setImageBitmap(BitmapFactory.decodeByteArray(img, 0, img.length));
  17.                         return true;
  18.                 }
  19.  
  20.                 if(view instanceof RatingBar) {
  21.                         RatingBar rb = (RatingBar) view;
  22.                         int kcal = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_KCAL));
  23.                         int vitc = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_VC));
  24.                         rb.setRating((float) (kcal * ((float) vitc/1000.0)));
  25.                         return true;
  26.                 }
  27.                
  28.                 return false;
  29.         }
  30. }
  31.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Last class is the ListActivity that implements the example
FruitDBSample
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.fruitsdbsample;
  2.  
  3. import android.app.ListActivity;
  4. import android.database.Cursor;
  5. import android.graphics.Bitmap;
  6. import android.graphics.BitmapFactory;
  7. import android.os.Bundle;
  8. import android.widget.SimpleCursorAdapter;
  9.  
  10. public class FruitsDBSample extends ListActivity {
  11.     private DBhelper mDB;
  12.        
  13.     public void onCreate(Bundle savedInstanceState) {
  14.         super.onCreate(savedInstanceState);
  15.              
  16.         mDB = new DBhelper(this);
  17.        
  18.         mDB.Reset();
  19.        
  20.         Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
  21.        
  22.         mDB.createFruitEntry(new Fruit(img, "Banane",   92, 10));
  23.         mDB.createFruitEntry(new Fruit(img, "Kiwi",     56, 71));
  24.         mDB.createFruitEntry(new Fruit(img, "Pfirsich", 41, 10));
  25.         mDB.createFruitEntry(new Fruit(img, "Zitrone",  40, 51));
  26.        
  27.         String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC};
  28.         String   table   = mDB.FRUITS_TABLE;
  29.        
  30.         Cursor c = mDB.getHandle().query(table, columns, null, null, null, null, null);
  31.  
  32.         startManagingCursor(c);
  33.        
  34.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
  35.                 R.layout.fruitlist,
  36.                 c,
  37.                 new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC},
  38.                 new int[] {R.id.img, R.id.txt, R.id.rating});
  39.        
  40.         adapter.setViewBinder(new FruitViewBinder());
  41.  
  42.         setListAdapter(adapter);
  43.     }
  44. }
  45.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


And last but not least the xml that defines the layout of a row in the final list
fruitlist.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="wrap_content">
  6.    
  7.     <ImageView
  8.        android:id = "@+id/img"
  9.        android:layout_width = "wrap_content"
  10.        android:layout_height = "wrap_content"
  11.        android:layout_alignParentLeft = "true">
  12.     </ImageView>
  13.    
  14.     <TextView
  15.        android:id = "@+id/txt"
  16.        android:layout_width = "wrap_content"
  17.        android:layout_height = "wrap_content"
  18.        android:layout_centerVertical = "true"
  19.        android:layout_toRightOf = "@id/img">
  20.     </TextView>
  21.    
  22.     <RatingBar
  23.        style="?android:attr/ratingBarStyleSmall"    
  24.        android:id = "@+id/rating"
  25.        android:numStars = "5"
  26.        android:stepSize = "0.5"
  27.        android:layout_width = "wrap_content"
  28.        android:layout_height = "wrap_content"
  29.        android:layout_alignParentRight = "true"
  30.        android:layout_centerVertical = "true"
  31.        android:layout_marginRight = "5px">
  32.     </RatingBar>
  33.    
  34.     <TextView
  35.        android:text = "Healthindex: "
  36.        android:layout_width = "wrap_content"
  37.        android:layout_height = "wrap_content"
  38.        android:layout_centerVertical = "true"
  39.        android:layout_toLeftOf = "@id/rating">
  40.     </TextView>
  41.    
  42. </RelativeLayout>
  43.  
Parsed in 0.005 seconds, using GeSHi 1.0.8.4


This is all pretty straight forward so no further explanation at this point.. but should something
remain unclear feel free to ask.

Greets Padde

--- Edit ---
And this is how it looks like.

Image







sorry for distrabbing u .

sir , when i use this application in Android 2.1 , successfully runnign .

but when i use this application in Android 1.5

it shows the application FruitsDBSample (process com.android.fruit )has stopped unexpectedly.
pleaese try again .

please find out the solution and send the code for Andoird 1.5 .

andalso in Android 2.1 , when i use the
setContentView(R.layout.main); // my main contain listview and button for refresh
it also show stopped unexpectedly .please try again .

Thank you.
hany
Junior Developer
Junior Developer
 
Posts: 19
Joined: Sat Mar 13, 2010 6:35 am

Postby padde » Sun May 02, 2010 8:17 pm

You really shouldn´t use android 1.5 anymore.
It has so many bugs and even the G1 is running 1.6 or later these times.

Anyway i found the problem.. its a bug in the SimpleCursorAdapter.. remove
all imports and use this version:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package de.padde.fruitsdbsample;
  3.  
  4.  
  5.  
  6. import android.content.Context;
  7.  
  8. import android.database.Cursor;
  9.  
  10. import android.net.Uri;
  11.  
  12. import android.view.View;
  13.  
  14. import android.view.ViewGroup;
  15.  
  16. import android.widget.ImageView;
  17.  
  18. import android.widget.ResourceCursorAdapter;
  19.  
  20. import android.widget.TextView;
  21.  
  22.  
  23.  
  24. import java.util.WeakHashMap;
  25.  
  26.  
  27.  
  28. public class SimpleCursorAdapter extends ResourceCursorAdapter {
  29.  
  30.     protected int[] mFrom;
  31.  
  32.     protected int[] mTo;
  33.  
  34.  
  35.  
  36.     private int mStringConversionColumn = -1;
  37.  
  38.     private CursorToStringConverter mCursorToStringConverter;
  39.  
  40.     private ViewBinder mViewBinder;
  41.  
  42.     private String[] mOriginalFrom;
  43.  
  44.     private Cursor mCursor;
  45.  
  46.     private final WeakHashMap<View, View[]> mHolders = new WeakHashMap<View, View[]>();
  47.  
  48.  
  49.  
  50.     public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
  51.  
  52.         super(context, layout, c);
  53.  
  54.         mTo = to;
  55.  
  56.         mOriginalFrom = from;
  57.  
  58.         mCursor = c;
  59.  
  60.         findColumns(from);
  61.  
  62.     }
  63.  
  64.  
  65.  
  66.     public View newView(Context context, Cursor cursor, ViewGroup parent) {
  67.  
  68.         return generateViewHolder(super.newView(context, cursor, parent));
  69.  
  70.     }
  71.  
  72.  
  73.  
  74.     public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
  75.  
  76.         return generateViewHolder(super.newDropDownView(context, cursor, parent));
  77.  
  78.     }
  79.  
  80.  
  81.  
  82.     private View generateViewHolder(View v) {
  83.  
  84.         final int[] to = mTo;
  85.  
  86.         final int count = to.length;
  87.  
  88.         final View[] holder = new View[count];
  89.  
  90.  
  91.  
  92.         for (int i = 0; i < count; i++) {
  93.  
  94.             holder[i] = v.findViewById(to[i]);
  95.  
  96.         }
  97.  
  98.         mHolders.put(v, holder);
  99.  
  100.  
  101.  
  102.         return v;
  103.  
  104.     }
  105.  
  106.  
  107.  
  108.     public void bindView(View view, Context context, Cursor cursor) {
  109.  
  110.         final View[] holder = mHolders.get(view);
  111.  
  112.         final ViewBinder binder = mViewBinder;
  113.  
  114.         final int count = mTo.length;
  115.  
  116.         final int[] from = mFrom;
  117.  
  118.  
  119.  
  120.         for (int i = 0; i < count; i++) {
  121.  
  122.             final View v = holder[i];
  123.  
  124.             if (v != null) {
  125.  
  126.                 boolean bound = false;
  127.  
  128.                 if (binder != null) {
  129.  
  130.                     bound = binder.setViewValue(v, cursor, from[i]);
  131.  
  132.                 }
  133.  
  134.  
  135.  
  136.                 if (!bound) {
  137.  
  138.                     String text = cursor.getString(from[i]);
  139.  
  140.                     if (text == null) {
  141.  
  142.                         text = "";
  143.  
  144.                     }
  145.  
  146.  
  147.  
  148.                     if (v instanceof TextView) {
  149.  
  150.                         setViewText((TextView) v, text);
  151.  
  152.                     } else if (v instanceof ImageView) {
  153.  
  154.                         setViewImage((ImageView) v, text);
  155.  
  156.                     } else {
  157.  
  158.                         throw new IllegalStateException(v.getClass().getName() + " is not a " +
  159.  
  160.                                 " view that can be bounds by this SimpleCursorAdapter");
  161.  
  162.                     }
  163.  
  164.                 }
  165.  
  166.             }
  167.  
  168.         }
  169.  
  170.     }
  171.  
  172.  
  173.  
  174.     public ViewBinder getViewBinder() {
  175.  
  176.         return mViewBinder;
  177.  
  178.     }
  179.  
  180.  
  181.  
  182.     public void setViewBinder(ViewBinder viewBinder) {
  183.  
  184.         mViewBinder = viewBinder;
  185.  
  186.     }
  187.  
  188.  
  189.  
  190.     public void setViewImage(ImageView v, String value) {
  191.  
  192.         try {
  193.  
  194.             v.setImageResource(Integer.parseInt(value));
  195.  
  196.         } catch (NumberFormatException nfe) {
  197.  
  198.             v.setImageURI(Uri.parse(value));
  199.  
  200.         }
  201.  
  202.     }
  203.  
  204.  
  205.  
  206.     public void setViewText(TextView v, String text) {
  207.  
  208.         v.setText(text);
  209.  
  210.     }
  211.  
  212.  
  213.  
  214.     public int getStringConversionColumn() {
  215.  
  216.         return mStringConversionColumn;
  217.  
  218.     }
  219.  
  220.  
  221.  
  222.     public void setStringConversionColumn(int stringConversionColumn) {
  223.  
  224.         mStringConversionColumn = stringConversionColumn;
  225.  
  226.     }
  227.  
  228.  
  229.  
  230.     public CursorToStringConverter getCursorToStringConverter() {
  231.  
  232.         return mCursorToStringConverter;
  233.  
  234.     }
  235.  
  236.  
  237.  
  238.     public void setCursorToStringConverter(CursorToStringConverter cursorToStringConverter) {
  239.  
  240.         mCursorToStringConverter = cursorToStringConverter;
  241.  
  242.     }
  243.  
  244.  
  245.  
  246.     public CharSequence convertToString(Cursor cursor) {
  247.  
  248.         if (mCursorToStringConverter != null) {
  249.  
  250.             return mCursorToStringConverter.convertToString(cursor);
  251.  
  252.         } else if (mStringConversionColumn > -1) {
  253.  
  254.             return cursor.getString(mStringConversionColumn);
  255.  
  256.         }
  257.  
  258.  
  259.  
  260.         return super.convertToString(cursor);
  261.  
  262.     }
  263.  
  264.  
  265.  
  266.     private void findColumns(String[] from) {
  267.  
  268.         if (mCursor != null) {
  269.  
  270.             int i;
  271.  
  272.             int count = from.length;
  273.  
  274.             if (mFrom == null || mFrom.length != count) {
  275.  
  276.                 mFrom = new int[count];
  277.  
  278.             }
  279.  
  280.             for (i = 0; i < count; i++) {
  281.  
  282.                 mFrom[i] = mCursor.getColumnIndexOrThrow(from[i]);
  283.  
  284.             }
  285.  
  286.         } else {
  287.  
  288.             mFrom = null;
  289.  
  290.         }
  291.  
  292.     }
  293.  
  294.  
  295.  
  296.     public void changeCursor(Cursor c) {
  297.  
  298.         super.changeCursor(c);
  299.  
  300.         findColumns(mOriginalFrom);
  301.  
  302.     }
  303.  
  304.    
  305.  
  306.     public void changeCursorAndColumns(Cursor c, String[] from, int[] to) {
  307.  
  308.         mOriginalFrom = from;
  309.  
  310.         mTo = to;
  311.  
  312.         super.changeCursor(c);        
  313.  
  314.         findColumns(mOriginalFrom);
  315.  
  316.     }
  317.  
  318.  
  319.  
  320.     public static interface ViewBinder {
  321.  
  322.         boolean setViewValue(View view, Cursor cursor, int columnIndex);
  323.  
  324.     }
  325.  
  326.  
  327.  
  328.     public static interface CursorToStringConverter {
  329.  
  330.         CharSequence convertToString(Cursor cursor);
  331.  
  332.     }
  333.  
  334.  
  335.  
  336. }
  337.  
  338.  
Parsed in 0.059 seconds, using GeSHi 1.0.8.4


After that the Sample works under 1.5 but the layout is broken.. i'am in no mood
to mess around with the buggy 1.5 layouts to make it look the same.. but here is
a layout that at least displays everything.
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.    android:orientation="vertical"
  7.  
  8.    android:layout_width="fill_parent"
  9.  
  10.    android:layout_height="wrap_content">
  11.  
  12.    
  13.  
  14.     <ImageView
  15.  
  16.        android:id = "@+id/img"
  17.  
  18.        android:layout_width = "wrap_content"
  19.  
  20.        android:layout_height = "wrap_content"
  21.  
  22.        android:layout_alignParentLeft = "true">
  23.  
  24.     </ImageView>
  25.  
  26.    
  27.  
  28.                 <TextView
  29.  
  30.                     android:id = "@+id/txt"
  31.  
  32.                     android:layout_width = "wrap_content"
  33.  
  34.                     android:layout_height = "wrap_content"
  35.  
  36.                     android:layout_toRightOf = "@id/img">
  37.  
  38.                 </TextView>
  39.  
  40.                
  41.  
  42.                 <RatingBar
  43.  
  44.                     style="?android:attr/ratingBarStyleSmall"    
  45.  
  46.                     android:id = "@+id/rating"
  47.  
  48.                     android:numStars = "5"
  49.  
  50.                     android:stepSize = "0.5"
  51.  
  52.                     android:layout_width = "wrap_content"
  53.  
  54.                     android:layout_height="wrap_content"
  55.  
  56.                     android:layout_alignParentRight ="true"
  57.  
  58.                     android:layout_marginRight = "5px">
  59.  
  60.                 </RatingBar>
  61.  
  62.                
  63.  
  64.                 <TextView
  65.  
  66.                     android:text = "Healthindex: "
  67.  
  68.                     android:layout_width = "wrap_content"
  69.  
  70.                     android:layout_height = "wrap_content"
  71.  
  72.                     android:layout_toLeftOf = "@id/rating">
  73.  
  74.                 </TextView>
  75.  
  76. </RelativeLayout>
  77.  
  78.  
Parsed in 0.005 seconds, using GeSHi 1.0.8.4


About that android 2.1 problem... your "main" layout must contain a ListView with the id "@android:id/list".

Example here:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <?xml version="1.0" encoding="utf-8"?>
  3.  
  4. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  5.  
  6.    android:orientation="vertical"
  7.  
  8.    android:layout_width="fill_parent"
  9.  
  10.    android:layout_height="fill_parent">
  11.  
  12.    
  13.  
  14.     <ListView
  15.  
  16.      android:id="@android:id/list"
  17.  
  18.      android:layout_width="fill_parent"
  19.  
  20.      android:layout_height="fill_parent"
  21.  
  22.    />
  23.  
  24.    
  25.  
  26.     <Button
  27.  
  28.      android:layout_width="fill_parent"
  29.  
  30.      android:layout_height="wrap_content"
  31.  
  32.      android:layout_alignParentBottom="true"
  33.  
  34.      android:text="Test">
  35.  
  36.     </Button>
  37.  
  38. </RelativeLayout>
  39.  
  40.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


After that ListActivity knows what list to use and the setContentView is no longer a problem.

Greets Padde
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

PND image & SQLite DB

Postby hany » Mon May 03, 2010 7:05 am

Thanks for ur reply and also
Thanks for ur valuable suggestion.

sir , please send full source about this proble .


Thank yor sir .
hany
Junior Developer
Junior Developer
 
Posts: 19
Joined: Sat Mar 13, 2010 6:35 am

Postby padde » Mon May 03, 2010 8:25 am

What is missing? And what version of android do you target with your app?
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

PNG image & SQLite DB

Postby hany » Mon May 03, 2010 11:03 am

padde wrote:What is missing? And what version of android do you target with your app?



Thanks for ur reply.

Sir , my application Android 1.5 and minSdkVersion 3



Thank you sir.
hany
Junior Developer
Junior Developer
 
Posts: 19
Joined: Sat Mar 13, 2010 6:35 am

Top

Postby cem » Tue May 04, 2010 11:47 am

Hi guys,

I was wondering, how can I save the images, I mean do I have to load them in my projects (resources ). I dont understand that.
cem
Freshman
Freshman
 
Posts: 4
Joined: Tue Apr 27, 2010 7:18 pm

Postby padde » Tue May 04, 2010 1:51 pm

In this case i used the default icon image that comes with a android project in eclipse.
But you could also download them beforehand and store them in the database or the SDcard.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Re: PNG image -> SQLite DB -> imageview

Postby HarryH » Sun May 23, 2010 7:04 pm

Apologies for resurrecting an old thread but I still cannot get this working. I am having the same problem as the original poster where a reference of something is stored in the database as opposed to the actual byte array.

I am using this code:
Code: Select all
                  
                  byte[] avatarBytes = vCard.getAvatar();
               
                  icon = BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length);

                  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                    icon.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                    ContentValues cv = new ContentValues();
                    cv.put("avatar", outputStream.toByteArray());           
                   
                                      mDbHelper.open();
                  database.addAvatar(uid, cv, hash);
                  mDbHelper.close();

     


database.java:
Code: Select all
public class database {



    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "avatardatabase";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private class DatabaseHelper extends SQLiteOpenHelper {

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

 
        @Override
        public void onCreate(SQLiteDatabase db) {

          
           
       ns
           
           
           db.execSQL("create table avatars (_id integer primary key autoincrement, userid text not null, avatar blob, avatar_hash text not null);");

        }

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

           db.execSQL("DROP TABLE IF EXISTS avatars");
           
            onCreate(db);
        }
    }

      public databasecheck(Context ctx) {
        this.mCtx = ctx;
    }

 
    public databasecheck open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
   
    public void close() {
        mDbHelper.close();
       
    }


          }


        public static void addAvatar(String uid, ContentValues avatar, String hash) {
          
           String sqlstring = "insert into avatars (userid, avatar, avatar_hash) values ('" + uid + "', '" + avatar + "', '" + hash + "');";
           mDb.execSQL(sqlstring);

        }
          }





Even after using ContentValues the contents of the 'avatars' table in the SQLIite database still only show the reference only in a different format (avatar=[B@43670ae8).

What am I doing wrong here?

Any help would be greatly appreciated.
Thankyou in advance.

Harry.
HarryH
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sun Mar 29, 2009 6:50 pm

Re: PNG image -> SQLite DB -> imageview

Postby padde » Sun May 23, 2010 7:54 pm

I really dont get what you are doing in your code or lets better say why you do it.
Please see the commends in the code.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     // you get an image as byte array from an vCard object here
  2.     byte[] avatarBytes = vCard.getAvatar();
  3.    
  4.     // convert the byte array to an bitmap              
  5.     icon = BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length);
  6.  
  7.     // and here you convert the bitmap again to an byte array.. but why?
  8.     // all you do effectivly is reencoding the image
  9.     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  10.     icon.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
  11.  
  12.     // here i really dont know why or how contentvalue should help?!
  13.     ContentValues cv = new ContentValues();
  14.     cv.put("avatar", outputStream.toByteArray());          
  15.    
  16.     // finally here you put the contentvalue into the database but you want/need byte array              
  17.     mDbHelper.open();
  18.     database.addAvatar(uid, cv, hash);
  19.     mDbHelper.close();
  20.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


Because i think this reencoding is just a failure working code should look like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     // Simply put the byte array directly into the Database without contentvalue
  2.     mDbHelper.open();
  3.     database.addAvatar(uid, vCard.getAvater(), hash);
  4.     mDbHelper.close();
  5.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


And in your Database class change the addAvatar method to this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     public static void addAvatar(String uid, byte[] avatar, String hash) {
  2.         String sqlstring = "insert into avatars (userid, avatar, avatar_hash)
  3.                           values ('" + uid + "', '" + avatar + "', '" + hash + "');";
  4.         mDb.execSQL(sqlstring);
  5.     }
  6.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Re: PNG image -> SQLite DB -> imageview

Postby HarryH » Sun May 23, 2010 10:16 pm

Whoa, thanks for the quick reply Padde. Sorry for all the rubbish in my code; it's left over from just mucking around with it.

I have scoured the web for a solution and they all seem to involved adding the byte array into ContentValues first which is why I have done that.

My first attempt was to add avatarBytes directly into the database which is basically what your code is also.
I have tried your code but am unfortunately still getting the 'references' in the table when I pull it from the emulator and open it with SQLIte Browser.

Have also tried using 1.6 instead of 1.5 but with that same result.

Any more thoughts on the problem?

Thanks,
Harry.
HarryH
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sun Mar 29, 2009 6:50 pm

Re: PNG image -> SQLite DB -> imageview

Postby padde » Sun May 23, 2010 11:46 pm

Ooops mistake by me.. you will need a preparedstatement or use the insert
function of the SQLiteDataBase class like i did in my example with the fruits stuff.
The method takes care about how to insert all kinds of data the right way.. maybe
their you have seen contentvalues... because you will need them for this method ;)

This would change your addAvatar method to this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public static void addAvatar(String uid, byte[] avatar, String hash) {
  2.     ContentValues cv = new ContentValues();
  3.     cv.put("avatar", avatar);            
  4.     cv.put("userid", uid);
  5.     cv.put("avatar_hash", hash);
  6.     mDb.insert("avatars", null, cv));
  7. }
  8.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


And still use it like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     mDbHelper.open();
  2.     database.addAvatar(uid, vCard.getAvater(), hash);
  3.     mDbHelper.close();
  4.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


PS. Sorry for confusing you ;)
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Re: PNG image -> SQLite DB -> imageview

Postby HarryH » Mon May 24, 2010 10:41 am

Thankyou very much Padde.

Your code works perfectly and once again I have learnt a little bit more about Java from this forum.

Thanks again,
Harry
HarryH
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sun Mar 29, 2009 6:50 pm

Re: PNG image -> SQLite DB -> imageview

Postby jiqqaman » Sat Sep 25, 2010 12:28 am

Hello, Im new to android development. Heres what im trying to accomplish.

>>> Click here to view a drawing <<<<

basically im trying to get the images that the user has selected and save that to a database. The images are located /res/drawable/
jiqqaman
Freshman
Freshman
 
Posts: 6
Joined: Sat Sep 25, 2010 12:23 am

Re: PNG image -> SQLite DB -> imageview

Postby rockyknight007 » Mon Oct 04, 2010 4:21 am

Hello Experts

I am a new baby for Android developments.
Please give me information for -
(1) Can communicate "Andriod and WCF (.Net)" ?
(2) If can communicate , please develop a very small app for me. (Hello World or Small Calculator (Addition)).

Best Regards
Kyaw
rockyknight007
Freshman
Freshman
 
Posts: 4
Joined: Mon Oct 04, 2010 3:42 am

Top
PreviousNext

Return to Networking & Database Problems

Who is online

Users browsing this forum: No registered users and 4 guests