omini data omini data - 1 year ago 72
Android Question

nullpointer when using shared prefference in no activity class

so i am trying to use my shared prefference in a no activity class but i keep getting null pointer on my

private SharedPreferences setingPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE);

how do i solve this?

public class ConnectionClass
Context context;
private SharedPreferences setingPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE);
String ip;
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "ISTABLocalDB";
String un = "istab_wpf";
String password = "istab_!234";
public Connection CONN() {
ip = setingPreferences.getString("server", "");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
Connection conn = null;
String ConnURL = null;
try {
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
return conn;

Answer Source

You need to initialize your context variable. One way would be to pass the context variable from the activity class to this non-activity class by defining a constructor in the ConnectionClass

public ConnectionClass (Context context)  
   this.context = context;


Wherever you are going to instantiate this class, instantiate it by passing the context from the calling class.

For example, if you are instantiating this from an activity class, you can do so by

ConnectionClass conn = new ConnectionClass(MyActivity.this.getApplicationContext());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download