Android Studio Add item in list view from a second Activity

Viewed 23

So actually when you have first Activity you can add something and in the second Activity there is a listView which gets the item added. In my case I want to push an add button, then a second Activity opens with a contact form. I can enter Information in it and then when I click done, I want that the data I entered will be added to the listView in my MainActivity. Is this possible ? You can compare it with an contact app, when you click +(add) then enters the data und the app throws you back to the original layer with a new contact now.

public class MainActivity extends AppCompatActivity {
private FloatingActionButton addContactButton;

ListView listView;
ArrayList<String> contacts;




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



    addContactButton = findViewById(R.id.add_contact);
    addContactButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openActivity2();
        }
    });


}
public void openActivity2() {
    Intent intent = new Intent(this, MainActivity2.class);
    startActivity(intent);
}

public class MainActivity2 extends AppCompatActivity {
private FloatingActionButton saveContact;

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


    saveContact = findViewById(R.id.save_Contact_button);



}
1 Answers

Yes, you can use a bundle with intent when starting your activity via startActivity(intent), like that :

in your contact activity add this code:

Bundle dataBundle = new Bundle();
dataBundle.putInt("test_id", 1);
dataBundle.putString("test_name", "test");
youintent.putExtras(dataBundle);
startActivity(intent);

and in your activity which you have a listview :

Bundle bundle = getIntent().getExtras();
int test_id = bundle.getInt("test_id");
String test_name = bundle.getString("test_name");

After that, you can add your information to your listview via adapter or notifiying your listview

Related