1

При попытке сеарилизовать поле типа LocalDate - теряется его значение. В чём проблема?

    package com.example.myapplication;
    
    import android.content.SharedPreferences;
    import android.os.Build;
    import android.os.Bundle;
    
    import com.google.android.material.floatingactionbutton.FloatingActionButton;
    import com.google.android.material.snackbar.Snackbar;
    
    import androidx.annotation.RequiresApi;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    
    import android.view.View;
    import com.google.gson.Gson;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import java.time.LocalDate;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            FloatingActionButton fab = findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings)
            {
                LocalDate localDate = LocalDate.now();
                Gson gson = new Gson();
                SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferences123", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                String json = gson.toJson(gson.toJson(localDate));
                editor.putString("MyCounting", json);
                editor.apply();
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
2
  • Как вы определили что значение теряется? Выведите хотя бы в лог полученную строку: Log.d("TAG", "JSON: " + json); Подозреваю что проблема вовсе не в сериализации.
    – woesss
    19 апр 2021 в 12:24
  • Точка останова) 19 апр 2021 в 15:44

2 ответа 2

1

Попробуйте сохранить дату в численом представлении

val time = localDate.toEpochDay()

Запишите long

editor.putLong("MyTime", time);

Воссоздать дату очень легко

val date = LocalDate.ofEpochDay(time)

Для сериализации LocalDate нужна конвертация

1
Переработал функции следующим образом:
if(id == R.id.action_SaveCountingEntries)
        {
            if(!countingEntries.isEmpty())
            {
                ArrayList<SaveDataObject> saveDataObjects = new ArrayList<SaveDataObject>();
                SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesForArrayList<CountingEntries>", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                Gson gson = new Gson();
                for(int i = 0; i < countingEntries.size(); i++)
                {
                    saveDataObjects.add(new SaveDataObject(countingEntries.get(i).GetPurchase(),countingEntries.get(i).GetCost(),countingEntries.get(i).GetDateOfPurchase().toEpochDay()));
                }
                String json = gson.toJson(saveDataObjects);
                editor.putString("MyCountingEntries", json);
                editor.apply();
                Toast.makeText(this, "Облікові записи успішно збережено!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Відсутні облікові записи для збереження!", Toast.LENGTH_SHORT).show();
            }
        }
        if(id == R.id.action_LoadCountingEntries)
        {
            SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesForArrayList<CountingEntries>", MODE_PRIVATE);
            String json = sharedPreferences.getString("MyCountingEntries",null);
            if(!json.isEmpty())
            {
                ArrayList<SaveDataObject> saveDataObjects = new ArrayList<SaveDataObject>();
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<SaveDataObject>>() {}.getType();
                saveDataObjects = gson.fromJson(json, type);
                countingEntries.clear();
                for(int i = 0; i < saveDataObjects.size(); i++)
                {   
                    long longdate = saveDataObjects.get(i).dateOfpurchase;
                    countingEntries.add(new CountingEntry(saveDataObjects.get(i).purchase,saveDataObjects.get(i).cost, LocalDate.ofEpochDay(longdate)));
                }
                RefreshList();
            }
            else
            {
                Toast.makeText(this, "Відсутні облікові записи для завантаження!", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
И объект для сохранение:
package com.example.personalaccounting;

public class SaveDataObject
{
    public String purchase;
    public int cost;
    public long dateOfpurchase;
    public SaveDataObject(String purchase_, int cost_, long dateOfpurchase_)
    {
        purchase = purchase_;
        cost = cost_;
        dateOfpurchase = dateOfpurchase_;
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.