我想將片段I傳遞給非活動類並將字符串轉換爲JSONObject。獲取字符串從片段到非活動類,然後轉換爲JSONObject
在我的片段我存儲的字符串,我需要在一個共享偏好
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.store_list, container, false);
//super.onCreate();
VolleyGet.getInstance(getActivity());
VolleyGet.getInstance().VolleyGET(domain, api, new CustomListener<String>(){
@Override
public void getResult(String result){
if (!result.isEmpty())
{
Log.e("storelist---------->", result);
SharedPreferences sp1=getActivity().getSharedPreferences("storeList", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp1.edit();
editor.putString("storeList", result);
editor.commit();
}
}
});
在我的非活性類我試圖獲取共享的偏好是這樣的:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder>{
Context context;
JSONArray storeArray;
SharedPreferences preferences = context.getSharedPreferences("storeList", Activity.MODE_PRIVATE);
String storeList = preferences.getString("storeList", "");
System.out.println("storelist", storeList);
storeArray = new JSONArray(storeList);
JSONObject jObj = storeArray.getJSONObject(0);
List<Movie> mItems;
public CardAdapter() {
super();
mItems = new ArrayList<Movie>();
Movie movie = new Movie();
movie.setName("this will come from the JSONObject");
movie.setThumbnail(R.drawable.will come from JSONObject);
mItems.add(movie);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.store_cardview, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
Movie movie = mItems.get(i);
viewHolder.tvMovie.setText(movie.getName());
viewHolder.imgThumbnail.setImageResource(movie.getThumbnail());
}
@Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imgThumbnail;
public TextView tvMovie;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView)itemView.findViewById(R.id.img_thumbnail);
tvMovie = (TextView)itemView.findViewById(R.id.tv_movie);
}
}
}
我在1.cannot解決符號println錯誤2.Unknown類:storelist 3.storearray也是未知的
請大家幫忙,謝謝!
你不能只在方法外println –
你真的需要適配器中的共享首選項嗎?爲什麼不能在創建適配器之前提取json數組/對象? –
@ cricket_007我可以在外面提取它,但我仍然想知道如何獲得課堂中的共享偏好,謝謝! – JerryKo