简体   繁体   English

如何将数组列表从活动发送到另一个活动,而不访问另一个活动

[英]How to send arraylist from activity to another, without visiting that other activity

I tried to get an answer for this before but couldn't get one that would solve my problem. 我曾尝试为此寻求答案,但无法解决我的问题。 I'm making app which keeps disc golf scores. 我正在制作可保持碟式高尔夫成绩的应用程序。 my MainActitivity has 4 buttons. 我的MainActitivity有4个按钮。 New game, resume game, courses and players. 新游戏,简历游戏,课程和玩家。

Atm when user goes to ActivityPlayers (Players button in main activity), user can add and delete players, and shared preferences keep that list save. 当用户转到ActivityPlayers(主要活动中的“播放器”按钮)时,用户可以添加和删除播放器,并且共享的首选项可以保存该列表。 But now I also need to somehow get that same list of players, to that ActivityNewGame (New game button in main activity), there I need to loop through that list, and use those names to make new items in ActivityNewGame list. 但是现在我还需要以某种方式将相同的玩家列表,移到那个ActivityNewGame(主活动中的“新游戏”按钮)上,我需要遍历该列表,并使用这些名称在ActivityNewGame列表中创建新项目。 (cannot just copy the list from ActivityPlayers straight, because in that recyclerview, those items have different buttons than new game recyclerview has, even tho they use the same list of names.) (不能直接从ActivityPlayers复制列表,因为在该recyclerview中,这些项目的按钮与新游戏recyclerview的按钮不同,即使它们使用相同的名称列表也是如此。)

I tried to do intent, but I realized that I can't use that because I have to visit that ActivityNewGame when a user adds or delete players from ActivityPlayers... 我试图做意图,但是我意识到我不能使用它,因为当用户从ActivityPlayers中添加或删除玩家时,我必须访问那个ActivityNewGame ...

This is the way I tried 这是我尝试的方式

This is my ActivityPlayers.java method. 这是我的ActivityPlayers.java方法。 This method will be called when the user adds a new name to mNamelist. 当用户向mNamelist添加新名称时,将调用此方法。

private void addItem(int position) {
    /** Get user input (name) **/
    textAdd = findViewById(R.id.name_input);

    /** Add name to the list **/
    mNameList.add(position, new NameItem(textAdd.getText().toString().trim()));

    /** sort that list **/
    sortArrayList();

    /** save changes to shared preferences **/
    saveData();

    /** Show changed list to user **/
    mAdapter.notifyItemInserted(position);

    /** Clear the input field **/
    textAdd.getText().clear();

    /** Send namelist to ActivitynewGame **/
    Intent i = new Intent(ActivityPlayers.this, ActivityNewGame.class);
    i.putExtra("PlayerList", mNameList);
    startActivity(i);
}

This is my savedata() method to save changes that user makes for namelist in ActivityPlayers: 这是我的savedata()方法,用于保存用户对ActivityPlayers中的名称列表进行的更改:

private void saveData() {
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(mNameList);
    editor.putString("task list", json);
    editor.apply();
}

This is my ActivityNewGame: 这是我的ActivityNewGame:

public class ActivityNewGame extends AppCompatActivity {
    private ArrayList<NewGamePlayerItem> mPlayerList;

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

        mPlayerList = new ArrayList<>();
        Intent intent = getIntent();
        ArrayList<NameItem> mNameList = (ArrayList<NameItem>) intent.getSerializableExtra("PlayerList");

        /** Check if mNameList has any items in it. **/
        if (mNameList.size() != 0) {
        /** Loop through that arraylist and set its names into this Activity items. ("true" is for checkbox that this item has.) **/
            for (int i = 0; i < mNameList.size(); i++) {
                mPlayerList.add(new NewGamePlayerItem(true, mNameList.get(i).getText1()));
            }
        }

        buildRecyclerView();
    }

The problem here is that I don't want to visit ActivityNewGame, I just want to pass that name list from ActivityPlayers, and when user choose to go to make a new game (ActivityNewGame), then that player list would be there. 这里的问题是我不想访问ActivityNewGame,我只想从ActivityPlayers传递该名称列表,并且当用户选择去制作一个新游戏(ActivityNewGame)时,该玩家列表就在那里。 So what should I do differently to manage to do that? 那么我应该怎样做才能做到这一点呢?

Please give me some examples of ideas if you have, thank you. 如果有的话,请给我一些想法示例,谢谢。

In ActivityPlayers.java addItem() method, save your data in shared preferences. 在ActivityPlayers.java addItem()方法中,将数据保存在共享首选项中。

private void addItem(int position) {
    /** Get user input (name) **/
    textAdd = findViewById(R.id.name_input);

    /** Add name to the list **/
    mNameList.add(position, new NameItem(textAdd.getText().toString().trim()));

    /** sort that list **/
    sortArrayList();

    /** save changes to shared preferences **/
    saveData();

    /** Show changed list to user **/
    mAdapter.notifyItemInserted(position);

    /** Clear the input field **/
    textAdd.getText().clear();

    /** save data to shared pref **/
    SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(<KEY_NAME>, ObjectSerializer.serialize(mNameList));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();
}

and in ActivityNewGame.java extract the ArrayList from shared preferences like so. 并在ActivityNewGame.java中从共享首选项中提取ArrayList,如下所示。

mNewNameList = new ArrayList<NewGamePlayerItem>();
 // load NewGamePlayerItems from preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

  try {
    mNewNameList = (ArrayList<NewGamePlayerItem>) ObjectSerializer.deserialize(prefs.getString(<KEY_NAME>, ObjectSerializer.serialize(new ArrayList<NewGamePlayerItem>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }

您可以使用RxBus将数据发送到另一个活动,而无需访问它。

You can save your arraylist in one file. 您可以将arraylist保存在一个文件中。

public void save(String fileName) throws FileNotFoundException {
String tmp = clubs.toString();
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
pw.write(tmp);
pw.close();
}

You can make the list static and then you don't need to pass it. 您可以将列表设为静态,然后无需传递它。 You can use it inside your app anywhere you want. 您可以在任何需要的应用程序内部使用它。

By making it static there may arise memory leaks problem so dispose them correctly after using it. 通过使其静态化,可能会出现memory leaks问题,因此请在使用后正确dispose它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM