2

Can i make my own folder to saving picture taken by camera. I have make it in my code and the picture save to sdcard0, but the name is always temp and if i take other picture it's doesn't work. can someone help me with this.

here my MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

private EditText nama, harga, kondisi, notelepon;

private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    nama = (EditText)findViewById(R.id.nama_barang);
    harga = (EditText)findViewById(R.id.harga_barang);
    kondisi = (EditText)findViewById(R.id.kondisi_barang);
    notelepon = (EditText)findViewById(R.id.no_telepon);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);
    btnselectpic = (Button)findViewById(R.id.button_selectpic);
    imageview = (ImageView)findViewById(R.id.imageView_pic);


    btnselectpic.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    upLoadServerUri = "http://192.168.43.226/jualan/barang_tes/UploadToServer.php";
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds options to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public void onClick(View arg0) {

    if(arg0==btnselectpic)
    {
        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    imagepath = f.getAbsolutePath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);

                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);

                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();


    }
    else if (arg0==uploadButton) {

         dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
         messageText.setText("uploading started.....");
         new Thread(new Runnable() {

             public void run() {

                  uploadFile(imagepath);
                  //send();

             }
           }).start();     
    }

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

     if (resultCode == RESULT_OK) {
        if (requestCode == 1) {

            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                // bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
                imageview.setImageBitmap(bitmap);


                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            imagepath = getPath(selectedImage);
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            //Log.w("path of image from gallery......******************.........", picturePath+"");
            imageview.setImageBitmap(thumbnail);
            messageText.setText("Uploading file path:" +imagepath);
        }
    }
}

     public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }


public int uploadFile(String sourceFileUri) {

      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"+imagepath);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"+ imagepath);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);
               String nm = nama.getText().toString();
               String hrg = harga.getText().toString();
               String knds = kondisi.getText().toString();
               String notlp = notelepon.getText().toString();
               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("uploaded_file", fileName);
               conn.setRequestProperty("uploaded_nama", nm);
               conn.setRequestProperty("uploaded_harga", hrg);
               conn.setRequestProperty("uploaded_kondisi", knds);
               conn.setRequestProperty("uploaded_notelepon", notlp);

               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_nama" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(nm); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_harga" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(hrg); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_kondisi" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(knds); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=uploaded_notelepon" + lineEnd); // name=uploaded_nama so you have to get PHP side using mobile_no
               dos.writeBytes(lineEnd);
               dos.writeBytes(notlp); // nm is String variable
               dos.writeBytes(lineEnd);

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                         + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);


               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.i("uploadFile", "HTTP Response is : " 
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" C:/AppServ/www/kambing/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                            //Intent i = new Intent(MainActivity.this,InputInfo.class);
                            finish();
                            //startActivity(i); 
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          }

           catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     }


 }
Don
  • 25
  • 1
  • 6
  • Can you please explain your question further? What part of the code does not work? What does? Can you add comments in your code snippet that point to the part with the issue? Or at least describe what each function should be doing? It will greatly help to understand where the problem is. – Tom Klino Aug 24 '14 at 18:16
  • @Tom my code is working. But i need to make my own folder for saving picture taken by camera. I have no idea to do it. can you help me? – Don Aug 24 '14 at 18:19
  • @Don see my answer for how to create folder – Jamil Aug 24 '14 at 20:48
  • @SoftCoder can you tell me how to implement it in my code? – Don Aug 24 '14 at 20:55

3 Answers3

0

Use the following method to create or fetch (in case it already exists) your directory: (taken from http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage)

private File getAlbumStorageDir(Context context, String albumName) {
    // Get the directory for the app's private pictures directory. 
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e("MainActivity.error", "Directory not created");
    }
    return file;
}

And the following method to implement file copy: (from: How to make a copy of a file in android?)

private void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

And finally, in your onActivityResult method, use the following lines of code to copy the temporary file from your camera to a more permanant location:

File picturesDir = getAlbumStorageDir(this, "myDirName");
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic.jpg");
try {
    copy(temp, savedPic);
} catch (IOException e) {
    Log.e("MainActivity.err", "failed to copy");
}

PS: Another tip. It seems that in order to obtain the picture taken from the camera, you are iterating over all the pictures in the pictures directory to find the one named temp.jpg. This is a very bad way of doing things, as it might be very slow when the directory has a lot pictures in it, and even worse, on future versions (or older) of android, the name of the file may not be temp or not be in that folder. Instead, follow the answer in this question for the correct and more efficient way to obtain the path of the temporary picture: Android How can I call Camera or Gallery Intent Together

Community
  • 1
  • 1
Tom Klino
  • 2,358
  • 5
  • 35
  • 60
  • I'm pretty sure you can just copy past the 2 upper code snippets as private methods in your `MainActivity`, and the 3rd one right under the for loop in your `onActivityResponse`. Altough, see the PS in my answer regarding that for loop. – Tom Klino Aug 24 '14 at 23:12
  • In a second look, you might need to change the variables names I used to fit the one you use. I think my `temp` should be your `f` – Tom Klino Aug 24 '14 at 23:14
0

How to Make folder

 // make a folder with name PicturesNR2
 String RootDir = Environment.getExternalStorageDirectory() + File.separator + "PicturesNR2";

 File RootFile = new File(RootDir);

 RootFile.mkdir();

how to retrieve file

 // here picname is with extension
 File imageFile = new File("/sdcard/PicturesNR2/"+picname);
 Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

also add in your Manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Edit: as you want to implement it in your code here is it below

First make a method in your class

 public void createFolder()
      {
          // here PictureFolder is the folder name you can change it offcourse
          String RootDir = Environment.getExternalStorageDirectory()
                  + File.separator + "PictureFolder";
          File RootFile = new File(RootDir);
          RootFile.mkdir();
      }

then in your code on Activity Result method which is

 if (resultCode == RESULT_OK) {
        if (requestCode == 1) {

            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                // bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
                imageview.setImageBitmap(bitmap);


                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

change this to this

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
            if (requestCode == 1 && resultCode == RESULT_OK) { 

                // create folder first
                createFolder();

                // get the photo from intent
                Bitmap photo = (Bitmap) data.getExtras().get("data"); 

                // set the bitmap to imageview
                imageview.setImageBitmap(photo);

                // this code is use to generate random number and add to file
                // name so that each file should be different 
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".jpg";

                // set the file path
                // sdcard/PictureFolder/ is the folder created in create folder method
                String filePath = "/sdcard/PictureFolder/"+fname;

                // the rest of the code is for saving the file to filepath mentioned above
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(filePath);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

                //choose another format if PNG doesn't suit you
                photo.compress(CompressFormat.PNG, 100, bos);

                try {
                    bos.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }  else if (requestCode == 2) {.........

i have tested this code on my phone and it work good

Jamil
  • 5,457
  • 4
  • 26
  • 29
  • I have edited my answer.. forget to add imageview.setImageBitmap(photo); now it is added :) – Jamil Aug 24 '14 at 21:38
-1

If you want to store your pictures in the pictures directory of your sdcard, do this:

private static File createPictureDirectory()
{
    File sdDirectory = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

    return new File(sdDirectory, "mypictures");
}

That will create and return your folder named mypictures and you can then store your photos there by writing to it. Always remember to request write permissions in your android manifest file before storing your photos.

I hope this helps.

Eenvincible
  • 5,641
  • 2
  • 27
  • 46