0

I am facing an issue which I do not understand. I am taking a picture then creating a PNG image file as per code that follows but somewhere down the line a random string is being added to the filename which causes me all sorts of issues. For example (as per tutorials I have found): I create an image called dimage_(generated timestamp) and save the string to shared preferences and the image in getExternalFilesDir(Environment.DIRECTORY_PICTURES). In shared preferences the string is correct but the file has the above mentioned string appended.

Eg: The generated filename string saved in shared prefs:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="driver_picture">dimage_20190610_065509</string>
</map>

Whereas the file checked with adb results as:

127|generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files/Pictures $ ls

dimage_20190610_0655091215099619.png

generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files    /Pictures $

I have no clue where the 1215099619 extra part comes from!

This is the code of the activity:

package africa.mykagovehicledrivers;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class RegisterDriverImage extends AppCompatActivity {

    String currentPhotoPath;
    final int REQUEST_TAKE_PHOTO = 1;
    final int CAMERA_PERMISSIONS = 3;
    Activity activity = this;

    ImageView imgTakePicture, imgDriver;
    Button btnContinueDriver;
    ProgressBar prgImage;
    SharedPreferences prefs;
    SharedPreferences.Editor edit;
    String imageFileName;
    Tools t;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // All good so launch take picture from here
                dispatchTakePictureIntent();
            } else {
                // Permission denied. Warn the user and kick out of app
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.permsDeniedCameraTitle);
                builder.setMessage(R.string.permsDeniedCameraMessage);
                builder.setCancelable(false);
                builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finishAffinity();
                    }
                });
                builder.create().show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            Uri starturi = Uri.fromFile(new File(currentPhotoPath));
            Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
            UCrop.Options options = AppConstants.setUcropOptions(activity);
            UCrop.of(starturi, destinationuri).withOptions(options).start(activity);
        }

        // On result from cropper add to image view

        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            prgImage.setVisibility(View.VISIBLE);
            final Uri resultUri = UCrop.getOutput(data);
            assert resultUri != null;
            File imgFile = new File(resultUri.getPath());
            Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
            builder.listener(new Picasso.Listener() {
                @Override
                public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                    exception.printStackTrace();
                }
            });
            builder.build().load(imgFile).into(imgDriver, new Callback() {
                @Override
                public void onSuccess() {
                    Log.d("-------->", "onSuccess: CROPPED!");
                    prgImage.setVisibility(View.INVISIBLE);
                    btnContinueDriver.setEnabled(true);
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_driver_image);

        prefs = getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
        edit  = prefs.edit();
        imgTakePicture = findViewById(R.id.imgTakePicture);
        imgDriver = findViewById(R.id.imgDriver);
        btnContinueDriver = findViewById(R.id.btnContinueDriver);
        prgImage = findViewById(R.id.prgImage);

        t = new Tools(getApplication(), getApplicationContext(), this);

        imgTakePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();
            }
        });

        imgDriver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();
            }
        });

        btnContinueDriver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit.putString("driver_picture", imageFileName);
                edit.putString("nextstep", "drivinglicense");
                edit.apply();
                Intent drivinglicense = new Intent(getApplicationContext(), RegisterDrivingLicense.class);
                startActivity(drivinglicense);
                finish();
            }
        });

        // Always ask for camera permissions
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA }, CAMERA_PERMISSIONS);
        }
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                Log.d("IMAGE CREATION FAILED", ex.toString());
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "africa.mykagovehicledrivers.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        imageFileName = "dimage_" + timeStamp;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".png",
                storageDir
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }
}

As per code I am using String imageFileName; to save the path and then use it in the button click action to save it into shared preferences.

Thanks!

2
  • Basically, it does this because that is how it is designed / specified to work: see the javadoc A temp file is one whose name is unlikely to be the same as another temp file. Commented Jun 10, 2019 at 9:35
  • Yes indeed, just found out. Thanks for the info. Commented Jun 10, 2019 at 9:35

1 Answer 1

0

Found out the reasin. createTempFile does this. Switched to new File() and this solved the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.