1

I have come across this question on StackOverflow but I can't use the solutions suggested. One of the most common solutions was to extend the Application class but I can't do that because the class I am in already extends another class. Is there any other way of getting the context of a class?

public class SMSReceiver extends BroadcastReceiver {
         .......
         .......
         CreateDB dc = new CreateDB(mcontext);
         dc.addBook(new Book(senderPhoneNumber,ang));

}

Basically, I need to receive a message and add the sender's number and the message to a database and I need to get the context to create an instance of the database. I am a beginner in android so it would be great if you could keep the language simple.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

when you extends BroadCastReceiver you have to add this method

 public void onReceive(Context context, Intent intent){

}

as you can see there is a context in the parameter

Anas Reza
  • 646
  • 2
  • 9
  • 28
  • Thanks! I didn't realise that I could use the same context and was trying to create a constructor which was resulting in my app crashing all the time. – Harichandan Pulagam Feb 15 '14 at 06:27
  • I am a newbie on StackOverflow and am apparently not allowed to accept an answer shortly after asking it.. I will definitely do so when it allows me.. – Harichandan Pulagam Feb 15 '14 at 06:33
1

You can get the Context from onReceive() method as follows...

public class SMSReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    CreateDB dc = new CreateDB(context);
    dc.addBook(new Book(senderPhoneNumber,ang));
  }
} 
Gopal Gopi
  • 11,101
  • 1
  • 30
  • 43
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
0

From Activity in your application you can access the Context of the activity. In your class by using a static reference for example In you activity class create a static reference

public class MyActivity extends Activity {
public static Context mContext;

public static Context getContext() {
    return mContext;
}

public static void setContext(Context mContext) {
    this.mContext = mContext;
}
}

and just pass it in your SMSReceiver class like this

public class SMSReceiver extends BroadcastReceiver {
         .......
         .......
         CreateDB dc = new CreateDB(MyActivity.getContext());
         dc.addBook(new Book(senderPhoneNumber,ang));

}
Abhijit Chakra
  • 3,201
  • 37
  • 66