我正在制作一个具有收藏夹功能的应用程序,用户可以在收藏夹列表中添加一个项目,并且我有一个listActivity可以显示收藏夹项目;我用这段代码将最喜欢的情况存储在sharedpreferences中
boolean[] favorite;
String[] storyTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
storyTitle = getResources().getStringArray(R.array.storyTitles);
favorite = new boolean [storyTitle.length];
SharedPreferences appPref = PreferenceManager.getDefaultSharedPreferences(this);
for(int x=0;x<storyTitle.length;x++){
String str ="subject_"+ String.valueOf(x);
favorite[x]= appPref.getBoolean(str, false);
}
}
当用户单击添加到收藏夹时,我有一种方法,通过将tat item设置为true可以添加到收藏夹; 但是当我想通过下面的代码显示带有喜欢的项目的ListActivity时;如果我的一项是假的; 其错误意外退出应用程序
String[] storyTitles;
String[] favorite;
int c=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
storyTitles=getResources().getStringArray(R.array.storyTitles);
favorite= new String[storyTitles.length];
doFav();
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,favorite));
}
public void doFav(){
int c=0;
SharedPreferences appPref = getSharedPreferences("Preference", MODE_PRIVATE);
for( int i=0 ; i<storyTitles.length;i++){
String str ="subject_"+String.valueOf(i);
boolean s = appPref.getBoolean(str,false);
if(s){
favorite[c]= storyTitles[i];
c++;
}
}
有什么问题?如果我评论这部分应用程序没有错误
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,favorite));
如果真值少于其最喜欢的数组,则最喜欢的数组可能具有null变量。
public void doFav(){
int c=0;
SharedPreferences appPref = getSharedPreferences("Preference", MODE_PRIVATE);
Vector<String>tmp = new Vector<String>();
for( int i=0 ; i<storyTitles.length;i++){
String str ="subject_"+String.valueOf(i);
boolean s = appPref.getBoolean(str,false);
if(s){
tmp.addElement(storyTitles[i]);
}
}
favorite = new String[tmp.size()];
tmp.copyInto(favorite);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句