How to save data in a program

Hi

Permission given just once and requested just once @TimeLex sketch is working you have to select your path

boolean maySaveData;

int count = 0;
String countFilePath;

void setup() {
  fullScreen();
  
 
 countFilePath  = "/storage/emulated/0/conunt.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);
  else if(loadStrings(path).length == 0)
    saveCount();
}
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();
}



1 Like