I am reaching out to seek your assistance regarding a persistent issue I am experiencing with my Android application (using Android Studio). In my application, I am using a HashMap to store groups and their contents, which I then serialize to JSON for storage. However, the data is not persisting between sessions, and the structure of the JSON output appears to be incorrect. This is causing problems when I attempt to load the data back into the app.
Somebody has maybe a solution to save the last changes on the App.
Below are the relevant code snippets from my project:
class Datenspeicher {
public static void speichern(HashMap<String, ArrayList> daten, String dateiname) throws JSONException {
JSONObject json = new JSONObject();
for (String key : daten.keySet()) {
json.put(key, daten.get(key));
}
try (FileWriter file = new FileWriter(dateiname)) {
file.write(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static HashMap<String, ArrayList<Object>> laden(String dateiname) {
HashMap<String, ArrayList<Object>> geladeneDaten = new HashMap<>();
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(dateiname))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONArray jsonArray = json.getJSONArray(key);
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i));
}
geladeneDaten.put(key, list);
}
} catch (IOException | JSONException e) {
e.getMessage();
}
return geladeneDaten;
}
}
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding // Binding to access the main layout
lateinit var groupListView: ListView // ListView to display groups
lateinit var addButton: FloatingActionButton // Floating action button to add items
lateinit var groupItems: ArrayList<Any> // List to store groups
lateinit var itemAdapter: ButtonArrayAdapter // Adapter for ListView
lateinit var hashGroups: HashMap<String, ArrayList<Any>> // HashMap to store groups and their contents
lateinit var ListQueue: ArrayList<ArrayList<Any>> // List queue for managing navigation
/**
* Called when the activity is first created. Initializes the activity.
*
* @param savedInstanceState If the activity is being re-initialized after previously being shut down,
* this contains the data it most recently supplied.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
init()
groupListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _, _, pos, _ ->
longClickFunction(pos)
true // Return true to signal that the event has been handled
}
addButton.setOnClickListener {
AddingButton()
}
}
private fun load(){
hashGroups = Datenspeicher.laden("JSON_AppStorage");
}
/**
* Initializes the variables and sets up the initial state of the activity.
*/
private fun init(){
groupListView = findViewById(R.id.GroupList)
addButton = findViewById(R.id.floatingActionButton)
groupItems = ArrayList()
ListQueue = ArrayList()
ListQueue.add(groupItems)
itemAdapter = ButtonArrayAdapter(this, ListQueue[0], this)
groupListView.adapter = itemAdapter
load();
}
/**
* Handles the back button press. If there are multiple lists in the queue,
* it navigates to the previous list. Otherwise, it performs the default back press action.
*/
override fun onBackPressed() {
Datenspeicher.speichern(hashGroups, "JSON_AppStorage");
if(Vsize() > 1) {
ListQueue.removeAt(Vsize()-1)
itemAdapter = ButtonArrayAdapter(this, ListQueue[Vsize()-1], this)
itemAdapter.notifyDataSetChanged()
groupListView.adapter = itemAdapter
} else {
super.onBackPressed()
}
}
Data Persistence:
I have implemented a method Datenspeicher.speichern(hashGroups, “JSON_AppStorage”) in the onBackPressed() method to save the data when the back button is pressed.
I also call a load() method during initialization to load the data from storage. Despite these efforts, the data does not seem to persist between app sessions.
JSON Structure:
I am using a HashMap<String, ArrayList> to store groups and their contents.
When serializing this map to JSON and later deserializing it, the JSON output does not reflect the expected structure. This mismatch causes issues when reloading the data into the app.
What I Expected
Data Persistence:
I expected the data to persist between app sessions. This means that any groups or items added should be saved when the app is closed and should be available again when the app is reopened.
JSON Structure:
I expected the JSON output to accurately reflect the structure of my HashMap, so that deserializing it would correctly restore the data into the same structure as before.
Ayman Laghlali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.