我正在尝试在我们的程序中使用 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>