Pergunta

i am using custom camera to capture images and saving into sd card using datetime, like below:

// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
return mediaFile;

But i have to make a small change in file name, like existing name looks like below:

IMG_20140312_162137.jpg

Now i want whenever user start capturing images, need to start counting from 001,

for an example for 1 image IMG_20140312_001.jpg, for 2 image IMG_20140312_002.jpg and so on.

Foi útil?

Solução

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + getNextNumber() +".jpg");
return mediaFile;




public String getNextNumber(){
    SharedPreferences prefs = this.getSharedPreferences(
          "com.example.app", Context.MODE_PRIVATE);

    int default = 0;


    int value = prefs.getInt("PICTURE_COUNT", default); 
    prefs.edit().putInt("PICTURE_COUNT", ++value).commit();
    return convertToDesiredFormat(value);
}

String convertToDesiredFormat(int value){
      String toReturn = null;
      if (value > 99)
         toReturn = Integer.toString(value);
      else if (value > 9)
         toReturn = "0" + Integer.toString(value);
      else if (value >= 0)
         toReturn = "00" + Integer.toString(value);
      return toReturn;
}

Outras dicas

then store the image count in one share preference and count increase as u click any no of picture and then again update share preference for next time simple because if u clear your app from stack then next time this count is have to start from last that why we use share preference

Append one counter at the end of your image name as below :

 int count=0;
 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp +" _00 "+ count +".jpg");
     count++;

    return mediaFile;

For this you will need to keep the track of the counter with shared preference when your application reopens

SharedPreferences pref;

    SharedPreferences.Editor edit;

        pref = context.getSharedPreferences("counter", 
                Context.MODE_PRIVATE);
        edit = pref.edit();

edit.putInt("count" ,count++);
edit.commit();


and the get the count when next time you use the count

mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp +pref.getString("count", 0))+ ".jpg");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top