Use of saveStrings

Hi ! I’m very new to processing and java, and for one of my first programs i need to create data file in .txt to store some variables… but when i use the syntax below, in the .txt file i have this :
-2097152
red

… i can’t figure out why the #e00000 (red colour) turned into “-2097152”…

is my code right ? Thanks for help and sorry for bad english :sweat:

here is my code :

String preferences;
final int backgroundcolorreference= #000000;
int backgroundcolor;
String clr;

void setup(){
  size(800,600);
  background(backgroundcolorreference);
}

void draw(){
  if (keyPressed==true){
    if (keyCode==UP){
      backgroundcolor=#ffffff;
      clr="white";
    }
    if (keyCode==DOWN){
      backgroundcolor=#e00000;
      clr="red;
    }
    if (keyCode==LEFT){
      preferences=backgroundcolor+" "+clr;
      String[] tosave = split(preferences," ");
      saveStrings("data/saveddata.txt",tosave);
      exit();
     
    }
    background(backgroundcolor);
  }
}
1 Like

A quotation mark seems to be missing after clr = “red”, but I’m not sure if that’s a copying issue.

Use the hex() function before writing as a string, or else it will get converted to a number (see first example in the reference): https://processing.org/reference/hex_.html

Eg: preferences = hex(backgroundcolor)+...

Also, welcome to the forums :wave:.

3 Likes

Ok ! It actually works ! Thanks :smile:

Hey again ! sorry to ask something again but i can’t figure out how to get the color i saved into “saveddata.txt”

String preferences;
final int backgroundcolorreference= #000000;
int backgroundcolor;
String clr;

void setup(){
  size(800,600);
  background(backgroundcolorreference);
  String[] loaded= loadStrings("data/saveddata.txt");
  // backgroundcolor= and i dont know what to put here
  background(backgroundcolor);
  clr =  loaded[1];
  print(clr," ",backgroundcolor);
}

void draw(){
  if (keyPressed==true){
    if (keyCode==UP){
      backgroundcolor=#ffffff;
      clr="white";
    }
    if (keyCode==DOWN){
      backgroundcolor=#e00000;
      clr="red";
    }
    if (keyCode==LEFT){
      preferences=hex(backgroundcolor)+" "+clr;
      String[] tosave = split(preferences," ");
      saveStrings("data/saveddata.txt",tosave);
      exit();
     
    }
    background(backgroundcolor);
  }
} 

thanks again

1 Like

Being pedantic here: it’s not converted to a number, a Processing color is a number already!

More precisely, a 32-bit (4-byte) int datatype representing the 4 octets ARGB:

Given you’re using hex() in order to convert a color value to its hexadecimal representation as a String before saveStrings():

You’re gonna need to convert it back to a color value after loadStrings(), given Processing can’t use a String in place of a color.

Processing’s API has the very convenient function unhex() for it btW:

println(#FF0000, unhex(hex(#FF0000)) == #FF0000); // -65536 true

4 Likes

Ok ! It works ! thank you man :slight_smile: