0

I created a Java file in the same package as my main activity with a class named sup.

Now, I need to use this class in the main activity file.

mainActivity.java:

package com.example.phy.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); } sup mola = new sup(this); mola.as(); } 

sup.java:

package com.example.phy.myapplication; import android.content.Context; import android.widget.Toast; public class sup { public sup(Context context){ CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } void as(Context context){ CharSequence text = "as method"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } 

Do I have to import the class into mainActivity? How?

2 Answers 2

1

sup class and MainActivity class are located in the same package, so you dont need to import anything, BUT you are calling a method of the classs sup in no defined scope... it would be better if you move this

sup mola = new sup(this); mola.as(); 

inside of the on create method so like:

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sup mola = new sup(this); mola.as(); } } 
Sign up to request clarification or add additional context in comments.

Comments

1

Import is not needed if MainActivity and sup class have the same package name

There's a missing parameter in mola.as(); It needs to be: mola.as(this);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.