r/javahelp • • Apr 03 '21

Solved Why does accessing an Arraylist from another class gives me an exception?

Now I know this is a very common issue, because I've seen many posts about on Stack, but I couldn't get those answers to work with my code. This is my code, shortened down to the relevant parts:

public class SeznamJedi {
    ArrayList<Jed> seznamJedi;

    public void addJed(String a, String b, double c){
        Jed toAdd = new Jed(a, b, c);
        seznamJedi.add(toAdd);
    }

    public int getSize(){
        return seznamJedi.size();
    }
}

^ This is my class, whose only purpose is to hold a list of Jed objects.

public class App extends Application {
      public SeznamJedi seznamJedi;

    @Override
    public void onCreate(){
        super.onCreate();
        seznamJedi = new SeznamJedi();
}

^ This is my App class, used to hold my global list of objects.

public class
MainActivity extends AppCompatActivity {
    App app;
    SeznamJedi tempSeznam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (App)getApplication();
        tempSeznam = app.seznamJedi;
        tempSeznam.addJed("h", "b", 12);
    }
}

^ And this is my MainActivity. The whole app crashes when I add the Jed object. Clearly it's not happy with me accessing the list and it's not allowing me to do any operations on it. I am at a loss and any help will be greatly appreciated.

16 Upvotes

10 comments sorted by

•

u/AutoModerator Apr 03 '21

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

25

u/morhp Professional Developer Apr 03 '21 edited Apr 03 '21

Your ArrayList in 'SeznamJedi' is never initialized, you just declared a field, but never assigned a new ArrayList<>().

Also generally, you should get an error message with the crash. Try to understand it first (Google it if required) and you still can't figure it out, at least post it here in the future.

Also this looks like an Android app, you're in the wrong subreddit for that, see sidebar.

14

u/RetroGmr Apr 03 '21

Thank you very much for the feedback. I made a proper constructor and it works now. Next time I will definetly include the error, that was pretty inconsiderate of me. I posted it here because I was pretty sure it wasn't an Android issue, but a Java issue. I'll take everything into consideration and thanks again.

8

u/morhp Professional Developer Apr 03 '21

That's fine, but note that a proper Java (especially the current versions) would've giving you a better error message (it would've told you which field is null) instead of just crashing, so it's still kinda relevant.

4

u/GDDragonGN_GDDK Apr 03 '21

I can't find your initialization of the ArrayList, meaning it will be null when you access it. Add seznamJedi = new ArrayList<>(); in the constructor of the class containing the list

2

u/RetroGmr Apr 03 '21

Thanks alot, this fixed it for me. I thought my initial "initializaton" was enough but clearly not.

2

u/bigibas123 Intermediate Brewer Apr 03 '21

Without seeing the error I can't know for sure but i don't see where the Arraylist in SeznamJedi is initialized.

2

u/ItsDotin Apr 03 '21

Initialise your ArrayList.

Usually, I will like to intilize it in a no-arg constructor i.e. default constructor. So when an object is created from the class it also creates an ArrayList object 'seznamJedi' for you.

(Not writting exact code- last time I did and was blocked for a week. 😅😂)

1

u/wildjokers Apr 03 '21

When you ask for help please include any relevant Exceptions you get. Saying "the whole app crashes" tells us nothing. Although in this case it was easy to see that you were most likely getting a NullPointerException when accessing seznamJedi, it isn't always that obvious.

0

u/[deleted] Apr 03 '21

[deleted]

1

u/wildjokers Apr 03 '21

There is a thread-safe variant of ArrayList called CopyOnWriteArrayList which should be used in that case.

CopyOnWriteArrayList should only be used if reads vastly out number writes. Writing to a CopyOnWriteArrayList is very expensive (as the name suggests).

Otherwise just use synchronize keyword to support multi-threaded access of a List (or some other appropriate concurrency mechanism).