Andrew McLaren
Andrew McLaren

Reputation: 45

How to fix file storage path

SO what I am essentially trying to do here is collect information from the user, then collect his/her signature and then attach it to the email.

String pilot, ship, to, from, zone1, zone2, CallSign, agent, date, imgPath;
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_send;
double vesselUnit;
Dialog dialog;
File file;
LinearLayout mContent;
View view;
signature mSignature;
Bitmap bitmap;


File fileDIRECTORY = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  + "/extSdCard" + "/DigitalSign");
String DIRECTORY= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/extSdCard" + "/DigitalSign";
String rootpic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String pic_name = rootpic_name + ".JPEG";
String StoredPath = DIRECTORY + File.separator + rootpic_name + ".JPEG";




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_digital_signature);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        pilot = extras.getString("Pilot");
        ship = extras.getString("ship");
        to = extras.getString("to");
        from = extras.getString("from");
        zone1 = extras.getString("zone1");
        zone2 = extras.getString("zone2");
        CallSign = extras.getString("callsign");
        agent = extras.getString("agent");
        vesselUnit = extras.getDouble("vesselunits");
        date = extras.getString("date");
    }
    // Setting ToolBar as ActionBar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Button to open signature panel
    btn_get_sign = (Button) findViewById(R.id.signature);
    btn_send= (Button) findViewById(R.id.btn_send);
    // Method to create Directory, if the Directory doesn't exists

    dialog = new Dialog(this);
    // Removing the features of Normal Dialogs
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_sig);
    dialog.setCancelable(true);

    btn_get_sign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Function call for Digital Signature
            dialog_action();

        }
    });
    btn_send.setOnClickListener(new OnClickListener() {
        public void onClick(View v){

            Uri upath = Uri.parse("file://" + StoredPath);
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Pilot: "+pilot+"\nShip: "+ship+"\n"+"Destination: "+to+"\n"+"Departure location: "+from+"\n"+"Zone 1: "+zone1+"\n"+"Zone 2: "+zone2+"\n"+"Callsign: "+CallSign+"\n"+"Angent: "+agent+"\n"+"Vessel Units: "+vesselUnit);
            // set the type to 'email'
            emailIntent.setType("image/*");
            String to[] = {"[email protected]"};
            emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
            // the attachment
            emailIntent.putExtra(Intent.EXTRA_STREAM, upath);
            Log.d("TAG","Tagged");
            // the mail subject
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, pilot+"'s Ticket for "+ship);


            startActivity(Intent.createChooser(emailIntent , "Send email..."));
        }
    });
}

// Function for Digital Signature
public void dialog_action() {

    mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
    mSignature = new signature(getApplicationContext(), null);
    mSignature.setBackgroundColor(Color.WHITE);
    // Dynamically generating Layout through java code
    mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    mClear = (Button) dialog.findViewById(R.id.clear);
    mGetSign = (Button) dialog.findViewById(R.id.getsign);
    mGetSign.setEnabled(false);
    mCancel = (Button) dialog.findViewById(R.id.cancel);
    view = mContent;

    mClear.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("tag", "Panel Cleared");
            mSignature.clear();
            mGetSign.setEnabled(false);
        }
    });
    mGetSign.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            Log.v("tag", "Panel Saved");
            view.setDrawingCacheEnabled(true);
            if(isExternalStorageReadable() && isExternalStorageWritable()) {
                file=mSignature.save(view);
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
                // Calling the same class
                recreate();
            }
            else{Toast.makeText(getApplicationContext(), "NOT Saved", Toast.LENGTH_SHORT).show();}
        }
    });
    mCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v("tag", "Panel Cancelled");
            dialog.dismiss();
            // Calling the same class
            recreate();
        }
    });
    dialog.show();
}


public class signature extends View {
    private static final float STROKE_WIDTH = 5f;
    private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
    private Paint paint = new Paint();
    private Path path = new Path();

    private float lastTouchX;
    private float lastTouchY;
    private final RectF dirtyRect = new RectF();

    public signature(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(STROKE_WIDTH);
    }

    public File save(View v) {
        Log.v("tag", "Width: " + v.getWidth());
        Log.v("tag", "Height: " + v.getHeight());
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
        }
        Canvas canvas = new Canvas(bitmap);
        fileDIRECTORY.mkdirs();
        File nfile = new File (fileDIRECTORY,pic_name);
        try {
            // Output the file
            FileOutputStream mFileOutStream  = new FileOutputStream(nfile);
            v.draw(canvas);
            // Convert the output file to Image such as .png
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream);
            mFileOutStream.flush();
            mFileOutStream.close();
            MediaScannerConnection.scanFile(getApplicationContext(), new String[] { nfile.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });


        } catch (Exception e) {
            e.printStackTrace();
        }
        return nfile;
    }

    public void clear() {
        path.reset();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        mGetSign.setEnabled(true);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;

            case MotionEvent.ACTION_MOVE:

            case MotionEvent.ACTION_UP:
                resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++) {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;
            default:
                debug("Ignored touch event: " + event.toString());
                return false;
        }

        invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

        lastTouchX = eventX;
        lastTouchY = eventY;

        return true;
    }

    private void debug(String string) {
        Log.v("log_tag", string);
    }

    private void expandDirtyRect(float historicalX, float historicalY) {
        if (historicalX < dirtyRect.left) {
            dirtyRect.left = historicalX;
        } else if (historicalX > dirtyRect.right) {
            dirtyRect.right = historicalX;
        }

        if (historicalY < dirtyRect.top) {
            dirtyRect.top = historicalY;
        } else if (historicalY > dirtyRect.bottom) {
            dirtyRect.bottom = historicalY;
        }
    }

    private void resetDirtyRect(float eventX, float eventY) {
        dirtyRect.left = Math.min(lastTouchX, eventX);
        dirtyRect.right = Math.max(lastTouchX, eventX);
        dirtyRect.top = Math.min(lastTouchY, eventY);
        dirtyRect.bottom = Math.max(lastTouchY, eventY);
    }
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state))
    {
        Log.d("TRACE","ISWRITEABLE");
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
    {
        Log.d("TRACE","ISREADABLE");
        return true;
    }
    return false;
}
public static void addImageToGallery(final String filePath, final Context context) {

    ContentValues values = new ContentValues();

    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, filePath);
    try{
        context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
    }catch(Exception e){
        Log.d("TAG","Not Saved in gallery");
    }

}

}

So I have created the directory but the picture is not attaching and not showing up in the file directory. I'm not seeing where my issue arising from but I definitely know hat the picture is either not being processed or not being saved properly in file.

Upvotes: 0

Views: 595

Answers (2)

Rohit Singh
Rohit Singh

Reputation: 18222

I would suggest you to first understand the android storage model.
There is a lot of confusion when we talk about internal and external storage in android. This is mainly because.

WHAT WE THINK:

Our understanding of external storage is SD CARD which is not quite right.

WHAT Android SDK THINKS :

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

Here is a good source to read more on Internal Storage and External Storage

EDIT : Try not to hard-code path when you are developing an app for multiple manufacturers because it varies from one manufacturer to another.

Upvotes: 1

Android Geek
Android Geek

Reputation: 9225

Change your path directory to

File DIRECTORY = new File(Environment.getExternalStorageDirectory()
                    .getParent() + "/extSdCard" + "/DigitalSign");

Log

/storage/emulated/extSdCard/DigitalSign

Upvotes: 0

Related Questions