我正在编写一个简单的应用程序,要求我记住动态生成的所有复选框状态。
我尝试使用SharedPreferences来保存这些状态,我使用了recyclelerview,因此我已经定义了我的共享偏好以及扩展Activity的mainactivity中的所有内容。
一切都很好,现在我试图通过尝试引用MainActivity.data
在我的Adapter类中使用它,但没有运气。
MainActivity相关代码:
public class MainActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static String FILENAME = "AnimeConfig";
public SharedPreferences data = getSharedPreferences(FILENAME, 0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetAnime().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
}
private class GetAnime extends AsyncTask<Void, Void, Void> {
private String animeUrl = "http://www.animeseason.com/anime-list";
public List<String> animes = new ArrayList<String>();
@Override
protected Void doInBackground(Void... params) {
try {
Document document = Jsoup.connect(animeUrl).get();
Elements elements = document.select("div.series_alpha span");
for (Element element : elements) {
animes.add(element.previousElementSibling().text());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
mAdapter = new MyAdapter(animes);
mRecyclerView.setAdapter(mAdapter);
}
}
MyAdapter相关代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public CheckBox mCheckbox;
public ViewHolder(CheckBox v) {
super(v);
mCheckbox = v;
}
}
public MyAdapter(List<String> animes) {
mDataset = animes;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
CheckBox v = (CheckBox) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mCheckbox.setText(mDataset.get(position));
holder.mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
String animeName = buttonView.getText().toString();
SharedPreferences.Editor editor = MainActivity.data.edit();
}
}
});
}
@Override
public int getItemCount() {
return mDataset.size();
}
}
我不明白为什么我不能使用MainActivity.data
。
答案 0 :(得分:0)
您应该将SharedPreferences数据声明为静态,以便您可以从其他类访问它。
但我更喜欢使用帮助程序类为我做所有这些工作
类似的东西:
public class GeneralHelper {
public static SharedPreferences getSharedPrefrence(Context contextversion) {
//do the code for getting SharedPreferences
}
}