如何调用SharedPreference

时间:2013-06-28 09:27:08

标签: android

我正在尝试在我们的程序中使用Sharedpreference但是它给了我默认值,我正在尝试更多但却没有得到我犯的错误 我提供了所需的类和xml文件

package com.example.preferenceexample;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

  public class MainActivity extends Activity {
private static final int RESULT_SETTINGS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showUserSetting();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.settings, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId()) {

    case R.id.menu_settings:
        Intent i = new Intent(this, UserSettingActivity.class);
        startActivityForResult(i, RESULT_SETTINGS);
        System.out.println("prefrence Activity called");
        break;

    }

    return true;
}

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case RESULT_SETTINGS:
            showUserSetting();
            break;

        }

    }
  private void showUserSetting()
{
    SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(this);
    StringBuilder sb=new StringBuilder();
    sb.append("\n User Name : "+sp.getString("pref_Username",null ));
     sb.append("\n Send report: " + sp.getBoolean("prefSendReport", false));
     sb.append("\n Sync Frequency:  "+ sp.getString("prefSecFrequency",null));
     TextView settingsTextView=(TextView) findViewById(R.id.textView1);
     settingsTextView.setText(sb.toString());
}

 }




  public class UserSettingActivity extends PreferenceActivity {

  public void onCreate(Bundle bundle)
  {
    super.onCreate(bundle);
    addPreferencesFromResource(R.xml.settings);
  }

   }




    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
 <PreferenceCategory android:title="@string/pref_user_profile">
 <EditTextPreference 
   android:title="@string/pref_user_name"
   android:summary="@string/pref_user_name_summary"
   android:key="pref_Username"/> 
 </PreferenceCategory>
 <PreferenceCategory android:title="@string/pref_update_setting">
  <CheckBoxPreference
      android:defaultValue="false"
      android:key="prefSendReport"
      android:summary="@string/pref_send_report_summary"
      android:title="@string/pref_send_report"></CheckBoxPreference>
  </PreferenceCategory>
 <PreferenceCategory>
  <ListPreference
      android:title="@string/pref_sync_frequency"
      android:key="prefSecFrequency"
      android:summary="@string/pref_sync_frequency_summary"
      android:entries="@array/syncFrequency"
      android:entryValues="@array/syncFrequencyValues"
      />
  </PreferenceCategory>
  </PreferenceScreen>

4 个答案:

答案 0 :(得分:0)

您将“NULL”作为默认值,这是一个String对象,而不是您的null对象,不要使用双引号,它使String成为常量。

答案 1 :(得分:0)

这段代码只是展示了偏好的复兴。如果你想放置首选项,请使用:

sp.edit().putString("pref_Username", "Test").commit();

答案 2 :(得分:0)

当你将它们保存到设备时,可能是你做错了。

请看下面的示例方法并尝试..

public String getLastRostersDownloadedTime(String key) {
    SharedPreferences sp = context.getSharedPreferences("FILE_NAME", 0);
    String value = sp.getString(key, null);
    LogUtils.LOGE("Last Download Time ::", "" + value);
    return value;
}

public boolean saveLastRostersDownloadedTime(String key, String value) {
    SharedPreferences sp = context.getSharedPreferences("FILE_NAME", 0);
    Editor edit = sp.edit();
    edit.putString(key, value);
    LogUtils.LOGE("Updateding new Download Time ::", "" + value);
    return edit.commit();
}

其中context是活动上下文。所以应该在活动中调用这些方法。或者将活动上下文作为参数传递给这些方法。

答案 3 :(得分:0)

我认为以下代码适合您。 在类

下面声明这个

public static final String PREFS_NAME =“MyPrefsFile”;

接下来使用以下代码,你想要消费

SharedPreferences settings = getSharedPreferences(PREFS_NAME,0); firstStart = settings.getBoolean(“firstStart”,true);