SharedPreferences第一次与GridView一起使用

时间:2016-05-09 07:41:53

标签: android gridview

这是我的Apps屏幕截图:

enter image description here

GridView中有两个按钮:+/-。

所以我要尝试的是当我按下“+”按钮或“ - ”按钮时,数量存储在SharedPreferences中。

但我真的很困惑。

到目前为止,这是我的代码:

package com.android.customer_blanjapasar.Utility;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.android.customer_blanjapasar.R;
    import com.squareup.picasso.Picasso;

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

    /**
     * Created by Leon on 5/3/2016.
     */
    public class CustomGridView2 extends BaseAdapter {
        private ArrayList<ListItem> listData;
        private LayoutInflater layoutInflater;
        private Context context;
        private String[] imageUrls;
        private int count = 0;
        int arrayCount[];
        SharedPreferences prefs ;
        SharedPreference sharedPreference;
        public CustomGridView2(Context context, ArrayList<ListItem> listData) {
            this.listData = listData;
            layoutInflater = LayoutInflater.from(context);
            this.context = context;
            sharedPreference = new SharedPreference();
        }

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

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

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

        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.afterlogin_product_gridview, null);
                holder = new ViewHolder();
                holder.headlineView = (TextView) convertView.findViewById(R.id.nama_produk);
                holder.teaserView = (TextView) convertView.findViewById(R.id.harga);
                holder.imageView = (ImageView) convertView.findViewById(R.id.img_produk);
                holder.cmdMinus = (Button) convertView.findViewById(R.id.btn_min);
                holder.cmdPlus = (Button) convertView.findViewById(R.id.btn_plus);
                holder.qty = (TextView) convertView.findViewById(R.id.lbl_qty);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ListItem newsItem = listData.get(position);
            String satuan = newsItem.getSatuan().toString();
            String harga = newsItem.getReporterName().toString();
            harga = "Rp. " + harga + " / " + satuan;
            holder.headlineView.setText(newsItem.getHeadline().toUpperCase());
            holder.teaserView.setText(harga);

            String a = newsItem.getUrl();
            holder.cmdPlus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt( holder.qty.getText().toString());
                    count++;
                    holder.qty.setText(""+count);
                }
            });

            holder.cmdMinus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    count = Integer.parseInt( holder.qty.getText().toString());

                    if(count == 0) {
                        holder.qty.setText("0");
                    }
                    else {
                        count--;
                        holder.qty.setText("" + count);
                    }
                }
            });

            if (holder.imageView != null) {
                //new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
                Picasso
                        .with(context)
                        .load(a)
                        .fit()
                        .into(holder.imageView);
            }



            return convertView;
        }

        static class ViewHolder {
            TextView headlineView;
            TextView teaserView;
            ImageView imageView;
            TextView satuan,qty;
            Button cmdPlus,cmdMinus;
        }

    }

我已经看到了tutorial。但我仍然感到困惑。请一步一步指导我。

修改

这是ListItem.class:

public class ListItem {

    private String headline;
    private String reporterName;
    private String kode;
    private String url;
    private String satuan;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getHeadline() {
        return headline;
    }

    public void setHeadline(String headline) {
        this.headline = headline;
    }

    public String getReporterName() {
        return reporterName;
    }

    public void setReporterName(String reporterName) {
        this.reporterName = reporterName;
    }

    public String getKode() {
        return kode;
    }

    public void setKode(String kode) {
        this.kode = kode;
    }

    public String getSatuan() {
        return satuan;
    }

    public void setSatuan(String satuan) {
        this.satuan = satuan;
    }

    @Override
    public String toString() {
        return "[ headline=" + headline + ", reporter Name=" + reporterName + " , date=" + kode + "]";
    }
}

这是MainActivity.class中的代码:

public class AfterLogin_Produk extends Activity {
    Activity activity;
    ImageButton btn_resep,btn_product;
    static int jArray;
    GridView product_gridview;
    static String[] nama_prdct;
    static String[] img_prdct;
    static String[] harga_prdct;
    static String[] satuan_prdct;
    static String kode_ktgr;
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.after_login_produk_main);
        product_gridview = (GridView) findViewById(R.id.product_gridview);
        new GetLength().execute();
    }

