Handling data from intent after orientation change - android

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

Related

How to make custom camera layout in Android?

I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.

how can i store gallery image in application directory

i have got the image directly from the camera , gallery to the image view in my app its all working fine.
Now what I want is to save this image from Image View to the application directory and also access it when required.
//You Can try This
File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/yourDirectoryname");
myDir.mkdirs();
File file = new File(myDir, yourImagePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
public class EditProfile extends AppCompatActivity {
ImageView imageView;
EditText Name,Email,MobileNo;
public static int count = 0;
String loginid;
Bitmap bitmap;
private static final int CAMERA_REQUEST = 1888;
String picturePath;
static int i=0;
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
byte[] image = null;
Button button1;
static File out;
String path1;
ImageView imageView1;
Bitmap photo ;
byte[] b=null;
Button EditProfile;
String Username;
String name;
String email;
String Imgpath;
String Imgpath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
EditProfile=(Button)findViewById(R.id.edit_profile);
Imgpath=getSharedPreferences("Bytearray",0).getString("Bytearray",null);
Imgpath1=getSharedPreferences("uri",0).getString("uri",null);
imageView=(ImageView)findViewById(R.id.profile_photo);
EditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
String path=out.getAbsolutePath();
getSharedPreferences("path",0).edit().putString("path",path).commit();
imageView.setImageBitmap(mBitmap);
}
else if (requestCode == 2) {
imageView.setImageURI(selectedImage);
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// imageView.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap image=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
imageView.setImageBitmap(image);
}
}
}
Initiate the camera intent like this by creating a file of known path,and after the image capture Your image appears in that path:
Uri capturedImageUri;//global variable
private void initiateImageCapture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
capturedImageUri = Uri.fromFile(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile == null || capturedImageUri == null) {
Utils.showLongToast(getActivity(), "error");
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
startActivityForResult(takePictureIntent, Constants.INTENT_IMAGE_CAPTURE);
else
Utils.showLongToast(getActivity(), "try again);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}

Image not Uploading to SQLite Database

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.

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();
}

android upload image to amazon storage with image path

I want to upload a image using it's file path. Most of the tutorial I have followed regarding upload image to amazon, there is select image option(image chooser from galary). But what i need is that:
But I want to skip this step. As I know the image path and name. Suppose I have a image in a directory in the device. When user click upload photo button, it will start uploading. I want to skip select image option. But How Can I upload image to amazon storage with image path instead of selecting image (Intent image/*)?
So in short I am just wanting to use file path directly instead of select image option to upload the image in amazon.
Any help will be greatly appreciated. Thanks in advance.
Edited:
Here is my activity:
public class SubmitActivity extends Activity {
Button submit;
ImageView thumbnailimage;
private AmazonS3Client s3Client = new AmazonS3Client(
new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
Constants.SECRET_KEY));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().setDisplayShowTitleEnabled(false);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));
setContentView(R.layout.submit);
submit = (Button) findViewById(R.id.buttonsubmit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri selectedImage = Uri.parse(Environment
.getExternalStorageDirectory().toString()
+ File.separator + "cubicasa.jpg");
new S3PutObjectTask().execute(selectedImage);
}
});
thumbnailimage = (ImageView) findViewById(R.id.thumbimg);
byte[] imageData = null;
try {
final int THUMBNAIL_SIZE = 150;
// InputStream is=getAssets().open("apple-android-battle.jpg");
FileInputStream fis = new FileInputStream(Environment
.getExternalStorageDirectory().toString()
+ File.separator
+ "cubicasa.jpg");
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width / height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap,
(int) (THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
thumbnailimage.setImageBitmap(imageBitmap);
} catch (Exception ex) {
}
}
private class S3PutObjectTask extends AsyncTask<Uri, Void, S3TaskResult> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(SubmitActivity.this);
dialog.setMessage(SubmitActivity.this.getString(R.string.uploading));
dialog.setCancelable(false);
dialog.show();
}
protected S3TaskResult doInBackground(Uri... uris) {
if (uris == null || uris.length != 1) {
return null;
}
// The file location of the image selected.
Uri selectedImage = uris[0];
ContentResolver resolver = getContentResolver();
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedImage, fileSizeColumn, null,
null, null);
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an
// int can't be
// null in java, the behavior is implementation-specific, which is
// just a fancy
// term for "unpredictable". So as a rule, check if it's null before
// assigning
// to an int. This will happen often: The storage API allows for
// remote
// files, whose size might not be locally known.
String size = null;
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString
// will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(resolver.getType(selectedImage));
if (size != null) {
metadata.setContentLength(Long.parseLong(size));
}
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
s3Client.createBucket(Constants.getPictureBucket());
PutObjectRequest por = new PutObjectRequest(
Constants.getPictureBucket(), Constants.PICTURE_NAME,
resolver.openInputStream(selectedImage), metadata);
s3Client.putObject(por);
} catch (Exception exception) {
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
SubmitActivity.this
.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
}
}
protected void displayErrorAlert(String title, String message) {
AlertDialog.Builder confirm = new AlertDialog.Builder(this);
confirm.setTitle(title);
confirm.setMessage(message);
confirm.setNegativeButton(
SubmitActivity.this.getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SubmitActivity.this.finish();
}
});
confirm.show().show();
}
private class S3TaskResult {
String errorMessage = null;
Uri uri = null;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
}
}
Here is my log cat error:
Try this:
Uri uriImg =Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/Images/img1.jpg");
PutObjectRequest por = new PutObjectRequest( Constants.getPictureBucket(),
Constants.PICTURE_NAME, new java.io.File( uriImg) );
s3Client.putObject( por );
I hpoe this help:

Categories

Resources