0

I asked this question yesterday:

I have a problem. I want to add some items to my list view which is in activity 'b' by click on the button or other view in activity 'a'. For example:

My Activity 'a' :

b.setOnClickListener(new onClickListener() {
    @Override
    public void onClick(view v) {
        // add item to myarray which there in activity 'b'
        myArray.add("");
    }
});

My Activity 'b' :

ArrayList<String> myArray;

Hope to get my purpose. Thank-you.

Then I get this answer:

You can create a third object ( A public class where you put the ArrayList ) and access it every time you need its values : Update it from first activity and get values from second activity.

Activity 1:

b.setOnClickListener(new onClickListener() {
    @Override
    public void onClick(view v) {
        Utilities.addValue("String");
    }
});

Activity 2:

ArrayList<String> myArray = Utilities.getArrayList();

Utility Class:

public static class Utilities {
    static ArrayList<String> mArrayList;

    public static void addValue(String a) {
        if (null == mArrayList) {
            mArrayList = new ArrayList<>();
        }
        mArrayList.add(a);
    }

    public static ArrayList<String> getArrayList() {
        return mArrayList;
    }
}

But I have a new problem. When I click on the button, item add to the array string and show in list view. But when I exit from app and comeback later to the app, Activity 'b' which there is the list view in it, crashed. What the problem? How to save added items? Thankyou.

Andrew Churilo
  • 2,229
  • 1
  • 17
  • 26
  • Do you need the array list after restarting app too? – mustafiz012 Mar 16 '19 at 17:10
  • You need save the array in some persistent storage like a DB or a file that you need to read when you need it. There are hundreds of ways to implement it so I don't think there is a proper answer for this – kingston Mar 16 '19 at 17:31
  • Anyway if you want to avoid null pointer exceptions, don't return null. Return an empty list. In this way you do not need to check every time you add another item – kingston Mar 16 '19 at 17:32
  • Yes. I need to array string after restarting app. – محمدشریف رحیمی Mar 16 '19 at 17:53
  • Then use shared preferences, this (https://stackoverflow.com/a/7965356/8263625) may help you to store array and retrieve it from shared preferences. – mustafiz012 Mar 16 '19 at 18:25

1 Answers1

0

Method getArrayList() can return null, that can lead to crash. Update your Utilities class like this:

public static class Utilities {
    private static ArrayList<String> mArrayList;

    public static void addValue(String a) {
        getArrayList().add(a);
    }

    public static ArrayList<String> getArrayList() {
        if (mArrayList == null) {
            mArrayList = new ArrayList<String>();
        }
        return mArrayList;
    }
}
Andrew Churilo
  • 2,229
  • 1
  • 17
  • 26