-1

I have latlng list of geopoints

  ArrayList<Route> arrayList

I am saving this by

 SharedPreferences prefeMain = MainActivitybatchGrp1.this.getSharedPreferences("APPLICATION", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefeMain.edit();

    try {
        Log.e("TASK","Success");
        editor.putString("GROUPA", ObjectSerializer.serialize(arrayListLatLong));
    } catch (IOException e) {
        Log.e("TASK","Fail:: "+e);
        e.printStackTrace();
    }
    editor.commit();

But it gives an IOException

java.io.NotSerializableException: com.directions.route.Route
Arjun saini
  • 4,223
  • 3
  • 23
  • 51

1 Answers1

1

If a class does not implement java.io.Serializable (like what you have in your case) you can convert it to JSON and store the JSON on the SharedPreferences.

Of course you will also need to deserialize the JSON string from the SharedPreferences.

Here is an example for serialization / de-serialization with the popular GSON library:

import com.google.gson.Gson;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class GsonTest {

    private static class Test1213 {

        public Test1213(String name) {
            this.name = name;
        }

        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    @Test
    void testConversion() throws IOException {
        Gson gson = new Gson();
        Test1213 john_doe1 = new Test1213("John Doe");
        String john_doe = gson.toJson(john_doe1);
        System.out.println(john_doe);
        Test1213 test1213 = gson.fromJson(john_doe, Test1213.class);
        assertThat(john_doe1.getName(), is(test1213.getName()));
    }
}

This test serializes to JSON and back.

This is the serialized JSON:

{"name":"John Doe"}
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76