How to save data in a program

Hello

I have been making a game and I wanted to know how you can save data in a game. For example you earned 10 points and when you close the app and reopen it, your progress will not be reset but the 10 points will stay.

1 Like

Hello,

Take a look here:
https://processing.org/reference#output

Experiment a little.

I was able to do this with saveStrings() and loadStrings()

This code is not complete:

String [] saved;
int score;

void setup()
  {
  size(200, 200);
  //loadStrings()
  }

void draw()
  {
  }

void keyPressed()
  {
  score++;
  println(score);
  }

void mousePressed()
  {
  //saveStrings();
  }

I was able to store and recall a score with that basic template and a file to save these.
There is code missing.

:)

Thank you. Do you also know how to add data from the programm into the txt file?

Did you have a chance to read up about saveStrings()?

Thank you. Do you also know how to create a new txt file in the programm code?

1 Like

Hi

  • You can either use saveStrings() again and write over the existing file (when you load it, add data and save it with the same name, it’s like append data to the existing file, like for a high score)

  • But you can also generate a new text file. For example just incrementing a number (so file name is myfile1.txt, myfile2.txt…). Or using a file name that is built from date and current time (when you save only once per second maximum).

  • There is also a full Save as… dialogue in processing. Here you can enter a file name (like when you save a Sketch in processing).

See reference for all commands.


date time stamp for file name

  // make date time stamp (the expression nf(n,2) means leading zero: 2 becomes 02)
  String dateTimeStamp = year() 
    + nf(month(), 2) 
    + nf(day(), 2) 
    + "-" 
    + nf(hour(), 2)
    + nf(minute(), 2)
    + nf(second(), 2)
    +".txt";

Save as… dialogue

see selectOutput() in reference : Reference / Processing.org

it’s Reference / Processing.org

Thank you for the help. Maybe I have forgotten to choose the topic processing for android so it is my fault I apologize. If you know if it works on Android too, it would be great but if you dont then its okay too. Because for some reason it doesn’t work on Android. I get no error but the file doesnt change.

1 Like

Hi

Hi

This example from APDE I just changed the path

String[] lines;
int index = 0;
String filepath = "/storage/emulated/0/test/positions.txt/";
void setup() {
  size(800, 800);
  background(0);
  stroke(255);
  frameRate(12);
  lines =  loadStrings(filepath);

    
}

void draw() {
  if (index < lines.length) {
    String[] pieces = split(lines[index], '\t');
    if (pieces.length == 2) {
      int x = int(pieces[0]) * 2;
      int y = int(pieces[1]) * 2;
      point(x, y);
    }
    // Go to the next line for the next run through draw()
    index = index + 1;
  }
}

Read this

Hello

It says the error that it contains a path separator

Firstly, your program needs to be converted into an app. If you run it in Notepad, Processing will automatically delete all old files. Second: With Android, apps first have to be authorized to save something. You can use hasPermission(permissionName) to test whether your app has the permission. With requestPermission(permissionName) you can request permissions. The name of the permission to store data is android.permission.WRITE_EXTERNAL_STORAGE.

2 Likes

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

*Small note:
I think if you store your files in the dataPath (e.g. dataPath("count.txt")) you don’t need to request permission, but I don’t know if some Android devices let you store data only then , if you request this, so do it to be safe.

Thank you. For me it doesn’t work right. When I start the App then it doesn’t start asking permission and if the permission is already enabled then I get the error “OutOfBoundsException”. But it does work when I replace the filename with something else that doesnt exist. I hope you can help me.

1 Like

An OutOfBoundsException can only occur if the file is empty. This would also explain why it worked with a different filename (because a new file was created that is not empty). I will change the code again so that this exception cannot be thrown again.

1 Like

Try this:

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);
  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();
}

Thanks. But for some reason I dont get the request to access the write external storage thing anymore

1 Like

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

Or this would be a better link