Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes vs Activities in Android

I'm a beginner in Android development but not in programming itself. Anyway, this question might be a bit dumb.

The question is: Are all classes in Android activities related to a UI element? I want to have a "regular" Java class from which i can normally create objects and i'm not figuring out how to "define it" and how to "call" it.

Any help would be much appreciated. Thanks

like image 678
tyb Avatar asked Dec 21 '22 03:12

tyb


2 Answers

Yes you can have regular classes and no they are not all related to a UI element. This works pretty much like normal Java. So in Eclipse you can create a new class like in the image and follow the one page wizard.

Creating a new class in Eclipse

You will end up with some code like the below (I added a few bits for the example):

package this.is.your.package;

public class Person{

    private int age;

    public void setAge(int _age)
    {
        age = _age;
    }

}

You can then build methods and other stuff as normal. As for instantiating or accessing your class you will probably have to make it public for the activities to get it. However there are a many number of different ways of doing this but for the example above I could do.

public class MyActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Person me = new Person();
        me.setAge(22); //feels old
    }

As you can see this is all pretty normal.

like image 172
Graham Smith Avatar answered Jan 06 '23 18:01

Graham Smith


The answer is NO. All activities are regular Java classes and you can - of course, have many non-UI classes like Application, you can have helpers etc... If I understand you question correctly, you are confused by the fact the Activity doesn't have user defined constructor and can be created only indirectly by calling startActivity method, but in other acpects it is a common Java class.

like image 35
vitakot Avatar answered Jan 06 '23 18:01

vitakot