theuses
theuses

Reputation: 294

Writing and reading JSON with Libgdx

Very confused with JsonBeans from Libgdx. Trying to save & load game progress to local storage. Initializing file:

file=Gdx.files.local(FILENAME);

Reading json:

if (file.exists()) {
        JsonReader jsonReader = new JsonReader();
        JsonValue jv = jsonReader.parse(file.reader());
        levels = jv.getInt(LEVELS, 1);
}

App dies with NullPointerException at levels = jv.getInt(LEVELS, 1); (jv is null).

But writing doesn't work too, output file is empty:

Json json=new Json(JsonWriter.OutputType.json);
json.setWriter(file.writer(true));
json.writeObjectStart();
json.writeValue(LEVELS, levels);
json.writeObjectEnd();

Any suggestions? Thanks in advance.

Upvotes: 1

Views: 1341

Answers (2)

theuses
theuses

Reputation: 294

Goddamn, tutorial at Libgdx wiki is extremely uninformative. First of all never mentioned what you need to set Writer to Json instance, secondly after reading the feeling remains that all the work on recording json on disc was done by Json class but it isnt. You need to do this by yourself:

file.writeString(json.prettyPrint(progress), false);

After that all worked. Thanks everyone.

Upvotes: 1

Deniz Yılmaz
Deniz Yılmaz

Reputation: 1094

Try Gdx.files.internal instead of Gdx.files.local because you may not have permissions to write to and read from local storage.

For desktop run as administrator (i think its enough)

For android add write/read permissions to android manifest.

Upvotes: 1

Related Questions