I'm trying to make a app where i can take a picture of something and then set that picture to a ImageView and I have succeded with that. the next step is to be able the save the picture in the imageView so that the picture remains the same even when closing and reopening the app. I am using SharedPrefrences for storing some other values but i can't find a way to use it for images. Here is my code:
package com.example.pongrknare;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ImageView imageView1;
private ImageView imageView2;
private ImageView imageView3;
private ImageView imageView4;
private ImageView imageView5;
private ImageView imageView6;
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private Switch undoSwitch;
private int nr = 1;
private int p1 = 0;
private int p2 = 0;
private int p3 = 0;
private int p4 = 0;
private int p5 = 0;
private int p6 = 0;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String P1 = "P1_value";
public static final String P2 = "P2_value";
public static final String P3 = "P3_value";
public static final String P4 = "P4_value";
public static final String P5 = "P5_value";
public static final String P6 = "P6_value";
private static final int REQUEST_IMAGE_CAPTURE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
imageView3 = findViewById(R.id.imageView3);
imageView4 = findViewById(R.id.imageView4);
imageView5 = findViewById(R.id.imageView5);
imageView6 = findViewById(R.id.imageView6);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
textView4 = findViewById(R.id.textView4);
textView5 = findViewById(R.id.textView5);
textView6 = findViewById(R.id.textView6);
undoSwitch = findViewById(R.id.undoSwitch);
loadData();
update_text();
}
public void takePicture1(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 1;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture2(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 2;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture3(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 3;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture4(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 4;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture5(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 5;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture6(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 6;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.reset_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.ja1:
p1 = 0;
p2 = 0;
p3 = 0;
p4 = 0;
p5 = 0;
p6 = 0;
update_text();
return true;
case R.id.ja2:
imageView1.setImageResource(R.color.colorImage);
imageView2.setImageResource(R.color.colorImage);
imageView3.setImageResource(R.color.colorImage);
imageView4.setImageResource(R.color.colorImage);
imageView5.setImageResource(R.color.colorImage);
imageView6.setImageResource(R.color.colorImage);
return true;
}
return super.onOptionsItemSelected(item);
}
private void update_text(){
textView1.setText("" + p1);
textView2.setText("" + p2);
textView3.setText("" + p3);
textView4.setText("" + p4);
textView5.setText("" + p5);
textView6.setText("" + p6);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (nr==1) {
Bundle extras = data.getExtras();
Bitmap imageBitmap1 = (Bitmap) extras.get("data");
imageView1.setImageBitmap(imageBitmap1);
saveData();
} else if(nr == 2){
Bundle extras = data.getExtras();
Bitmap imageBitmap2 = (Bitmap) extras.get("data");
imageView2.setImageBitmap(imageBitmap2);
saveData();
}else if(nr == 3){
Bundle extras = data.getExtras();
Bitmap imageBitmap3 = (Bitmap) extras.get("data");
imageView3.setImageBitmap(imageBitmap3);
saveData();
}else if(nr == 4){
Bundle extras = data.getExtras();
Bitmap imageBitmap4 = (Bitmap) extras.get("data");
imageView4.setImageBitmap(imageBitmap4);
saveData();
}else if(nr == 5){
Bundle extras = data.getExtras();
Bitmap imageBitmap5 = (Bitmap) extras.get("data");
imageView5.setImageBitmap(imageBitmap5);
saveData();
}else if(nr == 6){
Bundle extras = data.getExtras();
Bitmap imageBitmap6 = (Bitmap) extras.get("data");
imageView6.setImageBitmap(imageBitmap6);
saveData();
}else{
return;
}
}
public void count1(View view) {
if (undoSwitch.isChecked()== false) {
p1++;
}else if(p1> 0){
p1--;
}
textView1.setText(""+p1);
saveData();
}
public void count2(View view) {
if (undoSwitch.isChecked()== false) {
p2++;
}else if(p2>0){
p2--;
}
textView2.setText(""+p2);
saveData();
}
public void count3(View view) {
if (undoSwitch.isChecked()== false) {
p3++;
}else if(p3>0){
p3--;
}
textView3.setText(""+p3);
saveData();
}
public void count4(View view) {
if (undoSwitch.isChecked()== false) {
p4++;
}else if(p4>0){
p4--;
}
textView4.setText(""+p4);
saveData();
}
public void count5(View view) {
if (undoSwitch.isChecked()== false) {
p5++;
}else if(p5>0){
p5--;
}
textView5.setText(""+p5);
saveData();
}
public void count6(View view) {
if (undoSwitch.isChecked()== false) {
p6++;
}else if(p6>0){
p6--;
}
textView6.setText(""+p6);
saveData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(P1, p1);
editor.putInt(P2, p2);
editor.putInt(P3, p3);
editor.putInt(P4, p4);
editor.putInt(P5, p5);
editor.putInt(P6, p6);
editor.apply();
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
p1 = sharedPreferences.getInt(P1, 0);
p2 = sharedPreferences.getInt(P2, 0);
p3 = sharedPreferences.getInt(P3, 0);
p4 = sharedPreferences.getInt(P4, 0);
p5 = sharedPreferences.getInt(P5, 0);
p6 = sharedPreferences.getInt(P6, 0);
}
}
You can save the photos to the app pictures directory as follows
1. Generate the image file:
private File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_Hms").format(new Date());
String fileName = "JPEG_" + timestamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoImage = File.createTempFile(fileName, ".jpg", storageDir);
// Store this value in field to use later
picture1Path = photoImage.getAbsolutePath();
return photoImage;
}
Add the image file Uri to the IMAGE_CAPTURE intent:
private void takePicture1() {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), e.getMessage(), e);
}
// Add file Uri to intent
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile(
this,"com.your_app_package.fileprovider", photoFile);
imageTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
Save image Uri to shared preferences if image capture successful:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
setPic();
// Save imageUri
preferences.edit().putString("image1Uri", currentPhotoPath).apply();
}
}
}
private void setPic() {
// load and display pic
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
imageView1.setImageBitmap(bitmap);
}
4. Then set up the FileProvider:
In the app manifest.xml inside the tag:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your_app_package.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Also include the WRITE_EXTERNAL_STORAGE permission.
The create the "file_paths.xml" and add:
<paths>
<external-files-path name="my_images" path="/"/>
</paths>
And then in onCreate load the image file Uri from preferences and display:
currentPhotoPath = preferences.getString("image1Uri", null);
if (currentPhotoPath != null) {
setPic();
}
Related
I have pdf reader with listview with icon pdf
and how to make cover pdf show in listview like this?
or
source code: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/
How to change pdf icon to cover pdf in listview?
thanks
Main Activity.java
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
Log.e("Position", i + "Pdf");
}
});
}
public static ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".pdf")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
PdfActivity
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init() {
pdfView = (PDFView) findViewById(R.id.pdfView);
//position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
position = getIntent().getIntExtra("position", -1);
displayFromSdcard();
//String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.password("123456")
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
PdfAdapter
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PDFAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}
You can create the image by creating the bitmap of pdf first page. Then save the image to your app directory to be used later. You can use PdfiumCore (which is dependency of barteks PdfView) to generate the image.
You can use the following:
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class PDFUtils {
static String generateAndSaveFirstPageImage(Context context, Uri uri, long bookId) {
try {
ParcelFileDescriptor fd = context.getContentResolver().openFileDescriptor(uri, "r");
int pageNum = 0;
PdfiumCore pdfiumCore = new PdfiumCore(context);
try {
PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
pdfiumCore.openPage(pdfDocument, 0); // open first page for cover.
int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);
// do a fit center to 1920x1080
//double scaleBy = Math.min(1080 / (double) width, //
// 1920 / (double) height);
//width = (int) (width * scaleBy);
//height = (int) (height * scaleBy);
// ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
// RGB_565 - little worse quality, twice less memory usage
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNum, 0, 0, width, height);
//if you need to render annotations and form fields, you can use
//the same method above adding 'true' as last param
String fileName = bookId + ".jpg";
// save the file
File outputFile = new File(context.getFilesDir(), fileName);
FileOutputStream outputStream = new FileOutputStream(outputFile);
// a bit long running
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
fd.close();
pdfiumCore.closeDocument(pdfDocument); // important!
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then, you need to use the class by using the following:
long bookId = 2345; // your book identifier
Url yourPdfUrl; // url of pdf in your device
PdfUtils.generateAndSaveFirstPageImage(context, yourPdfUrl, bookId);
After you have saved the image, you can use the image again with something like this:
String imagePath = getFilesDir() + "/" + yourBookId + ".jpg";
I am developing a gallery application, I display all the icons from the external storage into my application. I followed the tutorial from the below link and it is working.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/
Now in addition to this, I provide an option for the user to take a picture from the application and save it to the gallery. When the picture is taken using the Camera intent, the image gets actually saved in the gallery. But I have to intent to another fragment and come back to the Gallery to see the picture I have taken.
To see the changes immediately, onActivityResult() of the Camera intent, I am recreating the fragment. But the problem occurs when we click the back button. The recreated fragment stays in the backstack forever. I am brain faded searching for answers. Any help is appreciated.
Please find below what I have tried so far.
public class GalleryFragment extends Fragment {
Toolbar toolbar;
MenuItem search;
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
FloatingActionButton cameraButton;
private static final int REQUEST_PERMISSIONS = 100;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_IMAGE_CAPTURE = 1;
String projectName = "ProjectGA";
File directory;
String mCurrentPhotoPath;
List<GridViewItem> gridItems;
GridView gridView;
public static GalleryFragment newInstance(){
GalleryFragment galleryFragment = new GalleryFragment();
return galleryFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
directory = new File(Environment.getExternalStorageDirectory() + projectName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
ImageView icon = (ImageView) getActivity().findViewById(R.id.toolbarIcon);
icon.setImageResource(R.drawable.ic_perm_media_black_24dp);
icon.setColorFilter(getResources().getColor(R.color.Gallery));
TextView title = (TextView) getActivity().findViewById(R.id.toolbarTitle);
title.setText(getString(R.string.galleryLabel));
title.setTextColor(getResources().getColor(R.color.textInputEditTextColor));
toolbar.setBackground(getResources().getDrawable(R.drawable.tile_green));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_green_24dp));
cameraButton = (FloatingActionButton) getActivity().findViewById(R.id.rightActionButton);
cameraButton.setVisibility(View.VISIBLE);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
#Override
public void onDestroyView() {
cameraButton.setVisibility(View.INVISIBLE);
super.onDestroyView();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
getFragmentManager().beginTransaction()
.replace(R.id.container_gaFragments, GalleryFragment.newInstance()).commit();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I also override the onBackPressed() in the Activity. Please help. Also attaching some images to make it clear.
The exact problem of what is happening
Any help is appreciated.
I am uploading image to server but image is rotate after uploaded to server Even preview is showing correct.
So many people facing this problem i found this link but didn't work. And there is many solution but i am not figure out how to fit in my code.
Please help me.
Here is my code
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class AddVehicleDocActivity extends AppCompatActivity {
private static final int FILE_SELECT_CODE = 124;
private Toolbar mToolbar;
TextView text_header;
MyTextView insuranceHTxt;
MyTextView permitHTxt;
MyTextView vRegHTxt;
MyTextView insNotFoundTxt;
MyTextView permitNotFoundTxt;
MyTextView vRegNotFoundTxt;
DBConnect dbConnect;
Button insBtn;
Button permitBtn;
Button vRegBtn;
LinearLayout insImgVIew;
LinearLayout permitImgVIew;
LinearLayout vRegImgVIew;
String language_labels_get_frm_sqLite = "";
String LBL_DOCUMENTS_TXT_str = "";
String LBL_YOUR_INSURANCE_TXT_str = "";
String LBL_WRONG_FILE_SELECTED_TXT_str = "";
String LBL_LOADING_TXT_str = "";
String LBL_YOUR_PERMIT_TXT_str = "";
String LBL_VEHICLE_REG_TXT_str = "";
String LBL_NOT_FOUND_TXT_str = "";
String LBL_BTN_OK_TXT_str = "";
String LBL_ERROR_TXT_str = "";
String LBL_TRY_AGAIN_LATER_TXT_str = "";
String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
String LBL_ADD_TXT_str = "";
String LBL_EDIT_TXT_str = "";
String LBL_SUCCESS_TXT_str = "";
String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
String LBL_CANCEL_TXT_str = "";
String currentDocType = "";
String carJson_str = "";
String vIns = "";
String vPermit = "";
String vReg = "";
android.support.v7.app.AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_vehicle_doc);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
text_header = (TextView) findViewById(R.id.text_header);
insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);
insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);
insBtn = (Button) findViewById(R.id.insBtn);
permitBtn = (Button) findViewById(R.id.permitBtn);
vRegBtn = (Button) findViewById(R.id.vRegBtn);
insBtn.setOnClickListener(new setOnClickAct());
permitBtn.setOnClickListener(new setOnClickAct());
vRegBtn.setOnClickListener(new setOnClickAct());
insImgVIew.setOnClickListener(new setOnClickAct());
permitImgVIew.setOnClickListener(new setOnClickAct());
vRegImgVIew.setOnClickListener(new setOnClickAct());
carJson_str = getIntent().getStringExtra("CarJson");
/* Set Labels */
getLanguageLabelsFrmSqLite();
/* Set Labels Finished */
ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
back_navigation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddVehicleDocActivity.super.onBackPressed();
}
});
Log.d("carJson_str", ":" + carJson_str);
try {
parseCarJson(carJson_str);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLanguageLabelsFrmSqLite() {
Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");
cursor.moveToPosition(0);
language_labels_get_frm_sqLite = cursor.getString(0);
JSONObject obj_language_labels = null;
try {
obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (obj_language_labels != null) {
text_header.setText("" + LBL_DOCUMENTS_TXT_str);
insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
insBtn.setText(LBL_ADD_TXT_str);
permitBtn.setText(LBL_ADD_TXT_str);
vRegBtn.setText(LBL_ADD_TXT_str);
}
}
public void parseCarJson(String carJson) throws JSONException {
JSONObject obj_profile = new JSONObject(carJson);
vIns = obj_profile.getString("vInsurance");
vPermit = obj_profile.getString("vPermit");
vReg = obj_profile.getString("vRegisteration");
if (vIns == null || vIns.equals("")) {
insNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(0);
}
if (vPermit == null || vPermit.equals("")) {
permitNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(1);
}
if (vReg == null || vReg.equals("")) {
vRegNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(2);
}
}
public void setDocView(int id) {
if (id == 0) {
insNotFoundTxt.setVisibility(View.GONE);
insBtn.setText(LBL_EDIT_TXT_str);
insImgVIew.setVisibility(View.VISIBLE);
} else if (id == 1) {
permitNotFoundTxt.setVisibility(View.GONE);
permitBtn.setText(LBL_EDIT_TXT_str);
permitImgVIew.setVisibility(View.VISIBLE);
} else if (id == 2) {
vRegNotFoundTxt.setVisibility(View.GONE);
vRegBtn.setText(LBL_EDIT_TXT_str);
vRegImgVIew.setVisibility(View.VISIBLE);
}
}
public class setOnClickAct implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.insBtn:
currentDocType = "vInsurance";
chooseFIle();
break;
case R.id.permitBtn:
currentDocType = "vPermit";
chooseFIle();
break;
case R.id.vRegBtn:
currentDocType = "vRegisteration";
chooseFIle();
break;
case R.id.insImgArea:
openDocument(vIns);
break;
case R.id.permitImgArea:
openDocument(vPermit);
break;
case R.id.vRegImgArea:
openDocument(vReg);
break;
}
}
}
public void openDocument(String documentName) {
Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
startActivity(browserIntent);
}
public void chooseFIle() {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
// Log.d("Path", "::" + uri.getPath());
// Log.d("Path", "::" + getPath(uri));
String filePath = "";
filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);
// Log.d("Ext", ":" + getFileExt(filePath));
final ArrayList<String[]> paramsList = new ArrayList<>();
paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
paramsList.add(generateImageParams("DocUploadType", currentDocType));
if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
|| getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
|| getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {
File selectedFile = new File(filePath);
if (selectedFile != null) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);
final String finalFilePath = filePath;
alertDialogBuilder
.setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
.setCancelable(true)
.setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
})
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
// showErrorOnSelection();
showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
}
}
}
}
public String[] generateImageParams(String key, String content) {
String[] tempArr = new String[2];
tempArr[0] = key;
tempArr[1] = content;
return tempArr;
}
public class uploadDocument extends AsyncTask<String, String, String> {
String selectedPath;
String responseString = "";
ProgressDialog myPDialog;
String temp_File_Name = "";
ArrayList<String[]> paramsList;
public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
this.selectedPath = selectedPath;
this.temp_File_Name = temp_File_Name;
this.paramsList = paramsList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
myPDialog.setMessage("" + LBL_LOADING_TXT_str);
myPDialog.setCancelable(false);
myPDialog.setCanceledOnTouchOutside(false);
myPDialog.show();
}
#Override
protected String doInBackground(String... strings) {
responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myPDialog.dismiss();
Log.d("responseString", "::" + responseString);
if (responseString != null && !responseString.equals("")) {
try {
JSONObject obj_temp = new JSONObject(responseString);
String action_str = obj_temp.getString("Action");
String fileName_str = obj_temp.getString("vFileName");
if (action_str.equals("1")) {
showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);
JSONObject obj_CarJson = new JSONObject(carJson_str);
if (currentDocType.equals("vInsurance")) {
obj_CarJson.remove("vInsurance");
obj_CarJson.put("vInsurance", fileName_str);
vIns = fileName_str;
setDocView(0);
} else if (currentDocType.equals("vPermit")) {
obj_CarJson.remove("vPermit");
obj_CarJson.put("vPermit", fileName_str);
vPermit = fileName_str;
setDocView(1);
} else if (currentDocType.equals("vRegisteration")) {
obj_CarJson.remove("vRegisteration");
obj_CarJson.put("vRegisteration", fileName_str);
vReg = fileName_str;
setDocView(2);
}
obj_CarJson.remove("eStatus");
obj_CarJson.put("eStatus", "Inactive");
carJson_str = obj_CarJson.toString();
Intent setData = new Intent();
setData.putExtra("CarJson", carJson_str);
setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
setResult(RESULT_OK, setData);
// Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
// Driver_main_profile.driverDocUpdated = true;
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} catch (JSONException e) {
e.printStackTrace();
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
}
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else {
return null;
}
}
public void showMessage(String title_str, String content_str) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(title_str);
alertDialogBuilder
.setMessage(content_str)
.setCancelable(true)
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is my Upload code
public class UploadFile {
public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {
ExifInterface exif = null; //Since API Level 5
try {
exif = new ExifInterface(sourceFileUri);
} catch (IOException e) {
e.printStackTrace();
}
String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
String responseString = "";
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(exifImage));
byte[] data;
try {
data = convertToByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);
for (int i = 0; i < params.size(); i++) {
String[] paramsArr = params.get(i);
multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
}
ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
multipartEntity.addPart(imageParamKey, cbFile);
httpPost.setEntity(multipartEntity);
// httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
// httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
// httpPost.setHeader("Content-Type", "multipart/form-data");
// httpPost.setHeader("Content-Type", "image/png");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
// httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setHeader("ENCTYPE", "multipart/form-data");
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if (httpResponse != null) {
Log.d("success", "success:" + httpResponse.toString());
responseString = EntityUtils.toString(httpResponse.getEntity());
} else { // Error, no response.
Log.d("Failed", "failed:" + httpResponse.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return responseString;
}
private byte[] convertToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1) {
bos.write(next);
next = inputStream.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* #param encodedString
* #return bitmap (from given string)
*/
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
}
You shouldn't rotate the image after upload. You need to rotate it before. The preview is correct maybe because you're respecting Exif values when showing it. But the server isn't.
You need to rotate the image according to it's exif rotation:
https://stackoverflow.com/a/20480741/3410697
And only then you should upload it to the server
Call this function where you get path of image
public void setImage(String _path) {
int orientation = CustomImageUtil.getExifOrientation(_path);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
if (orientation == 90) {
bitmap = CustomImageUtil.rotate(bitmap, 90);
} else if (orientation == 180) {
bitmap = CustomImageUtil.rotate(bitmap, 180);
} else if (orientation == 270) {
bitmap = CustomImageUtil.rotate(bitmap, 270);
}
// use your bitmap here
}
CustomImageUtil.class:
public class CustomImageUtil {
public static String getRealPathFromURI(Context context,Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* getExifOrientation -- Roate the image on the right angel
* #param filepath -- path of the file to be rotated
* #return
*/
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2,
(float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {ex.printStackTrace();
}
}
return b;
}
}
To convert Bitmap to Uri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs
In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
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();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File 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());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com