[英]Android: Saving an ArrayList to SharedPreferences, but loading it is not working
在今天早上提出類似問題之后,我進行了更多研究,並發現了(我認為)通過將其保存到SharedPreferences(將其轉換為Json String之后)來保存/加載ArrayList的方法。
問題是,我不知道將saveListe()和loadListe()放在哪里。
我沒有收到任何錯誤,但是在重新啟動應用程序時,列表仍然是默認列表(其中有1個游戲)。
這兩種方法和我的列表都在ListeJeux類中。
我嘗試在mainActivity中使用loadListe(),並在添加游戲后在另一個活動(將游戲添加到列表中以進行測試)中使用saveListe()。
如果我啟動其他活動,則它將一個游戲添加到列表中(此部分正在工作),但是如果我重新啟動應用程序,則該列表仍僅包含1個游戲(默認)。 問題是什么?
ListeJeux(包含保存和加載方法+默認列表):
package com.example.jouons;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
@SuppressWarnings("deprecation")
public class ListeJeux extends ActionBarActivity {
// By default, the list contains one game, if the listView show more than
// one, then addJeu() works, if it still shows more than one game after a
// restart, then the save/load works (not working for now).
static Jeu jeu1 = new Jeu("Ballon fou", "moyens grands", "intérieur");
static ArrayList<Jeu> jeux = new ArrayList<>(Arrays.asList(jeu1));
// This is only to test.
static void addJeu() {
jeux.add(new Jeu("Ballon fou", "moyens grands", "intérieur"));
}
// Takes "jeux" (this is where the problem happens, I think), and makes it a
// Json String. Then store it in SharedPreference.
static public void saveListe(Context context) {
Gson gson = new Gson();
String listeJson = gson.toJson(jeux);
SharedPreferences prefs = context.getSharedPreferences("listePrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("listeEditor", listeJson);
editor.commit();
}
// Takes the contain of the SharedPreference (Json String) and reverts it to
// an ArrayList. Then returns it.
static public ArrayList<Jeu> loadListe(Context context) {
Gson gson = new Gson();
SharedPreferences prefs = context.getSharedPreferences("listePrefs", MODE_PRIVATE);
String extractedJson = prefs.getString("listeEditor", "");
Type type = new TypeToken<ArrayList<Jeu>>() {
}.getType();
ArrayList<Jeu> jeux = gson.fromJson(extractedJson, type);
return jeux;
}
}
MainActivity(在其中我使用loadList()方法):
package com.example.jouons;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
@SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListeJeux.loadListe(this);
setupTrouvezButton();
setupRechercherButton();
setupListeButton();
}
private void setupListeButton() {
Button listeButton = (Button) findViewById(R.id.btnMainListe);
listeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ListeActivity.class));
}
});
}
private void setupTrouvezButton() {
Button trouvezButton = (Button) findViewById(R.id.btnMainTrouvez);
trouvezButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, TrouvezActivity.class));
}
});
}
private void setupRechercherButton() {
Button rechercherButton = (Button) findViewById(R.id.btnMainRechercher);
rechercherButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RechercherActivity.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
以及其他活動(將游戲添加到列表然后保存):
package com.example.jouons;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
@SuppressWarnings("deprecation")
public class RechercherActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rechercher);
ListeJeux.addJeu();
ListeJeux.saveListe(this);
setupRetourButton();
}
private void setupRetourButton() {
Button retourButton = (Button) findViewById(R.id.btnRechercherRetour);
retourButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.rechercher, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
如果要將陣列列表保存到共享首選項,則必須在保存之前序列化陣列列表。 如果它不是機密信息,我寧願將序列化對象保存到sdcard而不是將其保存到共享首選項。 如果它是一個緩存文件,我建議您將其保存到應用程序緩存目錄中。
序列化對象
public class SomeClassName implements Serializable{
private ArrayList<SomeObject> arrayList;
public void setObject(ArrayList<SomeObject> list){
arrayList = list;
}
public ArrayList<SomeObject> getObject(){
return arrayList;
}
}
雖然不建議使用ActionBarActivity,但它擴展了Activity,因此您應該能夠重寫onCreate,onResume和onPause來調用要加載和保存的方法。 例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rechercher);
setupRetourButton();
}
@Override
protected void onResume()
{
super.onResume();
ArrayList<Jeu> loaded = ListeJeux.loadListe(this);
for (Jeu j: loaded)
{
// This method to add doesn't exist and this whole loop should
// be refactored into the loadListe method.
ListeJeux.addJue(j)
}
// This size() method doesn't exist either and could also be subsumed into loadList
if (ListeJeux.size() == 0)
{
ListeJeux.addJeu();
ListeJeux.saveListe(this);
}
}
@Override
protected void onPause()
{
// Save the list as the app may stop any time after a pause.
ListeJeux.saveListe(this);
super.onPause();
}
我個人將對代碼進行一些重構,以便列表(ListeJeux)上的保存和加載方法實際上可以更新內部列表。 從本Android文檔頂部的圖中可以看出,您實際上只需要加載onResume,因為應始終在顯示活動之前調用onResume。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.