How to save data in a program

I forgot to say that you must enable the permission. Simply go on the 3 points in the top right corner → Sketch Properties → Sketch Permissions and then check WRITE_EXTERNAL_STORAGE.

Here is an example:

boolean maySaveData;

int count = 0;
String countFilePath;

void setup() {
  fullScreen();
  
  countFilePath = dataPath("count.txt");
  
  checkPermission();
  loadAndRequestCount();
}
void loadAndRequestCount() {
  if(maySaveData) {
    checkFileExists(countFilePath, "saveCount");
    loadCount();
  }else{
    requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    checkPermission();
  }
}
void checkPermission() {
  maySaveData = hasPermission("android.permission.WRITE_EXTERNAL_STORAGE");
}
void checkFileExists(String path, String callback) {
  File file = new File(path);
  if(!file.exists())
    method(callback);
}
void saveCount() {
  saveStrings(countFilePath, new String[]{str(count)});
}
int loadCount() {
  count = int(loadStrings(countFilePath)[0]);
  return count;
}

void draw() {
  background(255);
  textAlign(CENTER, CENTER);
  if(maySaveData) {
    textSize(100);
    fill(#000000);
    text(count, width/2, height/2);
  }else{
    textSize(30);
    fill(#FF0000);
    text("Please give permission to save data.\nOtherwise the program can't run correctly.\nPress to request again.", width/2, height/2);
    
    checkPermission();
  }
}

void mousePressed() {
  if(maySaveData) {
    count++;
    saveCount();
  }else
    loadAndRequestCount();
}

This code is realy advanced so if you have any qeustions yust ask.
Hope that helps :grin:

1 Like