2012-03-08 5 views
1

두 개의 사용자 설정 인 'radius'와 'cluster'를 저장하고 검색하는 단일 클래스를 만들려고합니다.Android SharedPreferences getSharedPreferences의 NullPointerException

'설정'활동을로드 할 때 널 포인터 예외가 발생합니다. 사용자 설정에서

발췌문 :

storage = new Persistence(); 
    radius = (EditText) findViewById(R.id.etRadius);   
    radius.setText(String.valueOf(storage.getRadius())); <-- Problem 

클래스 지속성을 다루는 :

public class Persistence extends Activity { 

    private static final String PREFERENCES = "tourist_guide_preferences"; 
    private SharedPreferences settings; 
    private SharedPreferences.Editor editor; 

    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     settings = getSharedPreferences(PREFERENCES, 0); 
     editor = settings.edit(); 
    } 

    public int getRadius() 
    { 
     return settings.getInt("radius", 2000); 
    } 

    public int getClusterSize() 
    { 
     return settings.getInt("cluster", 50); 
    } 

    public void setRadius(int radius) 
    { 
     editor.putInt("radius", radius); 
     editor.commit(); 
    } 

    public void setClusterSize(int size) 
    { 
     editor.putInt("cluster", size); 
     editor.commit();   
    } 
} 
+1

여기에서 체크 아웃하십시오. 가장 좋은 최상의 예제 http://stackoverflow.com/questions/5734721/android-shared-preferences –

답변

1

귀하의 Persistence 클래스는 Activity 안된다. 일반 클래스로 만들고이 일반 클래스 생성자 내에 onCreate 코드를 넣어야합니다. 이 같이하는

변경 :

public class Persistence { 

    private static final String PREFERENCES = "tourist_guide_preferences"; 
    private SharedPreferences settings; 
    private SharedPreferences.Editor editor; 
    private Context context; 


    public Persistence(Context context) 
    { 
     this.context = context; 
     settings = context.getSharedPreferences(PREFERENCES, 0); 
     editor = settings.edit(); 
    } 

    public int getRadius() 
    { 
     return settings.getInt("radius", 2000); 
    } 

    public int getClusterSize() 
    { 
     return settings.getInt("cluster", 50); 
    } 

    public void setRadius(int radius) 
    { 
     editor.putInt("radius", radius); 
     editor.commit(); 
    } 

    public void setClusterSize(int size) 
    { 
     editor.putInt("cluster", size); 
     editor.commit();   
    } 
} 

을 그리고 당신의 활동에, 당신은 인스턴스화이 같은이 Persistence 클래스 :

storage = new Persistence(this); 
+0

먼저 시도 했으므로 사용할 수 없습니다. 'getSharedPreferences'함수. 대신 내가 사용해야하는 다른 것이 있습니까? – Jack

+0

아마도 getSharedPreferences를 호출 할 컨텍스트가 없었을 것입니다. 이 메소드는 컨텍스트 변수에서 호출 할 수 있습니다. –

+0

감사합니다. 코드도 건배! +1 – Jack

1

저장 = 새 지속성(); 이것은 Persistence 활동의 onCreate를 호출하지 않습니다. 일반 수업을 만드는 것이 좋습니다. 컨텍스트 변수를 작성하여이를 사용하여 sharedpreference 인스턴스를 작성하십시오. 액티비티 클래스에서이 일반 클래스를 호출해야합니다.

+0

감사합니다. 작동합니다. +1 – Jack