Android 为ListView保存列表

Android 为ListView保存列表,android,listview,android-activity,android-listview,gson,Android,Listview,Android Activity,Android Listview,Gson,以下是名单声明: public List<gameRowItem> GameRowItem; 公共列表GameRowItem; 以下是setOnItemClickListener代码: gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> pa

以下是名单声明:

public List<gameRowItem> GameRowItem;
公共列表GameRowItem;
以下是setOnItemClickListener代码:

gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            if(position == plusPosition) //when plusSign is clicked
            {

                someGame = new Game();  //instance of game class
                someGame.gameName = preferences.getString("Game Name", null);
                gson = new Gson();

                jsonOfSomeGame = gson.toJson(someGame);       // put someGame into json
                editor.putString("someGame", jsonOfSomeGame);  //put some game into sharedPreferences
                editor.commit();

                jsonOfSomeGame = preferences.getString("someGame", null);  //receive json of some game
                savedSomeGame = gson.fromJson(jsonOfSomeGame, Game.class);  // turn json into object of game
                arrayOfGames.add(0, savedSomeGame);

                jsonOfNewGame = gson.toJson(newGame);
                editor.putString("newGame", jsonOfNewGame);
                editor.commit();

                jsonOfNewGame = preferences.getString("newGame", null);
                savedNewGame = gson.fromJson(jsonOfNewGame, gameRowItem.class);
                savedNewGame = new gameRowItem(savedSomeGame.gameName);

                jsonOfGameRowItem = gson.toJson(GameRowItem);
                editor.putString("GameRowItem", jsonOfGameRowItem);
                editor.commit();

                jsonOfGameRowItem = preferences.getString("GameRowItem", null);
                gameRowItem[] savedGameRowItem = gson.fromJson(jsonOfGameRowItem, gameRowItem[].class);



                GameRowItem.add(0, savedNewGame);
                adapter.notifyDataSetChanged();

                plusPosition++;


            }else{
                Intent toGamePlay = new Intent(ListOfGames.this, GamePlay.class);
                startActivity(toGamePlay);
            }


        }
    });
gameListView.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
if(position==plusPosition)//单击plusSign时
{
someGame=newgame();//游戏类的实例
someGame.gameName=preferences.getString(“游戏名”,null);
gson=新的gson();
jsonOfSomeGame=gson.toJson(someGame);//将someGame放入json
putString(“someGame”,jsonOfSomeGame);//将一些游戏放入SharedReferences
commit();
jsonOfSomeGame=preferences.getString(“someGame”,null);//接收某个游戏的json
savedSomeGame=gson.fromJson(jsonOfSomeGame,Game.class);//将json转换为游戏的对象
arrayOfGames.add(0,savedSomeGame);
jsonOfNewGame=gson.toJson(newGame);
putString(“newGame”,jsonOfNewGame);
commit();
jsonOfNewGame=preferences.getString(“newGame”,null);
savedNewGame=gson.fromJson(jsonOfNewGame,gameRowItem.class);
savedNewGame=新gameRowItem(savedSomeGame.gameName);
jsonOfGameRowItem=gson.toJson(GameRowItem);
putString(“GameRowItem”,jsonOfGameRowItem);
commit();
jsonOfGameRowItem=preferences.getString(“GameRowItem”,null);
gameRowItem[]savedGameRowItem=gson.fromJson(jsonOfGameRowItem,gameRowItem[].class);
GameRowItem.add(0,SavedNewName);
adapter.notifyDataSetChanged();
plusPosition++;
}否则{
Intent-toGamePlay=新意图(ListOfGames.this,GamePlay.class);
星际触觉(toGamePlay);
}
}
});

我正在尝试保存ListView上的项目,以便即使我离开活动,它仍会在那里。正如您可能看到的,我一直在尝试使用Gson来存储对象,希望它能将该项保存在ListView上。然而,我现在意识到我应该尝试保存实际的列表,即GameRowItem,我只是不知道如何继续保存GameRowItem。我甚至尝试将GameRowItem保存到代码的底部,但没有成功。任何帮助都将不胜感激,如果您需要更多代码,请随时询问。

