Android Access Activity Methods From Non-Activity Class - java

This is the method I want to access from the Activity class (ActivityName):
public MediaPlayer getBlipComp() {
return blipComp;
}
EDIT
In the activity class
public SingleGameActivity getSingleGameActivity() {
return this;
}
This is working fine in my SurfaceView class:
SingleGameActivity myActivity = ((SingleGameActivity)getContext()).getSingleGameActivity();
// Later in the code
myActivity.getBlipStart().start();
But when I pass the reference variable to the ball (normal)-class it doesn't work:
ball = new Ball(myActivity, box.getCenterX(), box.getCenterY(), currentLvl,
Color.GREEN);
Ball-class
public Ball(SingleGameActivity activity, int xPos, int yPos, int level,
int color) {
myActivity = activity;
THIS METHOD CAN NOT BE CALLED FROM THE BALL CLASS, WHY? SOLUTION?
myActivity.getBlipPlay().start();

Pass the ActivityName instance into the constructor of NormalClass like this:
public class NormalClass {
private ActivityName activity;
public NormalClass(ActivityName activity){
this.activity = activity;
}
public void doSomething()
{
activity.getBlipComp();
}
}

this line:
ActivityName name = new ActivityName();
actually creates a new Activity show.
thats not what you want.
You have to options to do this:
1. you pass the Activity show to the "normal class" and keep it as a field:
public class NormalClass {
private Activity myActivity;
and use it as you want.
2.do the same only in the activity class.
public class MyActivity extends Activity{
public static Activity myActivity;
and int the constructor assign "MyActivity.myActivity = this;"
and than use a static method like so to use your activity:
public static MediaPlayer getBlipComp(){
return myActivity.getBlipComp();
}
and than use this method like so:
MyActivity.getBlipComp();
Have Fun!

Related

How to change a variable from an activity inside my adapter (java class change variable passed to it)

My Activity has the value Sound selectedToe. I want my soundPageChangeListener to be able to update the selectedToe of the activity, so I pass selectedToe like this:
SoundPageChangeListener soundPageChangeListener = new SoundPageChangeListener(soundsToe, selectedToe);
however, when I change selectedToe inside soundPageChangeListener:
public class SoundPageChangeListener implements ViewPager.OnPageChangeListener {
private ArrayList<Sound> sounds;
Sound currentSound;
public SoundPageChangeListener(ArrayList<Sound> sounds, Sound currentSound) {
this.sounds = sounds;
this.currentSound = currentSound;
}
#Override
public void onPageSelected(int position) {
Sound sound = sounds.get(position);
currentSound = sound;
}
the selectedToe on the activity still null.
Aren't all java values pointers? If I change something inside the listener, shouldn't it change outside?
You can make SoundPageChangeListener inner class of your activity, so the Listener can access to the Activity selectedToe variable.
Having an inner class will allow this class SoundPageChangeListener to have visibility and access to your activity selectedToe variable.
The pointer is not kept in your scenario as you are creating a new class instance. Your are assigning currentSound not re-pointing to the memory address.
Then in onPageSelected assign selectedToe with sound
class YourActivity {
...
Sound selectedToe = currentSound // set the default sound if any
// Inside the activity, declare your listener
public class SoundPageChangeListener implements ViewPager.OnPageChangeListener {
private ArrayList<Sound> sounds;
// only the sound list is required here
public SoundPageChangeListener(ArrayList<Sound> sounds) {
this.sounds = sounds;
}
#Override
public void onPageSelected(int position) {
Sound sound = sounds.get(position);
YourActivity.this.selectedToe = sound
}
}
}

Android - How to properly get a variable from a parent activity from a fragment

I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.
if have an interface like this in my fragment
public interface InteractWithFragmentA {
String getStringText();
}
In my calling activity I tested it out with a dummy text
#Override
public String getStringText(){ return "Some dummy text";}
I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using
_hostActivity.getStringText()
the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.
Yo should do this:
Activity
public class YourActivity implements YourActivityInterface{
#Override public String getStringText(){ return "Some dummy text";}
}
Interface
public interface YourActivityInterface {
String getStringText();
}
Fragment
public class YourFragment extends Fragment {
YourActivityInterface mListener;
//your method...
mListener.getStringText()
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof YourActivityInterface) {
mListener = (YourActivityInterface) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement YourActivityInterface");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Try this from fragment
((YourActivity) getActivity()).getStringText();

How to call a Main activity method in another non activity class

Below is My Main activity with ColorChange method.I want to call this Colorchange method in ImageColor Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ColorChange() { // <----- Want to call this method in below class
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
And this is my class where i want to call the ColorChange method of Mainactivity.
public class ImageColor {
public void Imager() {
// Want to call my ColorChange method here
MainActivity obj = new MainActivity();
obj.ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
I have already tried using Mainactivity as object it crashes my app.I also cannot declare my ColorChange method static because it uses findViewbyid.Please let me know if there is any way to call Color change method in this Image Color Class.
Try this way. It will help you.
public class ImageColor {
public void Imager(Activity activity) {
// Want to call my ColorChange method here
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method
class MainActivity {
interface mInterface = new interface() {
public void colorChange(){
}
}
}
pass mInterface to non activity class and call colorChange of interface when you want ..
You have to pass activity as a parameter in ImageColor class
Then call your ColorChange() method by refference of Activity.
Like This-
public class ImageColor {
Activity activity;
public ImageColor(Activity activity)
{
this.activity = activity;
}
public void Imager()
{
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange();
}
}
Activity classes are created by Android. So the above method is not correct.
You have 2 ways to access the method in activity.
1 . using a static method
public static void ColorChange() {
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
Using a callback mechanism
public interface ImageLoadedcallback{
void onColorChanged(int color);
}
And update
public class ImageColor {
public void Imager(ImageLoadedcallback callback) {
callback.onColorChanged(color)
}
}
And In activity
public void ColorChange() {
new ImageLoader().Imager(new ImageLoadedcallback{
#Override
public void onImageLoaded(Color color){
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
});
}
To make it clear, make an Activity as a static variable can lead to Activity leak, so we must avoid doing that.
I suppose if the Activity where you create ImageColor object is MainActivity, you can pass MainActivity directly to achieve what you want.
public class ImageColor {
public void Imager(MainActivity activity) {
activity.ColorChange();
}
}
If you called it from other class(not from MainActivity), you can always passing MainActivity to that other class object to be used for ImageColor object.
PS: Check about java naming convention too, it will help you to write a better code

calling an activity method from custom onClickListener class

i trying to call a method that stays in my MainActivity class from custom onClickListener object. And there is something wrong with variable scope.
so in my MainActivity i have:
Button resetButton = (Button) findViewById(R.id.ResetButton);
View.OnClickListener myListener = new MyListener(GameBoard, width);
resetButton.setOnClickListener(myListener);
this is what my myListener class look like:
public class MyListener implements View.OnClickListener
{
private static MainActivity mainActivity;
public MyListener(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public void onClick(View v) {
mainActivity.myMethod();
}
}
and method also in MainActivity that uses some MainActivity instance variables:
public void myMethod()
{
InstanceVariable++; // for example
}
Then when calling that myMethod on mainActivity object that i passing to myListener constructor by clicking resetButton i getting an error something about MainActivity InstanceVariable scope. I`m very beginner to android programming, so i cant fully understand where its coming from.
And this error disappears when i pass this InstanceVariable to constructor of myListener object. I think there should be an easier way to do that.
Change to:
public void myMethod() {
mainActivity.instanceVariable++; // for example
}
instancevariable is not visible in your MyListener class, you have to point that it ts in the mainActivity object.
If your instanceVariable is private, create getter function in mainActivity:
public void getInstanceVariable() {
return this.instanceVariable
}
and use it this way:
public void myMethod() {
mainActivity.setInstanceVariable(mainActivity.getInstanceVariable()+1); // for example
}
make InstanceVariable to
public static int InstanceVariable;
and use this
#Override
public void onClick(View v) {
MainActivity.InstanceVariable++;
}
don't make methods for function that has less than 8 lines
Try this :
Make your listener an inner class of your activity, then :
class MyListener implements View.OnClickListener {
public MyListener() {
}
#Override
public void onClick(View v) {
MainActivity.this.myMethod();
}
}

Passing a variable from one class to another in java

I have an android app and I need to pass a variable (instrument) to its main activity. It may seem like a simple question, but it confuses me. I looked around and I already noticed that it seems like a good idea to write a getInstrument method. This is what I did so far:
public class MainActivity extends Activity{
//I need to read the instrument variable here
public void addListenerOnSpinnerItemSelection(){
instrumentSp = (Spinner) findViewById(R.id.instrument);
instrumentSp.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
}
seperate class (in seperate file):
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private int instrument;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"Please wait a minute for the instrument to be changed. ", Toast.LENGTH_SHORT).show();
//"Item : " + parent.getItemAtPosition(pos).toString() + " selected" + pos,
//Toast.LENGTH_SHORT).show();
instrument = pos;
}
public int getInstrument(){
return instrument;
}
}
But I don't think I can call the getInstrument() method from the main activity, since the object only exists within the listener. There must be a really simple way around it. I read some posts, but the problem seems to be that the object of the class does not really exist. Thanks for any insights.
You can try this :
public class MainActivity extends Activity{
//I need to read the instrument variable here
CustomOnItemSelectedListener MyListener = new CustomOnItemSelectedListener();
public void addListenerOnSpinnerItemSelection(){
instrumentSp = (Spinner) findViewById(R.id.instrument);
instrumentSp.setOnItemSelectedListener(MyListener);
}
}
If you have a reference to your listener, you should be able to call its methods, eg.
CustomOnItemSelectedListener listener = new CustomOnItemSelectedListener();
instrumentSp.setOnItemSelectedListener(listener);
....
int instrumentValue = listener.getInstrument();
Create a global instance of the
CustomOnItemSelectedListener listener;
int instrument;
public void onCreate(Bundle b){
listener = new CustomOnItemSelectedListener();
instrument = listener.getInstrument();
}
This will be on the MainActivity class

Categories

Resources