应用程序关闭时共享首选项列表视图不起作用

时间:2017-05-31 02:57:01

标签: android listview sharedpreferences baseadapter

我试图了解listview如何为我正在创建的应用程序工作,我已经让应用程序显示列表视图中的项目,图像和复选框。

我想要实现的是:当他们点击复选框时,该状态会在下次打开应用时保存。我认为我的代码是正确的,但不确定我做错了什么,因为当我重新打开应用程序时,所有复选框都被检回错误。

任何帮助将不胜感激:)

我的代码:适配器:

public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;


ListAdapter(Context context, ArrayList<Product> products) {
    ctx = context;
    objects = products;
    lInflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return objects.size();
}

@Override
public Object getItem(int position) {
    return objects.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.item, parent, false);
    }

   final Product p = getProduct(position);

    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    final CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
    SharedPreferences settings  = ctx.getSharedPreferences("data",ctx.MODE_PRIVATE);
    boolean Checked = settings.getBoolean(p.name, false);
    cbBuy.setChecked(Checked);



    cbBuy.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(cbBuy.isChecked()==true){
                SharedPreferences settings = ctx.getSharedPreferences("data",Context.MODE_PRIVATE);
                settings.edit().putBoolean(p.name, true).commit();
                Toast.makeText(ctx, "You Selected" + p.name, Toast.LENGTH_SHORT).show();


            }else{
                SharedPreferences settings = ctx.getSharedPreferences("data", Context.MODE_PRIVATE);
                settings.edit().putBoolean(p.name, false).commit();
                Toast.makeText(ctx, "You Deselected" +p.name, Toast.LENGTH_SHORT).show();

            }
        }
    });{

        return view;

    }

}

Product getProduct(int position) {
    return ((Product) getItem(position));
}

ArrayList<Product> getBox() {
    ArrayList<Product> box = new ArrayList<Product>();
    for (Product p : objects) {
        if (p.box)
            box.add(p);
    }
    return box;
}

OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView,
                                 boolean isChecked) {

        getProduct((Integer) buttonView.getTag()).box = isChecked;

    }


};
}

产品类别:

public class Product {
String name;
String price;
int image;
boolean isSelected = false;

public boolean isSelected() {
    return isSelected;
}
public void setSelected(boolean selected)
{
    isSelected = selected;
}


Product(String _describe, String _price, int _image, boolean _box) {
    name = _describe;
    price = _price;
    image = _image;
    isSelected = _box;
}


}

主要活动

public class MainActivity extends AppCompatActivity {

ArrayList<Product> products = new ArrayList<Product>();
ListAdapter boxAdapter;
private SharedPreferences mPrefs;
private String mData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    fillData();
    boxAdapter = new ListAdapter(this, products);

    ListView lvMain = (ListView) findViewById(R.id.lvMain);
    lvMain.setAdapter(boxAdapter);

}

void fillData() {
    products.add(new Product("Al", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Al", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alf", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfa", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfae", "5120%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfsdfsdfakher", "50435%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfasdfsdfkher", "5123120%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfasdfsdfkher", "501231%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfaksdfsdfher", "11250%", R.drawable.ic_launcher, false));
    /*for (int i = 1; i <= 20; i++) {
        products.add(new Product("Product " + i, i * 100,
                R.drawable.ic_launcher, false));
    }*/
}

/*public void showResult(View v) {
    String result = "Selected Product are :";
    int totalAmount=0;
    for (Product p : boxAdapter.getBox()) {
        if (p.box){
            result += "\n" + p.name;
            totalAmount+=p.price;
        }
    }
    Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
}*/
}

1 个答案:

答案 0 :(得分:1)

如果你想使用SharedPreference管理你的产品,你可以像这样做

MainActivity.java

public class MainActivity extends AppCompatActivity {

ArrayList<Product> products = new ArrayList<Product>();
ListAdapter boxAdapter;
private SharedPreferences mPrefs;
private String mData;
public static final String PREFS_NAME = "Product_Prefrence";

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

    products=getProductArray(this,"Products");
    if(products==null)
    { 
        fillData();
    }
    boxAdapter = new ListAdapter(this, products);

    ListView lvMain = (ListView) findViewById(R.id.lvMain);
    lvMain.setAdapter(boxAdapter);

}

void fillData() {
    products.add(new Product("Al", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Al", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alf", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfa", "5230%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfae", "5120%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfsdfsdfakher", "50435%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfasdfsdfkher", "5123120%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfasdfsdfkher", "501231%", R.drawable.ic_launcher, false));
    products.add(new Product("Alfaksdfsdfher", "11250%", R.drawable.ic_launcher, false));

}

  @Override
    public void onBackPressed() {
        saveProductArray(MainActivity.this,products,"Products");
        finish();
    }

    public void saveProductArray(Context c, List<Product> arrayList, String key) {

        SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        Gson gson = new Gson();
        String json = gson.toJson(arrayList);
        editor.putString(key, json).apply();

    }

    @NonNull
    public ArrayList<Product> getProductArray(Context c, String key) {

        Gson gson = new Gson();
        SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String json = settings.getString(key, "");
        Type type = new TypeToken<ArrayList<Product>>() {
        }.getType();
        ArrayList<Product> arrayList = gson.fromJson(json, type);

        return arrayList;
    }


}

适配器getView()方法:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = lInflater.inflate(R.layout.item, parent, false);
    }

   final Product p = getProduct(position);

    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    final CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);

//use click listener instead of checked change
cbBuy.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        if(objects.get(position).isSelected)
       {
              cbBuy.setChecked(false);
              objects.get(position).setSelected(false);

       }
       else
       {
              cbBuy.setChecked(true);
              objects.get(position).setSelected(true);

       }

    }
});


//For scrolling issue use this
if(objects.get(position).isSelected)
       {
              cbBuy.setChecked(true);

       }
       else
       {
              cbBuy.setChecked(false);
       }

            return view;

        }

    }

无需保持单一产品价值的共享偏好。

希望这会对你有所帮助。如果你仍然遇到问题,我们会找到其他方式