Reusing methods in different activities in Android
Is it possible to reuse methods in different activities? Say for example, I have retrieveAllStudents()
in StudentActivity
. Can I make it static or something and call the method in ClassActivity
? Or do I need to duplicate the method in both activities?
Which one is correct?
Example 1:
StudentActivity
public static ArrayList<Student> retrieveAllStudents(){
...
return studentList;
}
ClassActivity
import StudentActivity
开发者_如何学Go
ArrayList<Student> studentList= StudentActivity.retrieveAllStudents();
Example 2:
StudentActivity
public static ArrayList<Student> retrieveAllStudents(){
...
return studentList;
}
ClassActivity
public static ArrayList<Student> retrieveAllStudents(){
...
return studentList;
}
ArrayList<Student> studentList= retrieveAllStudents();
If it is public static
it is definitely accesible from other activities (and any other class in your app). However, when activities call functions on each other, it can lead to overly complex code. Consider moving the getStudent() function and other shared functionality to a separate Student class.
Edit yes it is possible to reuse methods in other classes. This is very common and considered a best practice. Given your two examples, the first is more correct.
If it is a generic method, then keep it in Application class, make static context of application class
public static Context getAppContext() {
return context;
};
By my opinion better approach would be to make class (just class but not Activity) with necessary methods, then create instance of that common methods class in Activity and use methods when u need them. (example)
Other solution would be to extend StudentActivity from ClassActivity if they both need to be Activities which is not the case here.
Anyway maybe you should think again what classes should be Activities in your App. It might be useful to read a bit about activities. Then I propose using one of two methods described above according to your needs. That will prevent problems caused by removing your activity from stack by Android system (you can read about activity lifecycle too) .
Cheers
精彩评论