关闭应用程序时,共享首选项列表视图不起作用 [英] Shared Preference List View Not Working When App Closed

查看:77
本文介绍了关闭应用程序时,共享首选项列表视图不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解listview如何为我创建的应用程序工作,我已经有了该应用程序来显示带有项目,图像和复选框的listview.

Im trying to learn how the listview works for an app im creating, I have got the app to show the listview with items, images and a checkbox.

我要实现的目标是:当他们单击复选框时,该状态将在下次打开应用程序时保存.我以为我的代码是正确的,但是我不确定我做错了什么,因为当我重新打开应用程序时,所有复选框都被检查回了false.

Im trying to achieve is: When they click the checkbox, that state is saved for the next time they open the app. I thought my code was correct but not sure what ive done wrong as when I re-open the app all the checkboxes are checked back to false.

任何帮助将不胜感激:)

Any Help would be appreciated :)

我的代码:适配器:

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();
}*/
}

推荐答案

如果您要使用SharedPreference管理您的产品,那么您可以这样做

If u want to manage ur product using SharedPreference than u can do like this

MainActivity.java

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;
    }


}

Adapter getView()方法:

Adapter getView() Method:

@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;

        }

    }

无需维护单个产品价值的共享首选项.

No need to maintain sharepreference for single product value.

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

Hope this will help u..if u still face problem we will find other way

这篇关于关闭应用程序时,共享首选项列表视图不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