Бесконечное назначение SharedPreference, но как? - PullRequest
0 голосов
/ 01 ноября 2018

Я делаю приложение, и у меня есть эта функция, которая бесконечно присваивает строку UserPreference, и я не понимаю, почему.

Java-файл:

public class generalSettings extends PreferenceActivity {
           @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.general_settings);

        List<Schedule> schedules = getSchedule();  

        if (schedules.isEmpty()) {
            from.setSummary("--:--");
            to.setSummary("--:--");
        } else {

            from.setSummary(schedules.get(0).getStartTime());
            to.setSummary(schedules.get(0).getEndTime());

        }


    private List<Schedule> getSchedule() {
        String cameraServiceSchedule = UserSharedPref.initializeSharedPreferencesForcameraServiceSchedule(getApplicationContext()).getString(UserSharedPref.cameraServiceSchedule, "");
        String[] scheduleStrings = cameraServiceSchedule.split(";");
        List<Schedule> schedules = new ArrayList<>();

        Log.d("TESTa:",cameraServiceSchedule);

        for (String scheduleString : scheduleStrings) {
            String[] times = scheduleString.split(",");
            if (times.length == 2) {
                try {

                    Log.d("TEST:","adding only 1");
                    schedules.add(new Schedule(Integer.parseInt(times[0]), Integer.parseInt(times[1])));
                    break;

                } catch (NumberFormatException ex) {

                    Log.d("TEST:","getting a NumberFormatException");
                    ex.printStackTrace();
                }
            }
        }
        return schedules;
        }
    }
   }

Schedule.java:

public class Schedule {

    private  Integer startTime;
    private  Integer endTime;

    public Schedule() {

    }
    public Schedule(Integer startTime, Integer endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public  Integer getStartTime() {
        return startTime;
    }

    public  void setStartTime(Integer startTime) {
        this.startTime = startTime;
    }

    public  Integer getEndTime() {
        return endTime;
    }

    public void setEndTime(Integer endTime) {
        this.endTime = endTime;
    }
}

Когда я регистрирую это, 2018-11-01 17:19:27.445 4346-4346/? D/TESTa:: 891,1131; в разное время печатается непрерывно до запуска приложения.

Итак, Testa печатает бесконечно, что является результатом логирования cameraServiceSchedule, который только что инициализирован из файла пользовательских настроек, но почему, он даже не находится в цикле, чтобы инициализироваться снова и снова. и один и тот же объект schedules.get(0) перезаписывается снова и снова, когда я делаю это List<Schedule> schedules = getSchedule();, я также регистрировал это. Есть ли обходной путь для этого?

1 Ответ

0 голосов
/ 01 ноября 2018

используйте этот подход это будет работать наверняка

это ваша основная деятельность

/**
 * Created by harkal on 01-11-2018.
 */

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ScheduleData scheduleData = new ScheduleData(this);
        if(scheduleData.getSchedule() == null){
            //set schedule here
            scheduleData.setSchedule(new Schedule(0, 0)); //set the schedule here i have put 0 just like that
        }else{
            //get the data and use it
            int startTime = scheduleData.getSchedule().getStartTime(); //this is the starting time use it how ever you want
            int endTime = scheduleData.getSchedule().getEndTime(); //similarly this is the ending time use it how ever you want
        }

    }
}

это ваш общий класс привилегий

/**
 * Created by harkal on 01-11-2018.
 */


public class ScheduleData {

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private static final String SCHEDULE_DATA = "SCHEDULE_DATA";
    private static final String SCHEDULE = "SCHEDULE";

    public ScheduleData(Context context) {
        sharedPreferences = context.getSharedPreferences(SCHEDULE_DATA , 0);
        editor = sharedPreferences.edit();
    }

    public void setSchedule(Schedule schedule) {
        Gson gson = new Gson();
        String json = gson.toJson(schedule);
        editor.putString(SCHEDULE, json);
        editor.commit();
    }

    public Schedule getSchedule() {
        Gson gson = new Gson();
        String json = sharedPreferences.getString(SCHEDULE, null);
        return gson.fromJson(json, Schedule.class);
    }

}

это файл объекта расписания

/**
 * Created by harkal on 01-11-2018.
 */

public class Schedule {

    private int startTime;
    private int endTime;

    public Schedule() {

    }

    public Schedule(int startTime, int endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public int getStartTime() {
        return startTime;
    }

    public void setStartTime(int startTime) {
        this.startTime = startTime;
    }

    public int getEndTime() {
        return endTime;
    }

    public void setEndTime(int endTime) {
        this.endTime = endTime;
    }
}

Я использовал библиотеку Google gson просто вставьте эту строку в файл Gradle вашего приложения

implementation 'com.google.code.gson:gson:2.8.5'

надеюсь, это поможет вам счастливое кодирование:)

если есть проблемы Леме знаю это

...