为UI和数据创建单独的类(模型和列表)

您已经有了您的型号:
游戏
。创建
GamesList
,方法包括从存储器中加载
games
列表、保存列表、添加新的
games

然后在活动中,加载
游戏列表
并填充列表视图。单击加号时,将新的
GameRowItem
添加到
GamesList
并保存它

我更喜欢将列表保存到私有文件,而不是
SharedReferences
,因为它很容易存储实现
可序列化的对象

public class Game implements Serializable {
    private String name;
    // ...
}


public class GamesList {
    private static final String FILENAME = "games.ser";

    private List<Game> list;

    public GamesList() {
        list = new ArrayList<Game>();
    }

    public int size() {
        return list.size();
    }

    public GamesList add(Game item) {
        // Add at the front of the list
        list.add(0, item);

        return this;
    }

    public Game get(int position) {
        return list.get(position);
    }

    public void remove(int position) {
        list.remove(position);
    }

    @SuppressWarnings("unchecked")
    public void loadFromCache(Context context) {
        try {
            InputStream in = context.openFileInput(FILENAME);

            ObjectInputStream objIn = new ObjectInputStream(in);
            list = (List<Game>) objIn.readObject();
            objIn.close();
        } catch (Exception e) {
        }
    }

    public void saveToCache(Context context) {
        try {
            FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(list);
            out.close();
        } catch (IOException e) {
        }
    }
}


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mGamesList = new GamesList();
    mGamesList.loadFromCache(this);
}

gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if(position == plusPosition) //when plusSign is clicked
        {

            someGame = new Game();  //instance of game class
            // fill game per your logic
            mGamesList.add(someGame).saveToCache(ListOfGames.this);

            adapter.notifyDataSetChanged();

            plusPosition++;


        }else{
            Intent toGamePlay = new Intent(ListOfGames.this, GamePlay.class);
            startActivity(toGamePlay);
        }


    }
});
公共类游戏实现可序列化{
私有字符串名称;
// ...
}
公共类玩家{
私有静态最终字符串FILENAME=“games.ser”;
私人名单;
公共游戏列表(){
列表=新的ArrayList();
}
公共整数大小(){
返回list.size();
}
公共游戏列表添加(游戏项目){
//在列表的前面添加
列表。添加(0,项);
归还这个;
}
公共游戏获取(整数位置){
返回列表。获取(位置);
}
公共无效删除(内部位置){
列表。删除(位置);
}
@抑制警告(“未选中”)
公共void loadFromCache(上下文){
试一试{
InputStream in=context.openFileInput(文件名);
ObjectInputStream objIn=新ObjectInputStream(in);
list=(list)objIn.readObject();
objIn.close();
}捕获(例外e){
}
}
公共void saveToCache(上下文){
试一试{
FileOutputStream fos=context.openFileOutput(文件名,context.MODE\u PRIVATE);
ObjectOutputStream out=新的ObjectOutputStream(fos);
out.writeObject(列表);
out.close();
}捕获(IOE异常){
}
}
}
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mGamesList=新游戏列表();
mGamesList.loadFromCache(此);
}
gameListView.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
if(position==plusPosition)//单击plusSign时
{
someGame=newgame();//游戏类的实例
//按照你的逻辑填充游戏
mGamesList.add(someGame.saveToCache)(games.this列表);
adapter.notifyDataSetChanged();
plusPosition++;
}否则{
Intent-toGamePlay=新意图(ListOfGames.this,GamePlay.class);
星际触觉(toGamePlay);
}
}
});

你能解释一下你想做什么吗?不太清楚。此外,类名称应以大写字母开头,变量应以小写字母开头。列表等集合的变量名应为复数。这将使其他人更容易理解您的代码。公开名单项目;我正在尝试将GameRowItem保存到SharedReferences,以便在向GameRowItem添加项目时,即使我在活动之间切换,该项目也将永久存在列表视图中。谢谢你的建议,我确实需要改进我的命名约定。