Home > OS >  How do I access an array from a different activity?
How do I access an array from a different activity?

Time:06-18

I have 2 activities: MainActivity and createRecipe, and a class Recipe. MainActivity directs me to createRecipe where I can create a new recipe. My problem is after creating the recipe, I want to save that in an ArrayList recipeList which was created in MainActivity. How would I access that array from createRecipe to save it?

Here's my code for createRecipe activity

// Create EditText objects from the layout
    EditText etRecipeName = findViewById(R.id.recipeName);
    EditText etDuration = findViewById(R.id.duration);
    EditText etIngredient = findViewById(R.id.ingredients);
    EditText etDesc = findViewById(R.id.description);
    EditText etSteps = findViewById(R.id.steps);

    // onClickListener for createRecipe button
    Button createButton = findViewById(R.id.createButton);
    createButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Checks if there are empty fields
            if (isEmpty(etRecipeName, etDuration, etIngredient, etDesc, etSteps) == false) {
                Toast.makeText(createRecipe.this, "There are empty fields. Please fill up all fields",
                        Toast.LENGTH_SHORT).show();
            }
            // Checks if fields are entered correctly
            else {
                if (correctType(etRecipeName, etDuration, etIngredient, etDesc, etSteps) == true) {
                    CreateRecipe(etRecipeName, etDuration, etIngredient, etDesc, etSteps);
                    Toast.makeText(createRecipe.this, "Recipe Created", Toast.LENGTH_SHORT).show();
                    // How should I save it
                    finish();
                }
                else {
                    Toast.makeText(createRecipe.this,
                            "Some fields are entered wrongly. Please try again", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

And in MainActivity, I have

ArrayList<Recipe> recipeList;

CodePudding user response:

You can pass an "ArrayList< Recipe >, the same way if the Recipe type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>(); intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

CodePudding user response:

When you direct from MainActivity to CreateRecipeActivity start the activty (for-result)
So it should be like this code:

MainActivity.java

ArrayList<Recipe> recipeList;

// this for register a contract for (Start Activity For Result)
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        recipeList = (ArrayList<String>) data.getSerializableExtra("recipeList");
                    }
                }
            });

void openCreateRecipeActivity(){
   Intent intent = new Intent(MainActivity.this, CreateRecipeActivity.class);
   activityResultLauncher.launch(intent);
}

CreateRecipeActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     Button createButton = findViewById(R.id.createButton);
     createButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // rest of your code
            ArrayList<Recipe> recipeList = CreateRecipe(..);
            Intent intent = new Intent();
            intent.putExtra("recipeList", recipeList);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    });
}
    

ArrayList<Recipe> CreateRecipe(..){
     ArrayList<Recipe> recipeList = new ArrayList<Recipe>();
     // what ever you do just return the array list
     return recipeList;
}

I hope this will help you :)

  • Related