Tran Ngu Dang
Tran Ngu Dang

Reputation: 2630

Why can't I use getBaseContext() here?

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?

Upvotes: 1

Views: 7914

Answers (2)

Yury
Yury

Reputation: 20936

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.

Upvotes: 0

dmon
dmon

Reputation: 30168

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.

Upvotes: 5

Related Questions