Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method in another activity from an activity

I know that we can't call a method from an Activity that's in another Activity. I'm trying to figure out the best way around this.

Here is my code. This is the method I am trying to call. It is in my ScoreCard activity.

public void numPlayerSetup(){
{
    int[] ids = {
        R.id.TextView11, R.id.TextView12, R.id.TextView13
    };

    for(int i : ids) {
        TextView tv = (TextView)findViewById(i);
        tv.setVisibility(View.INVISIBLE);
    }

}

Here is how I am trying to call the method. score is an object of the ScoreCard class.

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    int item = spinner.getSelectedItemPosition();


    if(item==1){
        Log.i("error","This Sucks");
        score.numPlayerSetup();
    }
}

I tried to put the numPlayerSetup method in a different class that would not extend Activity, just contain the logic, but I can't use the findViewById() method without extending activity.

This is how I am calling it.

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    int item = spinner.getSelectedItemPosition();
    ArrayList<TextView> myTextViewList = new ArrayList<TextView>();

    TextView tv1 = (TextView)findViewById(R.id.TextView14);
    myTextViewList.add(tv1);

    if(item==1){
        Log.i("error","This Sucks");
        Setup.numPlayerSetup(myTextViewList);
    }

Then this is the class I am calling.

public class Setup {
    TextView tv;

    public static void numPlayerSetup(ArrayList<TextView> tvs){
        for(TextView tv : tvs) {
            Log.i("crash","This Sucks");
            tv.setVisibility(View.INVISIBLE);  //this line is highlighted in the debugger as the line my error is coming from
        }    
    }
}

It logs the message in the logcat and gives me a null pointer exception. The debugger says that the value for tv is null. Is this why I am getting a null pointer exception?


1 Answers

You can just make a Utitlity class(not Activity) and pass in the Textviews you wish to change. and call that method whenever you need it.

public class Setup {

public static void numPlayerSetup(ArrayList<TextView> tvs){

                 for(TextView tv : tvs) {
                            tv.setVisibility(View.INVISIBLE);
                        }    
             }
}

Then you can use it like(in Activity):

ArrayList<TextView> myTextViewList = new ArrayList<TextView>();
TextView tv1 = (TextView)findViewById(R.id.tv1);
myTextViewList.add(tv1);


    Setup.numPlayerSetup(myTextViewList);
like image 189
ninjasense Avatar answered Nov 29 '25 15:11

ninjasense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!