First time SharedPreferences use with GridView

大憨熊 提交于 2019-12-13 07:28:59

问题


This is my Apps Screenshoot :

There is two button in that GridView : +/-.

So what im gonna try is when i press "+" button or "-" button, the quantity is store in SharedPreferences.

But really im confused about this.

This is my code so far :

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

    }

I already see this tutorial. But im still getting confused. Please guide me step by step.

EDIT

This is 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 + "]";
    }
}

And this is the code inside 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));

        }
    }

回答1:


you are using custom array list of object than set propertie to it and on back press of application you can jsonify your object to string and store it in shared preference and at activity on create you can regenerate your object getting from shared preference. in activity 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.
        }

and in backPressed you can read data from adapter and jsonify it using json and put it in sharedPreference i hope you understand the login . clear preference after data set.




回答2:


Your issue is here:

holder.qty.setText(store);

It is clearly pointed out in your error log:

android.content.res.Resources$NotFoundException: String resource ID 0x1 at android.content.res.Resources.getText(Resources.java:1409) at android.widget.TextView.setText(TextView.java:4943)

store is an integer and setText is trying to look for a resource with this id. Use this instead.

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

Also, to reduce the complexity of shared preferences specific code you can use this library



来源:https://stackoverflow.com/questions/37110188/first-time-sharedpreferences-use-with-gridview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!