public ArrayList<ListItem> getListData() {
        ArrayList<ListItem> listMockData = new ArrayList<ListItem>();

        for (int i = 0; i < jArray; i++) {
            ListItem newsData = new ListItem();
            newsData.setUrl(img_prdct[i]);
            newsData.setHeadline(nama_prdct[i]);
            newsData.setReporterName(harga_prdct[i]);
            newsData.setSatuan(satuan_prdct[i]);
            listMockData.add(newsData);
        }
        return listMockData;
    }


class GetLength extends AsyncTask<String, String, String> {
        String nama_product,img_product,harga_product,satuan_product;
        JSONParser2 jParser = new JSONParser2();
        ArrayList<String> list_nama_produk = new ArrayList<String>();
        ArrayList<String> list_img_produk = new ArrayList<String>();
        ArrayList<String> list_harga_produk = new ArrayList<String>();
        ArrayList<String> list_satuan_produk = new ArrayList<String>();
        protected String doInBackground(String... params) {
            try {
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("kode_kategori", kode_ktgr));
                JSONObject json = jParser.makeHttpRequest("http:xxx.php", "POST", param);
                JSONArray array = json.getJSONArray("categories");
                jArray = array.length();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject row = array.getJSONObject(i);
                    nama_product = row.getString("nama_produk");
                    img_product = row.getString("img_produk");
                    harga_product = row.getString("harga_satuan");
                    satuan_product = row.getString("nama_satuan");
                    list_nama_produk.add(nama_product);
                    list_img_produk.add(img_product);
                    list_harga_produk.add(harga_product);
                    list_satuan_produk.add(satuan_product);
                }
            } catch (Exception e) {
                System.out.println("Exception : " + e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //Toast.makeText(getBaseContext(),"Value : " + list_nama_kategori,Toast.LENGTH_SHORT).show();
            nama_prdct = new String[list_nama_produk.size()];
            img_prdct = new String[list_img_produk.size()];
            harga_prdct = new String[list_harga_produk.size()];
            satuan_prdct = new String[list_satuan_produk.size()];
            nama_prdct = list_nama_produk.toArray(nama_prdct);
            img_prdct = list_img_produk.toArray(img_prdct);
            harga_prdct = list_harga_produk.toArray(harga_prdct);
            satuan_prdct = list_satuan_produk.toArray(satuan_prdct);
            ArrayList<ListItem> listData = getListData();
            product_gridview.setAdapter(new CustomGridView2(AfterLogin_Produk.this, listData));

        }
    }

2 个答案:

答案 0 :(得分:0)

您正在使用对象的自定义数组列表而不是设置属性,并且在应用程序的背面按下您可以将对象jsonify为字符串并将其存储在共享首选项中,并且在创建活动时,您可以从共享首选项重新生成对象。在活动onCreate()

 SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
                (Dashboard.this);
        String data = mSettings.getString("data", "");
        /* Should Activity Check for Updates Now? */
        if ((data.equals(""))) {
//do nothing data is not in shared preference



        }
        else {
            //data is there convert To object
            data=mSettings.getString("data", "");
            Type listType = new TypeToken<ArrayList<ListRowItem>>() {
            }.getType();
            ArrayList<ListRowItem> listRowItems = new Gson().fromJson(data, listType);
//setAdapter coming for arrayList as usual.
        }

并且在backPressed中你可以从适配器读取数据并使用json对其进行jsonify并将其放在sharedPreference中  我希望你理解登录。数据集后明确偏好。

答案 1 :(得分:0)

您的问题在这里:

holder.qty.setText(store);

在错误日志中明确指出:

  

android.content.res.Resources $ NotFoundException:字符串资源ID   在android.widget.TextView的android.content.res.Resources.getText(Resources.java:1409)上有0x1。 setText (TextView.java:4943)

store是一个整数,setText正在尝试查找具有此id的资源。请改用它。

holder.qty.setText(store.toString());

此外,为了降低共享偏好设置特定代码的复杂性,您可以使用this library