Change the name of the stored images
Hi I'm making an application in which I make photos with an application of a camera that I created, and then I store these images in a particular folder (PFC_Gallery). The problem that I have is that I don't know how to change the name of the images that I store withot overwriting the previous ones. I tried with a variable imgCounter, that increments every time that I make a photo as you can see in the code below, but when I close the app, this variable restarts 开发者_StackOverflow社区again from 0 and I overwrite the other photos. If somebody knows any solution to this it will be really helpful.
public static int imgCounter = 0;
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File path = Environment
.getExternalStoragePublicDirectory(("PFC_Gallery"));
File file = new File(path, "IMG" + imgCounter + ".jpg");
imgCounter++;
try {
path.mkdirs();
OutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
You can set a Shared Preference to maintain your image counter.
Sounds like an ideal situation for storing the last number in a preference file on closing the application.
In oncreate you load the last number from the settings file
SharedPreferences settings = getSharedPreferences("settings", 0);
int n = settings.getInteger("lastNumber", 0);
and in onStop
SharedPreferences settings = getSharedPreferences("settings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInteger("lastNumber", n);
// Commit the edits!
editor.commit();
for more info: http://developer.android.com/guide/topics/data/data-storage.html#pref
Save the imgCounter
variable as a preference and load it when you start the activity.
精彩评论