使用 SharedPreferences 保存字符串
Posted
技术标签:
【中文标题】使用 SharedPreferences 保存字符串【英文标题】:Saving strings with SharedPreferences 【发布时间】:2014-12-25 21:52:20 【问题描述】:我正在尝试通过单击包含收藏夹的按钮创建一个列表视图。此列表视图项由 1 个图像、标题和副标题创建。
我的问题是这样的:似乎在保存将要的项目数的值时,它总是将值设为1,即使每次单击按钮(处于添加状态)这个变量被递增并存储在一个 sharedpreferences 中。
粘贴代码的重要部分:
List1(活动视图p的片段)
public class List1 extends Fragment
public String seleccion;
private Context context2;
private Activity act2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
context2 = getActivity().getApplicationContext();
act2 = this.getActivity();
View visor = inflater.inflate(R.layout.activity_principal, container, false);
ListView lista = (ListView) visor.findViewById(R.id.listadirectivos);
ArrayList<Directivo> arraydir = new ArrayList<Directivo>();
Directivo directivo;
// Forma 1: Introduzco los datos por orden alfab�tico
/*directivo = new Directivo(getResources().getDrawable(R.drawable.abccountry), "ABC ", "Country");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.abcjazz), "ABC ", "Jazz");
arraydir.add(directivo);*/
directivo = new Directivo(getResources().getDrawable(R.drawable.arrowclassicrock), "Arrow Classic Rock", "Rock");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.canalfiesta), "Canal Fiesta", "Radio Party");
arraydir.add(directivo);
directivo = new Directivo(getResources().getDrawable(R.drawable.cadenadial), "Cadena Dial", "Radio General");
arraydir.add(directivo);
//........
// Creo el adapter personalizado
AdapterDirectivos adapter = new AdapterDirectivos(act2, arraydir);
// Lo aplico
lista.setAdapter(adapter);
lista.setOnItemClickListener(new OnItemClickListener()
public void onItemClick(AdapterView<?> a, View v, int position, long id)
//Link con la radio: en general los que no van son MMS
String opcionSeleccionada =
((Directivo)a.getAdapter().getItem(position)).getNombre();
/*if (opcionSeleccionada == "ABC ") //no va
seleccion = "mms://a952.l11289754951.c112897.g.lm.akamaistream.net/D/952/112897/v0001/reflector:54951";
else if (opcionSeleccionada == "ABC ") //no va
seleccion = "mms://a134.l11289752133.c112897.g.lm.akamaistream.net/D/134/112897/v0001/reflector:52133";
*/
if (opcionSeleccionada == "Arrow Classic Rock") //va
seleccion = "http://91.221.151.155";
else if (opcionSeleccionada == "Canal Fiesta") //va
seleccion = "http://195.55.74.207/rtva/canalfiestaradio_master.mp3?GKID=3bfcb56203a811e4a80500163e914f69";
else if (opcionSeleccionada == "Cadena Dial") //va
seleccion = "http://194.169.201.177:8085/liveDial.mp3";
//............
Intent i = new Intent(context2, Radio.class);
i.putExtra("seleccion", seleccion);
i.putExtra("opcionSeleccionada", opcionSeleccionada);
startActivity(i);
);
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) visor.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return visor;
//“opcionSeleccionada”是ListView的其中一项的标题名称(用于之后创建listview),这里“选择”不重要
广播(活动)
public class Radio extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener
private int j=0;
private int i=0;
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private boolean dejaractivado=false;
private Button play;
private ToggleButton favs;
private Button stop;
private TextView textView;
boolean prevencion = false;
@Override
public void onCreate(Bundle icicle)
super.onCreate(icicle);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.TextView1);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
favs = (ToggleButton) findViewById(R.id.favs);
play.setOnClickListener(new View.OnClickListener()
public void onClick(View view)
play();
);
favs.setOnClickListener(new View.OnClickListener()
public void onClick(View view)
if(favs.isChecked())
addfavs();
else
delfavs();
);
stop.setOnClickListener(new View.OnClickListener()
public void onClick(View view)
stop();
);
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
private void play()
Bundle bundle=getIntent().getExtras();
prevencion = true;
textView.setText("Conectando con la radio......");
Uri myUri = Uri.parse(bundle.getString("seleccion"));
try
if (mp == null)
this.mp = new MediaPlayer();
else
mp.stop();
mp.reset();
mp.setDataSource(this, myUri);
mp.setAudiostreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
catch (Throwable t)
Log.d(TAG, t.toString());
@Override
public void onPrepared(MediaPlayer mp)
Log.d(TAG, "Stream is prepared");
mp.start();
textView.setText("");
/* String aux = (String) MediaStore.Audio.Media.ARTIST;
textView.setText("Estas escuchando: "+aux);
textView.setText("");*/
j=1;
private void addfavs()
i++;
//Toast toast = Toast.makeText(getApplicationContext(), "Bien, metido", Toast.LENGTH_SHORT);
//toast.show();
Bundle bundle=getIntent().getExtras();
String str = bundle.getString("opcionSeleccionada"); // str = Nombre Radio
//String str2= wmbPreference.getString("opcionSeleccionada",str);
SharedPreferences shared = getSharedPreferences("guardar", 0);
SharedPreferences.Editor editor = shared.edit();
editor.putString("opcionSeleccionada"+i, str);
editor.remove("Status_size");
editor.putInt("Status_size", i);
editor.commit();// commit is important here.
private void delfavs()
//it is a prototype:
SharedPreferences shared = getSharedPreferences("guardar", 0);
SharedPreferences.Editor editor = shared.edit();
editor.remove("opcionSeleccionada"+i);
editor.commit();// commit is important here.
//String channel = (shared.getString("opcionSeleccionada", ""));
//Toast toast = Toast.makeText(getApplicationContext(), channel, Toast.LENGTH_SHORT);
//toast.show();
//Toast toast = Toast.makeText(getApplicationContext(), "Mal, sacado", Toast.LENGTH_SHORT);
//toast.show();
private void stop()
if(j==1)
textView.setText("");
mp.stop();
public void onDestroy()
textView.setText("");
super.onDestroy();
stop();
@Override
public void onStop()
textView.setText("");
super.onStop();
if(dejaractivado==false)
else
stop();
public void onCompletion(MediaPlayer mp)
stop();
("i"为收藏项的值,"opcionSeleccionadai"为每项的字符串名称title)
查看p(活动)
公共类 Viewp 扩展 FragmentActivity 实现 ActionBar.TabListener
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private Context context = this;
String[] channel = new String[100];
int i;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager);
// Initilization
/*context.getSharedPreferences("guardar", 0);
SharedPreferences shared = getSharedPreferences("guardar", 0);
i = shared.getInt("Status_size", 0);
for(int s=1;s<=i;s++)
channel[s] = (shared.getString("opcionSeleccionada"+s, ""));
*/
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.emisoras))
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.estilo))
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getResources().getString(R.string.favoritos))
.setTabListener(this));
/* for (int w=0; w<tabs.length-1; w++)
actionBar.addTab(actionBar.newTab().setText(tabs[w])
.setTabListener(this));
*/
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
@Override
public void onPageSelected(int position)
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
@Override
public void onPageScrolled(int arg0, float arg1, int arg2)
@Override
public void onPageScrollStateChanged(int arg0)
);
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
@Override
public void onResume()
super.onResume();
context.getSharedPreferences("guardar", 0);
SharedPreferences shared = getSharedPreferences("guardar", 0);
i = shared.getInt("Status_size", 0); //i siempre da 1
for(int j=0; j<i; j++)
channel[j] = shared.getString("opcionSeleccionada"+j, "");
这里,我加载保存在另一个类中的值
List3(Viewp的片段)
public class List3 extends Fragment
public String seleccion;
private Context context;
private Activity act;
private String[] myValue;
private int y=0;
private boolean primeravez=true;
//private TextView estilo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View rootView = inflater.inflate(R.layout.activity_principal3, container, false);
context = getActivity().getApplicationContext();
act = this.getActivity();
Directivo directivo;
ArrayList<Directivo> arraydir2 = new ArrayList<Directivo>();
AdapterDirectivos2 adapter2 = new AdapterDirectivos2(act, arraydir2);
Viewp viewp = (Viewp)getActivity();
myValue = new String[viewp.channel.length];
for (int k=0; k<myValue.length; k++)
myValue[k]=viewp.channel[k];
for(int i=0; i<myValue.length;i++)
if(myValue[i]!=null)
if (myValue[i].equals("Esencia Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.esenciaradio), "Esencia Radio", "Radio General");
else if (myValue[i].equals("I love FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.ilovefm), "I Love FM", "Radio General");
else if (myValue[i].equals("Los 40 Principales"))
adapter2.addItem(getResources().getDrawable(R.drawable.los40principales), "Los 40 Principales", "Radio General");
else if (myValue[i].equals("RAC 105"))
adapter2.addItem(getResources().getDrawable(R.drawable.rac105), "RAC 105", "Radio General");
else if (myValue[i].equals("Sky FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.skyfm), "Sky FM", "Radio General");
else if (myValue[i].equals("Styl FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.stylfm), "Styl FM", "Radio General");
else if (myValue[i].equals("Cocktelera Blues"))
adapter2.addItem(getResources().getDrawable(R.drawable.cocktelerablues), "Cocktelera Blues", "General Blues");
else if (myValue[i].equals("Q fm"))
adapter2.addItem(getResources().getDrawable(R.drawable.qfm), "Q fm", "Jazz/Soul/Blues/Funky");
else if (myValue[i].equals("Radio Clásica RNE"))
adapter2.addItem(getResources().getDrawable(R.drawable.radioclasicarne), "Radio Clásica RNE", "Música Clásica");
else if (myValue[i].equals("Koffee FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.koffeeradio), "Koffee FM", "Chill out");
else if (myValue[i].equals("Ibiza Global Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.ibizaglobalradio), "Ibiza Global Radio", "House/Dance/Electrónica");
else if (myValue[i].equals("Maxima FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.maximafm), "Maxima FM", "Dance/Música Electrónica");
else if (myValue[i].equals("Cadena Latino"))
adapter2.addItem(getResources().getDrawable(R.drawable.cadenalatino), "Cadena Latino", "Latino/Flamenco");
else if (myValue[i].equals("Chanquete FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.chanquetefm), "Chanquete FM", "Flamenco");
else if (myValue[i].equals("Flamenco Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.flamencoradio), "Flamenco Radio", "Flamenco");
else if (myValue[i].equals("HotMix Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.hotmixradiofunky), "HotMix Radio Funky", "Funky Mix");
else if (myValue[i].equals("Sublime FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.sublimefm), "Sublime FM", "Jazz/Soul/Funk/Lounge");
else if (myValue[i].equals("Mix Radio House"))
adapter2.addItem(getResources().getDrawable(R.drawable.mixradiohouse), "Mix Radio House", "House");
else if (myValue[i].equals("Jazz Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.jazzradio), "Jazz Radio", "Jazz");
else if (myValue[i].equals("SmoothJazz Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.smoothjazz), "SmoothJazz Radio", "Smooth Jazz");
else if (myValue[i].equals("Canal Fiesta"))
adapter2.addItem(getResources().getDrawable(R.drawable.canalfiesta), "Canal Fiesta", "Pop");
else if (myValue[i].equals("Sky FM "))
adapter2.addItem(getResources().getDrawable(R.drawable.skyfmreggae), "Sky FM ", "Reggae");
else if (myValue[i].equals("Arrow Classic Rock"))
adapter2.addItem(getResources().getDrawable(R.drawable.arrowclassicrock), "Arrow Classic Rock", "Rock");
else if (myValue[i].equals("HotMix Radio Rock"))
adapter2.addItem(getResources().getDrawable(R.drawable.hotmixradiorock), "HotMix Radio Rock", "Rock");
else if (myValue[i].equals("Rock FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.rockfm), "Rock FM", "Rock");
else if (myValue[i].equals("Rock FM Classic"))
adapter2.addItem(getResources().getDrawable(R.drawable.rockfmbelgie), "Rock FM Classic", "Classic Rock");
else if (myValue[i].equals("Virgin Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.virginradio), "Virgin Radio", "Rock/Hard-Rock");
else if (myValue[i].equals("Trance FM"))
adapter2.addItem(getResources().getDrawable(R.drawable.trancefm), "Trance FM", "Trance");
else if (myValue[i].equals("M80 Radio"))
adapter2.addItem(getResources().getDrawable(R.drawable.m80radio), "M80 Radio", "Best of 70s/80s/90s");
但是,字符串myValue[]的Vector,和channel[]一样,好像只有1个位置,其他的值都是空的。因此,我认为在所有过程的某一时刻,“i 或 Status_size”值被重新声明或发生了一些罕见的事情。
【问题讨论】:
【参考方案1】:首先我要假设 channel[] 真的是private String channel[]
你真的应该发布所有相关代码,包括所有数组的所有初始化声明,因为此时我不知道你的通道数组的大小。
i = shared.getInt("Status_size", 0); //i siempre da 1
channel[i] = (shared.getString("opcionSeleccionada"+i, ""));
在上面的代码中,您声明您正在加载来自上一个活动的所有值。但此代码仅加载 1 个值。它将键 "opcionSeleccionada"+i
处的字符串加载到通道数组的位置 i
中。因此,如果这是您填充通道数组的唯一位置,那么它将永远只有 1 个值。
要解决此问题,您需要像在片段中那样使用循环来使用共享首选项映射中的正确值填充数组
for(int j=0; j < i; j++)
channel[j] = shared.getString("opcionSeleccionada"+j, "");
在 addFavs() 里面做这个
private void addfavs()
SharedPreferences shared = getSharedPreferences("guardar", 0);
int i = shared.getInt("Status_size", 0);
i++;
//Toast toast = Toast.makeText(getApplicationContext(), "Bien, metido", Toast.LENGTH_SHORT);
//toast.show();
Bundle bundle=getIntent().getExtras();
String str = bundle.getString("opcionSeleccionada"); // str = Nombre Radio
//String str2= wmbPreference.getString("opcionSeleccionada",str);
SharedPreferences.Editor editor = shared.edit();
editor.putString("opcionSeleccionada"+i, str);
//you do not need to remove a value from shared preferences. If you use the same key then it gets overridden
//editor.remove("Status_size");
editor.putInt("Status_size", i);
editor.commit();// commit is important here.
您可以将i
作为成员变量删除,并确保在 deleteFavs 方法中以相同的方式设置它
【讨论】:
感谢您的回答。不,通道不是私有变量(因为之后我需要在 List3 中使用它,如果我使用通道私有,我在 List3 上看不到这个值)。关于“for”我证明了这一点,但它仍然不起作用(我也相信你不需要“for”,因为我把这段代码放在 onRestart(方法)中并且每次都会更新) 好的,所以频道是公开的。关键部分是它是 ViewP 活动中的字符串数组。您没有显示完整文件,因此有点难以理解。仍然在重新启动时,您只填充数组的一个值。而不是使用onRestart()
尝试使用onResume()
。您正在向 1 个活动中的共享首选项添加值,当您重新启动主要活动时,您只能从共享首选项中获得 1 个值。因此,您的字符串数组通道将只有 1 个值,并且由于您在片段中复制该数组,它也有 1 个值。如果您发布所有代码,请运行它并向您展示。
还是不行。我正在编辑我的帖子以显示我的所有文件。
现已上传。也许活动 Radio 的变量“i”是问题所在……(这是我的直觉告诉我的)
据我所知,您的假设似乎是正确的。在您的无线电活动的每个实例中,变量 i 将被重置为 0。我假设您的广播活动的每个实例都是不同的频道或其他内容,并且您单击的按钮是收藏频道的收藏按钮。您可以在 addFavs 中将 i 从共享首选项中初始化为 Status_size 的值。然后增加它并添加你最喜欢的。下班后我会再看一看,但试试看。【参考方案2】:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL", "myStringToSave").commit();
【讨论】:
以上是关于使用 SharedPreferences 保存字符串的主要内容,如果未能解决你的问题,请参考以下文章
将 ArrayList 保存到 SharedPreferences
如何将 SharedPreferences 中的数据保存并显示为列表?