1

in my application i need to pass parameters to TimerTask for use Context. but i can not do it. in this below code GetSMSThread class is subclass and that need to get parameters from main class.

Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);

GetSMSThread subClass:

public class GetSMSThread extends TimerTask {
    @Override
    public void run() {

    }
}

3 Answers3

2

There two ways to resolve your issue

  • Declare your GetSMSThread it self in MainClass so no need to send params in Constructor

  • Another way is to send parameters in Constructors



Option 1 :

public class MainClass extends Activity {

    private String myString = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // .... your code
        Timer smsThread = new Timer();
        GetSMSThread getSMSThread = new GetSMSThread();
        smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
        myString = "assigning some value";
    }

    public class GetSMSThread extends TimerTask {

        @Override
        public void run() {
            myString = "manipulating Values";
        }
    }

}

Option 2 :

public class MainClass extends Activity {

    private String myString = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // .... your code
        myString = "assigning some value";
        Timer smsThread = new Timer();
        GetSMSThread getSMSThread = new GetSMSThread(myString);
        smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
    }

}

GetSMSThread :

public class GetSMSThread extends TimerTask {

    private String myString = "";

    public GetSMSThread(String mString) {
        myString = mString;
    }

    @Override
    public void run() {
        myString = "manipulating Values";
    }
}
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
0
    Timer smsThread = new Timer();
    GetSMSThread getSMSThread = new GetSMSThread("data");
    smsThread.scheduleAtFixedRate(getSMSThread, 0, 100000);
    GetSMSThread subClass:

    public class GetSMSThread extends TimerTask {

     String data;
    GetSMSThread(String data){

     this.data = data;

    }
        @Override
        public void run() {
              //use data here
        }
    }
Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
0

You can pass a context object to a class through a constructor.

public class GetSMSThread extends TimerTask {
Context context;
public GetSMSThread (Context context){
    this.context = context;
}
@Override
public void run() {
   //make sure you dont use the context in a background thread
}
}

You can instantiate the **GetSMSThread ** class and pass a valid context to it:

GetSMSThread  myThread = new GetSMSThread(myContext);
//start your timer
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61