2014-02-07 107 views
1

我絕對需要這個幫助!我的問題是,我無法找到如何獲得上次拍照的Uri。當我從圖庫中選擇照片時,我可以上傳照片,但其他功能缺失。照相機啓動後,照片拍攝後,它被保存在畫廊,但不知何故,我找不到最後拍攝的照片的URI。請幫忙!如何獲取上次拍攝的照片的文件名/ uri?

問候,

哈比卜

public class MainActivity extends Activity { 

    private final int SELECT_FILE = 1; 
    private final int REQUEST_CAMERA = 0; 
    private ImageView ivImage; 
    private Button btnSetImage; 
    TextView tv; 
    int serverResponseCode = 0; 
    ProgressDialog dialog = null; 

    File f = new File(Environment.getExternalStorageDirectory().toString()); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     ivImage = (ImageView) findViewById(R.id.ivImage); 
     btnSetImage = (Button) findViewById(R.id.btnSelectPhoto); 
     btnSetImage.setOnClickListener(onClickListener); 
     tv = (TextView) findViewById(R.id.tv); 

    } 

    private OnClickListener onClickListener = new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      selectImage(); 
     } 
    }; 

    public int uploadFile(String sourceFileUri) { 
     String upLoadServerUri = "...upload.php"; 
     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()) { 
      Log.e("uploadFile", "Source File Does not exist"); 
      return 0; 
     } 
     try { // open a URL connection to the Server 
      FileInputStream fileInputStream = new FileInputStream(sourceFile); 
      URL url = new URL(upLoadServerUri); 
      conn = (HttpURLConnection) url.openConnection(); // Open a HTTP 
                   // connection to 
                   // the URL 
      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); 
      dos = new DataOutputStream(conn.getOutputStream()); 

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

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

      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() { 
         tv.setText("File Upload Completed."); 
         Toast.makeText(MainActivity.this, 
           "File Upload Complete.", Toast.LENGTH_SHORT) 
           .show(); 
        } 
       }); 
      } 

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

     } catch (MalformedURLException ex) { 
      dialog.dismiss(); 
      ex.printStackTrace(); 
      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(); 
      Toast.makeText(MainActivity.this, "Exception : " + e.getMessage(), 
        Toast.LENGTH_SHORT).show(); 
      Log.e("Upload file to server Exception", 
        "Exception : " + e.getMessage(), e); 
     } 
     dialog.dismiss(); 
     return serverResponseCode; 
    } 

    private void selectImage() { 
     final CharSequence[] items = { "Take Photo", "Choose from Library", 
       "Cancel" }; 

     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
     builder.setTitle("Add Photo!"); 
     builder.setItems(items, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int item) { 
       if (items[item].equals("Take Photo")) { 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        File f = new File(android.os.Environment 
          .getExternalStorageDirectory(), "temp.jpg"); 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
        startActivityForResult(intent, REQUEST_CAMERA); 
       } else if (items[item].equals("Choose from Library")) { 
        Intent intent = new Intent(
          Intent.ACTION_PICK, 
          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        intent.setType("image/*"); 
        startActivityForResult(
          Intent.createChooser(intent, "Select File"), 
          SELECT_FILE); 
       } else if (items[item].equals("Cancel")) { 
        dialog.dismiss(); 
       } 
      } 
     }); 
     builder.show(); 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_OK) { 
      if (requestCode == REQUEST_CAMERA) { 
       File f = new File(Environment.getExternalStorageDirectory() 
         .toString()); 
       for (File temp : f.listFiles()) { 
        if (temp.getName().equals("temp.jpg")) { 
         f = temp; 
         break; 
        } 
       } 
       try { 
        Bitmap bm; 
        BitmapFactory.Options btmapOptions = new BitmapFactory.Options(); 

        bm = BitmapFactory.decodeFile(f.getAbsolutePath(), 
          btmapOptions); 

        // bm = Bitmap.createScaledBitmap(bm, 70, 70, true); 
        ivImage.setImageBitmap(bm); 

        String path = android.os.Environment 
          .getExternalStorageDirectory() 
          + File.separator 
          + "Phoenix" + File.separator + "default"; 
        f.delete(); 
        OutputStream fOut = null; 
        final File file = new File(path, String.valueOf(System 
          .currentTimeMillis()) + ".jpg"); 

        try { 
         fOut = new FileOutputStream(file); 
         bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut); 
         fOut.flush(); 
         fOut.close(); 
        } catch (FileNotFoundException e) { 
         e.printStackTrace(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

      } else if (requestCode == SELECT_FILE) { 
       Uri selectedImageUri = data.getData(); 

       final String tempPath = getPath(selectedImageUri, 
         MainActivity.this); 
       Bitmap bm; 
       BitmapFactory.Options btmapOptions = new BitmapFactory.Options(); 
       bm = BitmapFactory.decodeFile(tempPath, btmapOptions); 
       ivImage.setImageBitmap(bm); 

       dialog = ProgressDialog.show(MainActivity.this, "", 
         "Uploading file...", true); 
       new Thread(new Runnable() { 
        public void run() { 
         runOnUiThread(new Runnable() { 
          public void run() { 
           tv.setText("uploading started....."); 
          } 
         }); 

         int response = uploadFile(tempPath); 
         System.out.println("RES : " + response); 
        } 
       }).start(); 
      } 
     } 
    } 

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

} 
+0

我認爲這可能是重複的看到這個: http://stackoverflow.com/questions/10238846/android-how-do-i-get-the-uri-of-the-latest-file-saved-由這系統 – CubanAzcuy

回答

1

您可以使用此作爲路徑/文件,其中尋找最新的照片相機存儲照片代替。

Uri.fromFile(f)

相機意圖存儲圖像到你通過它的位置。因此,可能會將圖像的路徑存儲在活動中,因爲它是您傳遞的臨時路徑。並使用on activity結果方法來訪問文件。