显示存储在共享首选项

时间:2017-03-08 10:21:59

标签: android android-fragments android-recyclerview sharedpreferences

我有一个带有几件物品的recyclerview。当有人点击主片段中的某个项目时,它会存储在共享首选项中,然后所有单击的项目都应显示在另一个片段上。我的问题是当有人点击某个项目时,只有第一个被点击的项目会显示在另一个片段(详细信息片段)上,而不是项目列表。

这些是在我的SessionManager.class

上保存,检索和删除项目的方法
public void saveitems(Context context,List<SingleItem> items){

        Gson gson = new Gson();
        String cartitems = gson.toJson(items);
        editor.putString(KEY_ITEMS,cartitems);
        editor.commit();
    }

    public void grandtotal (String total){
        editor.putString(KEY_TOTAL,total);
        editor.commit();
    }

    public void savetocart(Context context, SingleItem singleitems){
        List<SingleItem>  itemList = getItems(context);

        if (itemList == null) {

                itemList = new ArrayList<>();
                itemList.add(singleitems);
                saveitems(context, itemList);

        }

    }

    public ArrayList<SingleItem>  getItems(Context context){
        List<SingleItem> items;

        if (pref.contains(KEY_ITEMS)){
            String cartitems = pref.getString(KEY_ITEMS,null);
            Gson gson = new Gson();
            SingleItem[] singleItems = gson.fromJson(cartitems,SingleItem[].class);

            items = Arrays.asList(singleItems);
            items = new ArrayList<>(items);

        }
        else
            return null;

        return (ArrayList<SingleItem>) items;
    }

    public void removeitem(Context context, SingleItem singleItem){
        ArrayList<SingleItem> items = getItems(context);

        if (items != null){
            items.remove(singleItem);
            saveitems(context,items);
        }
    }

这就是我存储已点击的项目的方式。看看(RecyclerItems):

package com.carlton.shop;


import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ss.com.bannerslider.banners.RemoteBanner;
import ss.com.bannerslider.views.BannerSlider;



/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends Fragment {
    private BannerSlider bannerSlider;
    private RecyclerView Categories;
    public RecyclerView RecyclerItems;
    private ShopItemAdapter adapter;
    private List<ShopItem> item;
    SessionManager sessionManager;
    private List<SingleItem> items;
    private SingleItemAdapter adapters;
    private LinearLayout Layoutcategories, Layoutitems;
    private TextView CatName;
    private Button Up;


    public MainFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        bannerSlider = (BannerSlider) view.findViewById(R.id.banner_slider1);
        Categories = (RecyclerView) view.findViewById(R.id.recyclercategories);
        Layoutcategories = (LinearLayout) view.findViewById(R.id.LayoutCategories);
        Layoutitems = (LinearLayout) view.findViewById(R.id.LayoutItems);
        RecyclerItems = (RecyclerView) view.findViewById(R.id.recycleritems);
        CatName = (TextView) view.findViewById(R.id.tvcategoryname);
        Up = (Button) view.findViewById(R.id.btnup);

        sessionManager = new SessionManager(getContext());

        Categories.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        Categories.setLayoutManager(layoutManager);

        RecyclerItems.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
        RecyclerItems.setLayoutManager(layoutmanager);

        Categories.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                Layoutcategories.setVisibility(View.GONE);
                Layoutitems.setVisibility(View.VISIBLE);

                sessionManager.createcategorysession(item.get(position).getCategory());
                HashMap<String, String> cat = sessionManager.getcategoryitems();

                CatName.setText(cat.get(SessionManager.KEY_CATEGORY));

                Up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Layoutitems.setVisibility(View.GONE);
                        Layoutcategories.setVisibility(View.VISIBLE);
                    }
                });


                items = new ArrayList<>(item.get(position).getItems());
                adapters = new SingleItemAdapter(getContext(),items);
                RecyclerItems.setAdapter(adapters);
                RecyclerItems.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            sessionManager.savetocart(getContext(), items.get(position));
                            Toasty.success(getContext(),"Added to cart",Toast.LENGTH_SHORT,true).show();


                    }

                }));

            }
        }));


        Banner();

        getdata();

        return view;
    }


    private void Banner() {
        bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
        bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
        bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
        bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));

    }


    private void getdata() {
        final ProgressDialog progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Loading Items...");
        progressDialog.show();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        InterfaceRequest request = retrofit.create(InterfaceRequest.class);
        Call<JSONResponse> call =request.getJSON();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

                if (response.isSuccessful()){

                    JSONResponse jsonResponse = response.body();

                    item = new ArrayList<>(jsonResponse.getItem());
                    adapter = new ShopItemAdapter(getContext(),item);
                    Categories.setAdapter(adapter);

                } else {
                    Toasty.warning(getContext(),"Oops! Items could not be loaded",Toast.LENGTH_SHORT,true).show();
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Toasty.error(getContext(),t.getLocalizedMessage(),Toast.LENGTH_SHORT,true).show();
                Log.d(Constants.TAG,t.getMessage());
                progressDialog.dismiss();
            }

        });

    }

}

这就是我在DetailsFragment上检索项目的方式;

package com.carlton.shop;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

import static com.helpshift.util.HelpshiftContext.getApplicationContext;


/**
 * A simple {@link Fragment} subclass.
 */
public class Details extends Fragment {
    private RecyclerView RecyclerDetails;
    private TextView CartPrice;
    private CheckBox CheckCart;

    private List<SingleItem> list;
    private CartAdapter adapter;
    private boolean add = false;
    private Paint p = new Paint();
    private SessionManager sessionManager;



    public Details() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_details, container, false);

        RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart);
        CartPrice = (TextView) view.findViewById(R.id.tvcart);
        CheckCart = (CheckBox) view.findViewById(R.id.chkcart);

        sessionManager = new SessionManager(getContext());

        RecyclerDetails.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        RecyclerDetails.setLayoutManager(layoutManager);
        list = sessionManager.getItems(getContext());

        RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        }));



        if(list != null){
            Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_LONG,true).show();
            adapter = new CartAdapter(getContext(),list);
            RecyclerDetails.setAdapter(adapter);
            }

        //initswipe();
        return view;
    }
}

1 个答案:

答案 0 :(得分:0)

在会话管理器中,使用savetocart()方法不对。

第一次调用时,getItems()将按预期返回null,因此下一行中的 if 语句将解析为 true ,并且项目将加上。但在此之后itemList不会为空,因此 if 语句将始终解析为<​​strong> false ,并且不会向列表中添加任何项目。

该方法应如下所示

public void savetocart(Context context, SingleItem singleitems){
    List<SingleItem>  itemList = getItems(context);

    if (itemList == null) {
       itemList = new ArrayList<>();
    }
    itemList.add(singleitems);
    saveitems(context, itemList);

}