这是ViewActivity

public class ViewActivity extends AppCompatActivity {

    private ListView lvPerson;
    private PersonListAdapter adapter;
    public List<Person> mPersonList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);

        lvPerson = (ListView)findViewById(R.id.listView);

        //Add new person
        Intent intent = getIntent();
        if(intent.hasExtra("add")){
            String name = intent.getStringExtra("name");
            String email = intent.getStringExtra("email");
            String address = intent.getStringExtra("address");
            mPersonList.add(new Person(name, email, address));
            Toast.makeText(getApplicationContext(), "Data berhasil ditambahkan", Toast.LENGTH_SHORT).show();
        }

        //Init adapter
        adapter = new PersonListAdapter(getApplicationContext(), mPersonList);
        lvPerson.setAdapter(adapter);

    }
}


这是InputActivity

public class InputActivity extends AppCompatActivity {

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

    public void saveButtonClicked(View view){

        EditText name = (EditText) findViewById(R.id.editTextName);
        EditText email = (EditText) findViewById(R.id.editTextEmail);
        EditText address = (EditText) findViewById(R.id.editTextAddress);

        String strName = name.getText().toString();
        String strEmail = email.getText().toString();
        String strAddress = address.getText().toString();

        Intent intent = new Intent(this, ViewActivity.class);
        intent.putExtra("add", true);
        intent.putExtra("name", strName);
        intent.putExtra("email", strEmail);
        intent.putExtra("address", strAddress);
        startActivity(intent);

    }
}


显示我的流程是在InputActivity中单击保存按钮时,它将在ViewActivity中运行“添加人”代码,并将数据从表单添加到ArrayList。

那是可行的,但是当我使用意图更改活动并回到ViewActivity时,ArrayList数据消失了。

我想要的是保留我已经在InputActivity中输入的所有值。

希望你明白我的意思:)

最佳答案

这里有一些很好的答案,但是由于您只希望它在一个应用会话中持久存在,因此我将添加另一种方法,即单例来保存数据:

class DataHolder {
    final List<Person> people = new ArrayList<>;

    private DataHolder() {}

    static DataHolder getInstance() {
        if( instance == null ) {
            instance = new DataHolder();
        }
        return instance;
    }

    private static DataHolder instance;
}


在任一活动(或应用程序中的任何位置)中,您都可以使用

List<Person> ppl = DataHolder.getInstance().people;


例如,您将替换

public List<Person> mPersonList = new ArrayList<>();




// not sure why that was public...
private List<Person> mPersonList = DataHolder.getInstance().people;


它只会在当前的应用程序会话中持续,但是如果您以后想保存它们,则可以将后端数据库添加到DataHolder中,以便每次添加一个人时,该数据库都会自动保存在某个地方。

07-26 06:24