• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Separate Java into different files.

Karæthon

Newbie
I am reading the Java for my app and the file is getting very large and unwieldy can I take parts of my code that are related to each other put them into their own Java file and have the system load it somehow at one time or compilation time how do I reference these other files if I can is it in include statement or import statement?
 
Yes you can restructure your code and create more class files, if it makes sense to do so. You can even create new packages to group your classes. For example, you might want to have a 'database' package for all the code related to database access.
Use import statements to use classes from other packages. Android Studio is able to do that automatically, and add the correct import statements.
 
Ok, so I could theoretically have 1 file that handles all my button interaction code (quickly becoming the largest part of my code) and a different one that handles all my text field interaction code ( second largest code fragment) and then my Main activity file for the rest? Do I just put them in the Java folder with mainactivity.java or do I need to specify somehow to the import statement what to get?
 
You could do that. What a lot of people don't realise, is that software can fairly quickly become a mess of unorganised code (spaghetti code is the technical term :)
To avoid this, it's useful to apply some architectural design patterns.

This article is quite advanced, but I think it's a super presentation of a really great software architecture, which partitions the functionality into different layers, with each layer having a well defined role, and interface to other layers. Interfaces are very important in software architecture.

https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0

Once you achieve a good architecture, your code becomes infinitely more maintainable. Believe me you'll thank yourself for organising your code better, when it comes to adding features, and fixing bugs later.
 
Back
Top Bottom