如何在Android recyclerview上的共享首选项中保存和加载数据

时间:2018-08-13 08:07:46

标签: android android-recyclerview sharedpreferences

我在将数据存储到Android sharedpreferences上的recyclerview时遇到困难,在这里我想在从Intent流程输入后保存数据,并且还想在删除并重新加载多个列表后保存数据与sharedpreference

我的 KeranjangRVAdapter.java

package lestari.lestari.Keranjang;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import untag.tugasakhir.lestari.lestari.Home.HomeDetail.HomeDetailActivity;
import untag.tugasakhir.lestari.lestari.Keranjang.KeranjangModel;
import untag.tugasakhir.lestari.lestari.R;

public class KeranjangRvAdapter extends RecyclerView.Adapter<KeranjangRvAdapter.MyHolder>{
    private Context mContext ;
    SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    private static final String PREF_NAME   = "KERANJANG";

    List<KeranjangModel> list=  new ArrayList<>();

    public KeranjangRvAdapter(Context mContext, List<KeranjangModel> list) {

        this.mContext = mContext;
        this.list = list;

    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_keranjang_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        final KeranjangModel keranjangModel = list.get(position);

        holder.tv_name.setText(keranjangModel.getJudul());
        holder.tv_harga.setText(keranjangModel.getHarga());

        holder.tv_qty.setText(keranjangModel.getQty()+" x "+keranjangModel.getHargaSatuan());
        Glide.with(mContext).load(list.get(position).getThubnail())
                .into(holder.iv_img);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

        holder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.remove(position);
                notifyDataSetChanged();

            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        TextView tv_name,tv_harga,tv_qty, tv_delete;
        ImageView iv_img;

        public MyHolder(View itemView) {
            super(itemView);

            tv_name = itemView.findViewById(R.id.tv_nama_item);
            tv_harga = itemView.findViewById(R.id.tv_harga_item);
            tv_qty = itemView.findViewById(R.id.tv_qty_item);
            iv_img = itemView.findViewById(R.id.iv_img);
            tv_delete = itemView.findViewById(R.id.tv_delete_item);
        }
    }



    public void UpdateData(int position,KeranjangModel keranjangModel){

        list.remove(position);
        list.add(keranjangModel);
        notifyItemChanged(position);
        notifyDataSetChanged();
    }
}

我已将其应用到下面的KeranjangActivity,但是对于删除过程,数据无法正常工作

我的 KeranjangActivity.java

package lestari.lestari.Keranjang;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import untag.tugasakhir.lestari.lestari.Config.URL;
import untag.tugasakhir.lestari.lestari.R;

public class KeranjangActivity extends AppCompatActivity {
    List <KeranjangModel> list;
    RecyclerView recyclerView;
    KeranjangRvAdapter adapter;

    SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    private String judul, harga,hargaSatuan, gambar, deskripsi, diskon, totHargaRP, qty, kode_barang, cek;

    private static final String PREF_NAME   = "KERANJANG";

    private Button btn_hapus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_keranjang);

        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        this.setTitle("Keranjang");

        //load keranjang
        loadKeranjang();

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        btn_hapus = findViewById(R.id.keranjang_hapus);

        cek = getIntent().getExtras().getString("cek");
        //ambil data dari intent
        if (cek != "ada"){
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            adapter = new KeranjangRvAdapter(getApplicationContext(), list);
            recyclerView.setAdapter(adapter);
            judul  = getIntent().getExtras().getString("judul");
            harga = getIntent().getExtras().getString("harga");
            hargaSatuan = getIntent().getExtras().getString("hargaSatuan");
            gambar = getIntent().getExtras().getString("gambar") ;
//        deskripsi = getIntent().getExtras().getString("deskripsi") ;
//        diskon = getIntent().getExtras().getString("diskon") ;
            qty = getIntent().getExtras().getString("qty") ;
//        kode_barang = getIntent().getExtras().getString("kode_barang") ;
            //memasukkan ke list
            KeranjangModel keranjangModel = new KeranjangModel();
            keranjangModel.setJudul(judul);
            keranjangModel.setHarga(harga);
            keranjangModel.setHargaSatuan(hargaSatuan);
            keranjangModel.setQty(qty);
            keranjangModel.setThubnail(gambar);
            list.add(keranjangModel);
            adapter.notifyDataSetChanged();

            saveKeranjang();

        }

        btn_hapus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharedPreferences= getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
                editor = sharedPreferences.edit();
                editor.clear();
                editor.commit();
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void loadKeranjang() {
        sharedPreferences= getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = sharedPreferences.getString("mykeranjang",null);
        Type type = new TypeToken<ArrayList<KeranjangModel>>(){}.getType();
        list = gson.fromJson(json,type);
        if (list==null){
            list = new ArrayList<>();
        }
    }


    private void saveKeranjang() {
        sharedPreferences= getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString("mykeranjang",json);
        editor.apply();
    }

    @Override
    public boolean onSupportNavigateUp(){
        finish();
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

使用此类用于从Sharedprefrence保存和加载

    public class DataProccessor {

    public Context context;

    public DataProccessor(Context context){
        this.context = context;
    }

    public final static String PREFS_NAME = "package_prefs";

    public void setInt( String key, int value) {
        SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public int getInt(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getInt(key, 0);
    }

    public void setStr(String key, String value) {
        SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public String getStr(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getString(key,"DNF");
    }

    public void setBool(String key, boolean value) {
        SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public boolean getBool(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getBoolean(key,false);
    }
}

示例集并获得:

        DataProccessor dataProccessor = new DataProccessor(this);
        dataProccessor.setStr("key" , "value");

        String value = dataProccessor.getStr("key");