0

I have an activity MyActivity that holds a service class MyService. I would like the service to send String data to the activity, and then create a button using this data.
Following this post I created a static method in the activity.
The problem of course is that i can't use this in a static context.

public class MyActivity extends Activity {


    private MyService myService;


    public void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.main);
        myService = new MyService();

    }


    public static void connectMethod (String buttonName) {

        Button btn = new Button(this); // error
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);

    }
}





public class MyService {

    ...

    private void showButton (String data) {
        MyActivity.connectedMethod(data);
    }
}
Community
  • 1
  • 1
Presen
  • 1,809
  • 4
  • 31
  • 46

1 Answers1

0

Two possible solutions to avoid your error:

  1. public static void connectMethod (Context context, String buttonName) {
    
        Button btn = new Button(context); 
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);
    
    }
    
    // ...
    
    public class MyService {
    
        private Context context;
    
        public MyService(Context context) {
            this.context = context;
        }
        ...
    
        private void showButton (String data) {
            MyActivity.connectedMethod(context, data);
        }
     }
    
  2. Or create a static class field : private static Context context;

    public static void connectMethod (String buttonName) {
    
        Button btn = new Button(context); 
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);
    
    }
    
S.Thiongane
  • 6,883
  • 3
  • 37
  • 52