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
Related
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.
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.
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:
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
In my app, I' using Tab. There are three tabs. In which 3rd tab is Activity group which has two activities. In first activity, there are two options for user. User can choose image from camera or from gallery. After selecting an image, user should move to child activity, which will display selected image in that activity. Till this app is working fine. But only problem here I'm facing is, image is not being cleared when I move back to parent activity from child activity. Means once I choose image from gallery/camera, user moves to child activity, and image is being displayed in child activity. Now when I press back button from child activity, user moves back to parent activity and again if user selects different image from galley/camera, that different image is not there in child activity. The previous image is there in child activity. Below is my code.
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
View view;
int column_index;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
view = getLocalActivityManager().startActivity("ParentActivity", new Intent(ABCGroup.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(view);
}
public void replaceView(View v) {
history.add(v);
setContentView(v);
}
public void back() {
if(history.size() > 0)
{
history.remove(history.size()-1);
if(history.size()<=0)
{
finish();
}
else
{
setContentView(history.get(history.size()-1));
}
}
else
{
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == Tab1.REQUEST_ID && resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
if (requestCode == 3 && resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(Tab1.mUri, null);
ContentResolver cr = getContentResolver();
try
{
Tab1.mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, Tab1.mUri);
Second.bmp = Tab1.mPhoto;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Tab1.mPhoto.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File direct = new File(Environment.getExternalStorageDirectory() + "/ABCGroup");
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Toast.makeText(getBaseContext(), "Time :" + mydate, 5000).show();
if(!direct.exists())
{
direct.mkdir();
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
else
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
return cursor.getString(column_index);
}
public void onResume()
{
super.onResume();
column_index = 0;
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
ImageView iv;
private static final int TAKE_PICTURE = 3;
public static final int REQUEST_ID = 1;
private static final int HALF = 2;
public static Uri mUri;
public static Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.tab1);
View viewToLoad = LayoutInflater.from(Tab1.this.getParent()).inflate(R.layout.tab1, null);
Tab1.this.setContentView(viewToLoad);
myActivityHistory = new ArrayList<View>();
gallery = (Button)viewToLoad.findViewById(R.id.gallery);
camera = (Button)viewToLoad.findViewById(R.id.camera);
iv = (ImageView)viewToLoad.findViewById(R.id.iv);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
ABCGroup.group.startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
ABCGroup.group.startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent)
{
View mview = ABCGroup.group.getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)).getDecorView();
ABCGroup.group.replaceView(mview);
}
}
Second.java
public class Second extends Activity {
public static Bitmap bmp;
Bitmap myBitmap;
String path;
ImageView iv;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
View viewToLoad = LayoutInflater.from(Second.this.getParent()).inflate(R.layout.second, null);
Second.this.setContentView(viewToLoad);
Button btn = (Button)viewToLoad.findViewById(R.id.button1);
iv = (ImageView)viewToLoad.findViewById(R.id.imageView1);
iv.setImageBitmap(bmp);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Toast.makeText(getBaseContext(), "" + path, 1000).show();
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY ) );
}
public void onResume()
{
super.onResume();
}
}
Finally I got the answer
public void onResume()
{
super.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
imgFile = new File(path);
Toast.makeText(getBaseContext(), "" + path, 2000).show();
if(imgFile.exists())
{
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}