Image not Uploading to SQLite Database - android

I am new to android programming so hopefully someone can be off help. Been having issues with attempting to add an image from Gallery or Camera to my SQLite database. I stumbled across someone's GitHub who had a CameraGallerySqliteDemo
Found here
I tried to amend the code for my needs but have been unable to add an image to my gallery table.
Below is the class I am using to add images to the database.
public class add_gallery extends AppCompatActivity {
Button addImage;
ArrayList<Gall> imageArry = new ArrayList<Gall>();
GalleryImageAdapter imageAdapter;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
ListView dataList;
//maybe change to image title later
byte[] imageName;
int imageId;
Bitmap theImage;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_gallery);
dataList = (ListView) findViewById(R.id.list);
/**
* create DatabaseHelper object
*/
myDb = new DatabaseHelper(this);
/**
* Reading and getting all records from database
*/
List<Gall> images = myDb.getAllGallery();
for (Gall cn : images) {
String log = "ID:" + cn.getID() + " Image: " + cn.getImage()
+ " ,Title: " + cn.getTitle()
+ " ,Caption: " + cn.getCaption();
// Writing Galls to log
Log.d("Result: ", log);
// add images data in arrayList
imageArry.add(cn);
}
/**
* Set Data base Item into listview
*/
imageAdapter = new GalleryImageAdapter(this, R.layout.gallery_list,
imageArry);
dataList.setAdapter(imageAdapter);
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getImage();
imageId = imageArry.get(position).getID();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(add_gallery.this,
DisplayImageActivity.class);
intent.putExtra("imageid", imageId);
intent.putExtra("imagename", theImage);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Take from Camera",
"Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
addImage = (Button) findViewById(R.id.btnAdd);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
/**
* On activity result
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Galls
Log.d("Insert: ", "Inserting ..");
myDb.addGallery(new Gall("Android", imageInByte));
Intent i = new Intent(add_gallery.this,
add_gallery.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Galls
Log.d("Insert: ", "Inserting ..");
myDb.addGallery(new Gall("Android", imageInByte));
Intent i = new Intent(add_gallery.this,
add_gallery.class);
startActivity(i);
finish();
}
break;
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
}
Below is the method I call to add an Image to the Gallery, addGallery
public// Adding new image to gallery
void addGallery(Gall gallery) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(IMAGE, gallery._image);
values.put(TITLE, gallery._title);
values.put(CAPTION, gallery._caption);
// Inserting Row
db.insert(GALLERY_TABLE, null, values);
db.close(); // Closing database connection
}
Below is the Gall class
public class Gall {
// private variables
int _id;
byte[] _image;
String _title;
String _caption;
// Empty constructor
public Gall() {
}
// constructor
public Gall(int keyId, byte[] image, String title, String caption) {
this._id = keyId;
this._image = image;
this._title = title;
this._caption = caption;
}
public Gall(byte[] image, String title, String caption) {
this._image = image;
this._title = title;
this._caption = caption;
}
public Gall(int keyId) {
this._id = keyId;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting image
public byte[] getImage() {
return this._image;
}
// setting image
public void setImage(byte[] image) {
this._image = image;
}
// getting
public String getTitle() {
return this._title;
}
// setting title
public void setTitle(String title) {
this._title = title;
}
// getting caption
public String getCaption() {
return this._title;
}
// setting caption
public void setCaption(String caption) {
this._title = caption;
}
Perhaps a trained eye can spot where I am going wrong, I not receiving any errors, just that the image is not being added to database table. Any help would be greatly appreciated.

Store image as byte array in the db.
Please check the example here. This might help you.

You should save your images in a folder and save their paths in you db . If you want your images to be protected and don't wanna show them in gallery as well then there are some ways like using .nomedia files or you can save your images in private folder which will not be accessible to any other app rather than yours.

Related

How to save image in storage folder as well as in database when I changed profile picture in android?

My mainactivity has code which takes picture from camera and from gallary .
public class MainActivity extends Activity {
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChoosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main11);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.ivImage);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity11.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(MainActivity11.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
}
It works fine. But, I am not getting how to save this image into the database as well as in a storage folder.
Save Image in storage folder :
MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), bitmap, "Detected Image", "");
And bitmap in Sqlite database :
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatbase12";
private static final String TABLE_NAME= name
private static final String KEY_ID = "id";
//Pancard variable
private static final String KEY_NAME = "pancard_name";
private static final String KEY_PHOTO = "Photo";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAIL_TABLE = "CREATE TABLE " + TABLE_NAME+ "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT ,"
+ KEY_PHOTO
+ " blob not null" + ")";
db.execSQL(CREATE_DETAIL_TABLE);
System.out.println("table created ");
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME
// Create tables again
onCreate(db);
db.close();
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new PANCARD detail
public void addData(String data,Bitmap bitmap) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, data); // tital
values.put(KEY_PHOTO, Utility.getBytes(bitmap));
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
}
add Utilty class for conver image to byte:
public class Utility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
So now pass bitmap in addData method like : addData("name",bitmap)
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
// store this imagePath in your database
String imagePath = destination.getAbsolutePath();
Thanks
Finally I resolved all my issue :
private void selectImage() {
final CharSequence[] items = { "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Saving to Database...
if (saveImageInDB(selectedImageUri)) {
//Image Saved in Database...
profile_pic.setImageURI(selectedImageUri);
}
// Reading from Database after 3 seconds just to show the message
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (loadImageFromDB()) {
//Image Loaded from Database...
}
}
}, 3000);
}
}
}
// Save image in database
Boolean saveImageInDB(Uri selectedImageUri) {
try {
dbHelper.open();
InputStream iStream = getActivity().getContentResolver().openInputStream(selectedImageUri);
byte[] inputData = Utils.getBytes(iStream);
dbHelper.editUserImage(inputData,LoginDetails.user_id);
dbHelper.close();
return true;
} catch (IOException ioe) {
Log.e("EditProfileFragment", "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
dbHelper.close();
return false;
}
}
//load image from database
Boolean loadImageFromDB() {
try {
dbHelper.open();
byte[] bytes = dbHelper.retreiveImageFromDB(LoginDetails.user_id);
dbHelper.close();
// Show Image from DB in ImageView
profile_pic.setImageBitmap(Utils.getImage(bytes));
return true;
} catch (Exception e) {
Log.e("EditProfileFragment", "<loadImageFromDB> Error : " + e.getLocalizedMessage());
dbHelper.close();
return false;
}
}
}
and my util.java
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();
}
public static void slide_down(Context ctx, View v){
Animation a = AnimationUtils.loadAnimation(ctx,R.anim.slide_down);
if(a != null){
a.reset();
if(v != null){
v.clearAnimation();
v.startAnimation(a);
}
}
}
}
dbhelper functions :
public void editUserImage(byte[] imageBytes, String user_id ) {
try{
ContentValues cv = new ContentValues();
cv.put(IMAGE, imageBytes);
mDb.update(USER_TABLE, cv, ID + " = " + user_id + "", null);
}catch(Exception e)
{
e.printStackTrace();
}
}
public byte[] retreiveImageFromDB(String user_id) {
try{
Cursor cur = mDb.query(true, USER_TABLE, new String[]{IMAGE},
ID+"=?",new String[]{user_id}, null, null, null,null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
cur.close();
return blob;
}
cur.close();
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
This is working fine.

Decode and Show Image Thumbnail in MessageBox Android Activity Firebase

I am following this tutorial. With this link you can see my comment for the particular problem, I followed this tutorial and I was at success to send and receive text messages on both peers. I can also see my Firebase database from console and its updating as well. Thing working fine till here.
Now, I want to send/receive camera images to Firebase, so I found various methods to convert a image to Base64 encode string, upload that string to Firebase database, I am success at this also.
I have successfully uploaded the encoded string to Firebase. Now as my current system is build for only text string messages application got crash when it receives encode string .
How to decode encoded string back to bitmap?
Show bitmap image thumbnail in MessageBox
Here is my modified chat.java activity code: as a reference you can follow the provided url up for chat.java class and how it works originally, but I am unable to achieve decoding and showing bitmap thumbnail in messagebox.
chat.java
public class Chat extends AppCompatActivity {
LinearLayout layout;
ImageView sendButton,vidcall,cam;
public final static String AUTH_KEY_FCM = "";
public final static String API_URL_FCM = "";
EditText messageArea;
ScrollView scrollView;
Firebase reference1, reference2;
private ConnectionDetector cd;
String urltok;
public static String msg;
String tuk;
private Uri selectedImage = null;
private Bitmap bitmap, bitmapRotate;
String imagepath = "";String fname;
File file;
private Boolean upflag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_chat);
cd = new ConnectionDetector(Chat.this);
layout = (LinearLayout)findViewById(R.id.layout1);
sendButton = (ImageView)findViewById(R.id.sendButton);
vidcall = (ImageView)findViewById(R.id.vidBtnk);
messageArea = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
cam = (ImageView)findViewById(R.id.pictk);
Firebase.setAndroidContext(this);
reference1 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
reference2 = new Firebase("https://*******.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);
cd = new ConnectionDetector(getApplicationContext());
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
msg = messageText;
if(!messageText.equals("")){
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user", UserDetails.username);
reference1.push().setValue(map);
reference2.push().setValue(map);
}
new RetrieveFeedTask().execute();
messageArea.setText("");
}
});
vidcall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Chat.this, ConnectActivity.class));
}
});
cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, 101);
}
});
reference1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if(userName.equals(UserDetails.username)){
addMessageBox("You:-\n" + message, 1);
// addimagethumb(bitmapRotate,1);
}
else{
addMessageBox(UserDetails.chatWith + ":-\n" + message, 2);
// addimagethumb(bitmapRotate,2);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
} //oncreate ends
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case 101:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
selectedImage = data.getData(); // the uri of the image taken
if (String.valueOf((Bitmap) data.getExtras().get("data")).equals("null")) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
} else {
bitmap = (Bitmap) data.getExtras().get("data");
}
if (Float.valueOf(getImageOrientation()) >= 0) {
bitmapRotate = rotateImage(bitmap, Float.valueOf(getImageOrientation()));
} else {
bitmapRotate = bitmap;
bitmap.recycle();
}
// ivImage.setVisibility(View.VISIBLE);
//ivImage.setImageBitmap(bitmapRotate);
//                            Saving image to mobile internal memory for sometime
//String root = getApplicationContext().getFilesDir().toString();
String root = "/storage/emulated/0";
File myDir = new File(root + "/hidoctor");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
//                            Give the file name that u want
fname = "null" + n + ".jpg";
imagepath = root + "/hidoctor/" + fname;
file = new File(myDir, fname);
upflag = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
if (cd.isConnectingToInternet()) {
if (!upflag) {
Toast.makeText(Chat.this, "Image Not Captured..!", Toast.LENGTH_LONG).show();
} else {
saveFile(bitmapRotate, file);
encodeBitmapAndSaveToFirebase(bitmapRotate);
}
} else {
Toast.makeText(Chat.this, "No Internet Connection !", Toast.LENGTH_LONG).show();
}
}
public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
String imageEncoded = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
reference1.child("imageUrl").push().setValue(imageEncoded);
reference2.child("imageUrl").push().setValue(imageEncoded);
}
private int getImageOrientation() {
final String[] imageColumns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imageColumns, null, null, imageOrderBy);
if (cursor.moveToFirst()) {
int orientation = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION));
System.out.println("orientation===" + orientation);
cursor.close();
return orientation;
} else {
return 0;
}
}
public static Bitmap rotateImage(Bitmap source, float angle) {
Bitmap retVal;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
return retVal;
}
// Saving file to the mobile internal memory
private void saveFile(Bitmap sourceUri, File destination) {
if (destination.exists()) destination.delete();
try {
FileOutputStream out = new FileOutputStream(destination);
sourceUri.compress(Bitmap.CompressFormat.JPEG, 60, out);
out.flush();
out.close();
if (cd.isConnectingToInternet()) {
//new DoFileUpload().execute();
} else {
Toast.makeText(Chat.this, "No Internet Connection..", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void addimagethumb(Bitmap pic , int type){
ImageView imgpresc = new ImageView(Chat.this);
imgpresc.setImageBitmap(pic);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 10);
imgpresc.setLayoutParams(lp);
if(type == 1) {
// textView.setBackgroundResource(R.drawable.rounded_corner1);
}
else{
// textView.setBackgroundResource(R.drawable.rounded_corner2);
}
layout.addView(imgpresc);
scrollView.fullScroll(View.FOCUS_DOWN);
}
public void addMessageBox(String message, int type){
TextView textView = new TextView(Chat.this);
//ImageView imgpresc = new ImageView(Chat.this);
textView.setText(message);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, 10);
textView.setLayoutParams(lp);
if(type == 1) {
textView.setBackgroundResource(R.drawable.rounded_corner1);
}
else{
textView.setBackgroundResource(R.drawable.rounded_corner2);
}
layout.addView(textView);
scrollView.fullScroll(View.FOCUS_DOWN);
}
}
So Far I am getting this :
Now when we tap cam icon on appbar it goes to camera takes the picture and on return it saves image to device storage and encode&upload to firebase after this iwant both users to see like this image
I Want like this
If you check my chat.java activity class I tried to add imageview dynamically to view but when user encode and upload the picture once and when on next session upon oncreate the activity crashed for null value . system gets confuse when retrieving the message from map for user . and all the references got lost .
Kindly help me , I am stuck on this for more than 30 days . It will be much appreciated . Thanks
I solved this issue by creating a separate child for images and wverything worked fine
imagref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map2 = dataSnapshot.getValue(Map.class);
String retrieveEncodedImg = map2.get("imageUrl").toString();
Log.e("encodedimagegetmap2", retrieveEncodedImg+"");
byte[] decodedString = Base64.decode(retrieveEncodedImg, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
addimagethumb(decodedByte,1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Here you can check my output

how to put image in Android using Insert Into query in SQLite Android?

I'm a newbie in Android,
I just wondering how to store an image to SQLite database in Android, well i have database look like this.
Photo
id (int) | image (BLOB)
Then i have a class to get an image from gallery..
LogoSQLiDemoActivity
public class LogoSQLiteDemoActivity extends Activity implements OnClickListener{
ContactImageAdapter imageAdapter;
Validation valid;
DBDataSource db;
private ArrayList<image> imageArry = new ArrayList<image>();
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
int imageId;
byte[] imageName;
String nama_foto;
String nama;
Bitmap theImage;
byte imageInByte[];
private Long id;
//widget
private EditText edNama_foto;
Button addImage;
Button cancel;
ListView dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_data_photo2);
/*** create DatabaseHandler object*/
db = new DBDataSource(this);
//error in here
db.open();
dataList = (ListView) findViewById(R.id.list);
cancel = (Button)findViewById(R.id.btnCancel);
addImage = (Button) findViewById(R.id.btnAdd);
cancel.setOnClickListener(this);
Sma sekolah = db.getLastSma();
id = sekolah.getId();
/**
* Reading and getting all records from database
*/
List<image> img = db.getAllImage_Logo(id);
for (image cn : img)
{
// add contacts data in arrayList
imageArry.add(cn);
/** Set Data base Item into listview}*/
imageAdapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry);
dataList.setAdapter(imageAdapter);
}
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getLokasi_foto();
imageId = imageArry.get(position).get_id_sma();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(LogoSQLiteDemoActivity.this,
DisplayImageActivity2.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Ambil dari Kamera",
"Pilih dari Album" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pilihan");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Pilihan", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
/**
* On activity result
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this, LogoSQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null)
{
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this,
LogoSQLiteDemoActivity.class);
startActivity(i);
finish();
}
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 150);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnCancel:
Intent intent = new Intent(getApplicationContext(), MenuAdmin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
and this a method i use to store picture in sqlite
public void addImage3(image img) {
open(); //it's mean to open the connection from database
//THE Question is right here, how i can put a byte array into database
//without using this method, a.k.a INSERT INTO, cause i have tried to search any
//solution in google, but i can't solve my problem
ContentValues values = new ContentValues();
values.put(image, img._lokasi_foto);
// Inserting Row
database.insert(Photo, null, values);
close(); // Closing database connection
}
and here's my image class
public class image {
public byte[] _lokasi_foto;
//this is getter
public byte[] getLokasi_foto() {
return _lokasi_foto;
}
//this is setter
public void setLokasi_foto(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
and this the constructor
public image(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
}
Can someone help me with this problem, cause i have been search in google, but i can't still solve my problem, Please Help...
Save the image in a local folder with the same name as your id. So now whenever you want to retrieve the image, just open id.jpg / id.png
private void saveToDB() {
SQLiteDatabase myDb;
String MySQL;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL = "create table emp1(_id INTEGER primary key autoincrement, sample TEXT not null, audio BLOB);";
myDb = openOrCreateDatabase("Blob List", Context.MODE_PRIVATE, null);
myDb.execSQL(MySQL);
String s = myDb.getPath();
textView.append("\r\n" + s + "\r\n");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("sample", "HI Hello");
try {
InputStream is = new FileInputStream("YOUR IMAGE PATH");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
textView.append("\r\n" + bytes.length + "\r\n");
newValues.put("audio", bytes);
long ret = myDb.insert("emp1", null, newValues);
if (ret < 0)
textView.append("\r\n!!! Error add blob failed!!!\r\n");
} catch (IOException e) {
textView.append("\r\n!!! Error: " + e + "!!!\r\n");
}
Cursor cur = myDb.query("emp1", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\r\n" + cur.getString(1) + "\r\n");
cur.moveToNext();
}
// /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("audio"));
// bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
// byteImage2.length));
textView.append("\r\n" + byteImage2.length + "\r\n");
cur.close();
myDb.close();
}

Handling data from intent after orientation change

My app is set to only display in portrait mode. The problem is that I need to use a camera and a gallery intent and you can't specify those apps to be the same orientation so some funky stuff happens in between those orientation changes which makes my image data null.
This code works fine when the phone isn't tilted sideways (in portrait mode) how would I improve it to handle data after an orientation change?
public class PostPhotosActivity extends Activity {
public static final String TAG = "PostPhotosActivity";
String title, price, description, maincat, subcat, pname, pemail, pphone, pmeet, imageUri;
public static final String TEMP_PHOTO_FILE_NAME = "temp_photo.jpg";
public static final int REQUEST_CODE_GALLERY = 0x1;
public static final int REQUEST_CODE_TAKE_PICTURE = 0x2;
public static final int REQUEST_CODE_CROP_IMAGE = 0x3;
private ImageView mImageView;
private File mFileTemp;
ParseFile file;
double latitude, longitude;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //To change body of overridden methods use File | Settings | File Templates.
setContentView(R.layout.activity_post_photos);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
title = extras.getString("TITLE"); // get the value based on the key
price = extras.getString("PRICE"); // get the value based on the key
description = extras.getString("DESCRIPTION"); // get the value based on the key
maincat = extras.getString("MAINCAT"); // get the value based on the key
subcat = extras.getString("SUBCAT"); // get the value based on the key
pname = extras.getString("PNAME"); // get the value based on the key
pemail = extras.getString("PEMAIL"); // get the value based on the key
pphone = extras.getString("PPHONE"); // get the value based on the key
pmeet = extras.getString("PMEET"); // get the value based on the key
}
button = (Button) findViewById(R.id.post_data);
button.setVisibility(View.INVISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(PostPhotosActivity.this);
/**
* Set GPS Location fetched address
*/
if (mGpsLocationTracker.canGetLocation())
{
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
Log.i(TAG, String.format("latitude: %s", latitude));
Log.i(TAG, String.format("longitude: %s", longitude));
}
else
{
mGpsLocationTracker.showSettingsAlert();
}
ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
ParseObject setPost = new ParseObject("testData");
// Create an author relationship with the current user
setPost.put("author", ParseUser.getCurrentUser());
// Get location
setPost.put("location", point);
setPost.put("Title", title);
setPost.put("Price", price);
setPost.put("Description", description);
setPost.put("MainCat", maincat);
setPost.put("SubCat", subcat);
setPost.put("PName", pname);
setPost.put("PEmail", pemail);
setPost.put("PPhone", pphone);
setPost.put("PMeet", pmeet);
setPost.put("Photo", file);
setPost.saveInBackground();
Intent intent = new Intent(PostPhotosActivity.this, Flow.class);
startActivity(intent);
}
});
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
takePicture();
} else { // pick from file
openGallery();
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.iv_photo);
mImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE_NAME);
}
else {
mFileTemp = new File(getFilesDir(), TEMP_PHOTO_FILE_NAME);
}
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
/*
* The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "cannot take picture", e);
}
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
private void startCropImage() {
Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
intent.putExtra(CropImage.SCALE, true);
intent.putExtra(CropImage.ASPECT_X, 1);
intent.putExtra(CropImage.ASPECT_Y, 1);
startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
startCropImage();
} catch (Exception e) {
Log.e(TAG, "Error while creating temp file", e);
}
break;
case REQUEST_CODE_TAKE_PICTURE:
startCropImage();
break;
case REQUEST_CODE_CROP_IMAGE:
String path = data.getStringExtra(CropImage.IMAGE_PATH);
if (path == null) {
return;
}
//byte[] idata = path.getBytes();
Bitmap picture = BitmapFactory.decodeFile(path);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
picture.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// get byte array here
byte[] idata= stream.toByteArray();
file = new ParseFile("photo.jpg", idata);
file.saveInBackground();
bitmap = BitmapFactory.decodeFile(mFileTemp.getPath());
mImageView.setImageBitmap(bitmap);
button.setVisibility(View.VISIBLE);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
]
You could use fragments to retain the information that is being lost by the orientation change.
http://www.vogella.com/articles/AndroidFragments/article.html#headlessfragments2

nullpointer exception raises when i click on the button

When I click on CheckData button on android, it is throwing a nullpointer exception.
SaveData.java
public class SaveData extends Activity implements OnClickListener {
static final int DIALOG_ID = 0;
private Uri mImageCaptureUri;
private ImageView mImageView;
public static class Certificates {
private Bitmap bmp;
public Certificates(Bitmap b) {
bmp = b;
}
public Bitmap getBitmap() { return bmp; }
}
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.addname);
View button1Click=findViewById(R.id.btn_choose);
button1Click.setOnClickListener(this);
View button2Click = findViewById(R.id.Button01add);
button2Click.setOnClickListener(this);
View button3Click = findViewById(R.id.Button01check);
button3Click.setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.Button01add:
showDialog(DIALOG_ID);
break;
case R.id.Button01check:
startActivity(new Intent (SaveData.this,CheckData.class));
break;
}
// picking an image from camera or gallery
final String [] items = new String [] {"From Camera", "From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.image1);
((Button) findViewById(R.id.btn_choose)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = "";
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
protected final Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Information saved successfully ! Add Another Info?")
.setCancelable(false)
.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SaveData.this.finish();
}
})
.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
dialog = alert;
break;
default:
}
return dialog;
}
// menu option
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.item1) {
Log.d("Option", "Save option is clicked");
}
if(item.getItemId() == R.id.item2) {
Log.d("Option", "Delete option is clicked");
}
if(item.getItemId() == R.id.item3) {
Log.d("Option", "Exit option is clicked");
}
return super.onOptionsItemSelected(item);
}
}
DataManipulator.java:
public class DataManipulator {
public static final String KEY_IMG = "image";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "DBtest";
private static final int DATABASE_VERSION = 1;
private static final String CERTIFICATES_TABLE = "certificates";
private static final String CREATE_CERTIFICATES_TABLE = "create table "+CERTIFICATES_TABLE+" (" +KEY_IMG+" blob not null) ";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CERTIFICATES_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+CERTIFICATES_TABLE);
onCreate(db);
}
}
public void Reset() { mDbHelper.onUpgrade(this.mDb, 1, 1); }
public DataManipulator(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DataManipulator open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() { mDbHelper.close(); }
public void createCertificatesEntry(Certificates certificates) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
mDb.insert(CERTIFICATES_TABLE, null, cv);
}
public Certificates getFirstCertificatesFromDB() throws SQLException {
Cursor cur = mDb.query(true, CERTIFICATES_TABLE, new String[] {KEY_IMG}, null, null, null, null, null, null);
if(cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(KEY_IMG));
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
cur.close();
return new Certificates(bitmap);
}
cur.close();
return null;
}
}
DataManipulator.java:60 is certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
CheckData.java:
public class CheckData extends ListActivity {
TextView selection;
DataManipulator dm;
private DataManipulator DataManipulator;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
LinearLayout layout = new LinearLayout(this);
ImageView image = new ImageView(this);
DataManipulator = new DataManipulator(this);
Certificates testCertificates = new Certificates(BitmapFactory.decodeFile(Context.STORAGE_SERVICE));
DataManipulator.open();
DataManipulator.createCertificatesEntry( (Certificates) testCertificates);
DataManipulator.close();
testCertificates = null;
DataManipulator.open();
testCertificates = DataManipulator.getFirstCertificatesFromDB();
DataManipulator.close();
image.setImageBitmap(((Certificates) testCertificates).getBitmap());
setContentView(layout);
}
}
CheckData.java:29 is DataManipulator.createCertificatesEntry( (Certificates) testCertificates);
Logcat error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{list.certificates/list.certificates.CheckData}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
at android.app.ActivityThread.access$600(ActivityThread.java:122)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at list.certificates.DataManipulator.createCertificatesEntry(DataManipulator.java:60)
at list.certificates.CheckData.onCreate(CheckData.java:29)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
You're getting a null from certificates.getBitmap() because there's not a bitmap there. In your initial assignment, you're trying to decode a file that doesn't exist. Using Context.STORAGE_SERVICE doesn't work that way, it's just a string equaling storage.
For example code of how to use a storage manager properly, try this.
If you're just trying to decode a resource(drawable, raw, etc) use another form of decode:
InputStream is = context.getResources().openRawResource(resID);
Bitmap bitmap = BitmapFactory.decodeStream(is);
Update:
Assuming I know what it is you're trying to do, the problem is that you're switching to the CheckData activity without passing the selected bitmap in any way. The activity has no way of knowing what bitmap to use, and Context.STORAGE_SERVICE is not a bitmap in any way, so you can't decode it.
For good answers on how to pass the bitmap to the new activity, look here.
In short, you could add an mBitmap variable to SaveData, and pass it along to CheckData.
For this, change the code in SaveData.onClick() to:
case R.id.Button01check:
Intent intent = new Intent (SaveData.this,CheckData.class);
intent.putExtra("bitmapData", mBitmap)
startActivity(intent);
break;
And, in onActivityResult(), add this at the end:
mBitmap = bitmap;
In CheckData.onCreate():
Bitmap bmp = getIntent().getExtras().get("bitmapData");
if(bmp != null) {
Certificates testCertificates = new Certificates(bmp);
} else {
// Back out gracefully //
}
Problem root:
Your problem is in this line
Certificates testCertificates =
new Certificates(BitmapFactory.decodeFile(Context.STORAGE_SERVICE));
The parameter to decodeFile is invalid hence it returns null. The parameter should be the path to the image file, whereas you are passing a constant that is to be used for retrieving the storage service.
Fix:
You already have the bitmap in SaveData activity. You need to pass it to CheckData activity through intent.
Add the bitmap to the intent :
case R.id.Button01check:
Intent intent = new Intent(this, CheckData.class);
intent.putExtra("BitmapImage", bitmap);
startActivity(intent);
Then in CheckData activity, retrieve the bitmap from intent and create the Certificates object.
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("BitmapImage");
Certificates testCertificates = new Certificates(bitmap );
Reference: How can I pass a Bitmap object from one activity to another
Either certificates is null, or certificates.getBitmap() is returning null. Add logging to find out which.
check certificates is null or not before inserting data as:
public void createCertificatesEntry(Certificates certificates) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if(certificates !=null)
{
certificates.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
mDb.insert(CERTIFICATES_TABLE, null, cv);
}
else
{
}
}
generally , in order to handle exceptions, i would give you this tip:
when you get the exception on the logcat , double click (or press
ENTER) each of the red lines of the logs in this chunk , till the text
cursor goes to the correct line that you got the exception .
then , once you know on which of the variables you got the expcetion ,
put a breakpoint there ,on the event of clicking , and on the event of
onCreate , to see why you got this exception .
however , your code has so many weird things , for example:
why do you call setContentView twice in the same method ?
why do you try to decode a bitmap file which its name is Context.STORAGE_SERVICE ?
why do you have a class and and instance with the same name (DataManipulator) ? please use a more standard way to name fields and variables.

Categories

Resources