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,438
  • 68
  • 55
  • 126
Tran Ngu Dang
  • 2,410
  • 6
  • 27
  • 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
  • 29,903
  • 7
  • 86
  • 95
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
  • 19,958
  • 7
  • 55
  • 85