1

I want to try getting some value from my Setting using the following code:

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.content.*;
public class TCPdumpHandler {

    public void getPreference() {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        Boolean checkboxPreference = prefs.getBoolean("checkboxPref", true);
    }
}

But the error is : The method getBaseContext() is undefined for the type TCPdumpHandler

Can you tell me the reason why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tran Ngu Dang
  • 2,540
  • 6
  • 29
  • 38
  • 2
    [You shouldn't use `getBaseContext()` at all](http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context) if you don't know why you need exactly that context *(given that this is a beginner question, you probably don't know)*. Rather stick with the activity context. –  Dec 21 '11 at 18:17

2 Answers2

5

Because TCPdumphandler does not extend from Activity. getBaseContext() is a method of that class (technically, of the ContextWrapper class). You need to pass the context to the constructor of TCPdumphandler.

dmon
  • 30,048
  • 8
  • 87
  • 96
0

The getContext() methods can be called only from classes that extends Activities and Services (and, but I'm not sure, Application). To use context in other classes you should pass a context as a parameter.

Yury
  • 20,618
  • 7
  • 58
  • 86