Question

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.

Était-ce utile?

La solution

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

Autres conseils

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));
  }
} 

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));

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top