Why isn’t my Android app properly saving data to JSON and loading it correctly?

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.

New contributor

Ayman Laghlali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật