Mainactivity recognizes methods from external classes

Asked

Viewed 64 times

0

And everyone, I’m starting to program with Android Studio, but I have a problem. I created a class in the same mainactivity package, and I was able to instill that class, but I can’t use its Methods. Mainactivity is not recognizing these methods.

Follows Code of the Class:

package com.example.myapplication;

public class Casa {

    public void AbrirPorta(){
        System.out.println("Porta Aberta");
    }
}

Follow Mainactivity Code:

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    Casa C = new Casa();
}
  • Good night, Wesley! Where you call the method?

  • Yes Ivan, right after the instance, I call the class, but it does not suggest any option of methods. And if I type the method name, it is not recognized

1 answer

1

Good night, Wesley!

Simply call your method within another, that way

public class MainActivity extends AppCompatActivity {
    Casa c = new Casa(); // Mudei de posição apenas por questões didáticas

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Chame aqui ou dentro de outro método
        c.seuMetodo();
    }
}

In class internal space, you can only declare properties/parameters, methods and instantiating objects [as you did], but you cannot call methods.

  • Vlw Ivan, it worked, but the fuck is that, according to the instructor of the course I’m doing, the method call it makes works out of the "protected void onCreate()"

  • It doesn’t necessarily need to be inside the onCreate, but it needs to be within some method. If my answer helped you, mark it as correct. Hug!

  • Anything, ask him to prove that he can call some method within the "scope" of another

Browser other questions tagged

You are not signed in. Login or sign up in order to post.