How to make the photos taken from the camera be stored in /DCIM/Camera/ under the names obtained as image_i , where i are consecutive natural numbers (image_1, image_2, image_3, etc.).

Here is my code:

 int n = 0; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button buttonCheck = (Button)findViewById(R.id.mainButton); buttonCheck.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ File imagesFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera/"); File image = new File(imagesFolder, "image_" + n +".jpg"); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uriSavedImage = Uri.fromFile(image); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); startActivityForResult(cameraIntent, 1112); if(image.exists()){ n++; image = new File(imagesFolder, "image_" + n + ".jpg"); cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); uriSavedImage = Uri.fromFile(image); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); startActivityForResult(cameraIntent, 1112); } } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); Intent intent = new Intent(MainActivity.this, Result.class); startActivity(intent); } 

In the code, the variable n is a counter. The problem is that when you return from the camera activity to the main one, the counter is reset, and the new image file replaces the old one created.

  • Do you know the answer yourself? - Nikitos
  • If necessary within one application launch, make n static. If you just need to form files in this format, loop through n and check that a file with that name does not exist. If you need to find a file with the maximum n and create a file with n+1 - loop through all the files with the appropriate format, find the maximum n , etc. The problem is what? - zRrr
  • You can write the value n to a text file, and then read it. Since when the application is restarted, the value of n reset - Nikito's

1 answer 1

Usually time is used to save the photo in the title. In fact, it is always unique.

 String currentTime = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()); File image = new File(imagesFolder, "image_" + currentTime +".jpg"); 
  • If it is necessary in the image_i format, where i are consecutive positive integers, you can also use time, but not a formatted representation, but as “image_” + System.currentTimeMillis () - Chubatiy