0

I'm new to creating apps on Android with Eclipse and having a little trouble doing certain things.

I'm currently trying to not have to repeat tasks over and over again, so instead do functions that can be called from any activity.

Making a new java file with a public class appears to work ok, but then certain things don't work.

package com.android.packagename;
import android.content.SharedPreferences;
public class Functions
{
public static final String PREFS_NAME = "PrefsFile";
SharedPreferences preferences;

public void loadPreferences()
{
    SharedPreferences preferences=getSharedPreferences(PREFS_NAME,0);
    String username = preferences.getString("username", "");
}
}

where I get the error of "The method getSharedPreferences(String, int) is undefined for the type Functions" and calling it by Functions.loadPreferences();

This code is absolutely fine when in the original Activity. I've tried adding this. etc onto the beginning but with no such luck. What am I missing?

Thanks

Yury
  • 20,618
  • 7
  • 58
  • 86
Richard Whitehouse
  • 679
  • 3
  • 14
  • 28
  • Read about static functions and a book about Java. Functions.loadPreferences() would be good when loadPreferences where static function. So summing up use either: static public void lP() or Functions f = new Functions(); f.lP(). – gregory561 Jul 10 '11 at 17:13
  • You might want to read over this question (http://stackoverflow.com/q/708012/778427) as well. This way, your global class will have a `Context`. – Glendon Trullinger Jul 10 '11 at 17:57

2 Answers2

0

The code works in Activity because Activity is derived from Context which is where getSharedPreferences() is defined

mibollma
  • 14,959
  • 6
  • 52
  • 69
0

Instead of

public void loadPreferences()
{
    SharedPreferences preferences=getSharedPreferences(PREFS_NAME,0);
    String username = preferences.getString("username", "");
}

use

public void loadPreferences(Context C)
{
    SharedPreferences preferences=C.getSharedPreferences(PREFS_NAME,0);
    String username = preferences.getString("username", "");
}

If the method you are trying to use is contained in some other class type then pass in the instantiated class object to make it useable from multiple activities etc.

If you call loadPreferences(this) from an activity that would then work, same kind of pattern for other things will work as well.

You are right though, Android takes a bit of thought to make things reusable

Idistic
  • 6,281
  • 2
  • 28
  • 38