1

here is my code

Setting values in Preference:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;

        if(convertView == null){
            holder = new ViewHolder();
            convertView=inflater.inflate(resource, null);
            holder.tvItemName = (TextView) convertView.findViewById(R.id.tvItemName);
            holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
            holder.bLess = (Button) convertView.findViewById(R.id.bLess);
            holder.bAdd = (Button) convertView.findViewById(R.id.bAdd);
            holder.etItemQuantity = (EditText) convertView.findViewById(R.id.etItemQuantity);
            holder.bAddToCart = (Button) convertView.findViewById(R.id.bAddToCart);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvItemName.setText(itemModelList.get(position).getItemName());
        holder.tvPrice.setText("Rs " + itemModelList.get(position).getSalesRate());

        holder.bAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int qty = Integer.parseInt(holder.etItemQuantity.getText().toString().trim());
                qty++;
                holder.etItemQuantity.setText(""+qty);
            }
        });

        holder.bLess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int qty = Integer.parseInt(holder.etItemQuantity.getText().toString().trim());
                if(qty != 0){
                    qty--;
                    holder.etItemQuantity.setText(""+qty);
                }
            }
        });
        final String itemName = itemModelList.get(position).getItemName();
        final String salesRate = itemModelList.get(position).getSalesRate();


        holder.bAddToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putString("itemName", itemName );
                edit.putString("salesRate", salesRate );
                edit.commit();
                Toast.makeText(Items.this,"Added item to cart", Toast.LENGTH_LONG).show();
            }
        });
        return convertView;
    }

Retrieve data from preference:

public class CartDisplay extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row_cart_display);

    TextView tvItemName = (TextView) findViewById(R.id.tvItemName);
    TextView tvSalesRate = (TextView) findViewById(R.id.tvSalesRate);
    TextView tvTotalAmount = (TextView) findViewById(R.id.tvTotalAmount);


    SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
    String restoredText = prefs.getString("text", null);
    if (restoredText != null) {
        String itemName = prefs.getString("itemName", "No itemName defined");//"No name defined" is the default value.
        String salesRate = prefs.getString("salesRate", "0");//"0" is the default value.
        tvItemName.setText(itemName);
        tvSalesRate.setText("RS "+salesRate);
        tvTotalAmount.setText("Total: RS" +salesRate);
    }

}

Here is how the view looks

idk why my code dont work

  • iam trying to send itemname and salesrate to next activity but it wont display that in here it works if i use bundle or intents
  • also i want to store etItemQuantity value in sharedprefrences btw idk how make qty variable global so that i can store the value on addToCart button click

really need help here guys, here is my full code

Sooraj S
  • 291
  • 5
  • 13

5 Answers5

1

EDIT 2

Create Application class store qty variable there and access anywhere in app.

See example for creating application class


EDIT 1

As you were referring example if (restoredText != null) { might be used to check whether SharedPreference has value or not. user is trying to avoid checking null for every value. So he set one value for "text"

You are not setting text value just paste below code remove if statement .

 String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
 int idName = prefs.getInt("idName", 0); 

I think

 String restoredText = prefs.getString("text", null);

returning null so if statement is not executing

if (restoredText != null) { ...}
Community
  • 1
  • 1
N J
  • 27,217
  • 13
  • 76
  • 96
  • eh ? why will it return null i have putStrings in there – Sooraj S Aug 30 '16 at 11:27
  • where dud you set value for "text" in shared preference , you are only getting value for key "text" & default value is "null" – N J Aug 30 '16 at 11:28
  • Oh ohk iam sorry my mistake i have [fixed that](https://github.com/sooorajjj/KOT/commit/b5495a76c14a1d639e3f0f62bcfa2510b06544b5) can you please answer the 2nd part of my question – Sooraj S Aug 30 '16 at 11:40
  • if i can set Global Variable like that then i guess i dont need sharedpreferences ? – Sooraj S Aug 30 '16 at 11:54
  • Yes you don't need – N J Aug 30 '16 at 11:58
1

I have found some logic mistake in your code . Here it was

String restoredText = prefs.getString("text", null);
// you are trying to fetch the value of "text" but you had forgot to put /save the "text" value in your code 


SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putString("itemName", itemName );
            edit.putString("salesRate", salesRate );
            edit.commit();

Solution: put some value in "text" , during save and try to fetch again. Like this

SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putString("text", "text" );
            edit.putString("itemName", itemName );
            edit.putString("salesRate", salesRate );
            edit.commit();

String restoredText = prefs.getString("text", null);
if (restoredText.equals("text")) {
    String itemName = prefs.getString("itemName", "No itemName defined");//"No name defined" is the default value.
    String salesRate = prefs.getString("salesRate", "0");//"0" is the default value.
    tvItemName.setText(itemName);
    tvSalesRate.setText("RS "+salesRate);
    tvTotalAmount.setText("Total: RS" +salesRate);
}
anu
  • 213
  • 1
  • 3
  • 10
  • Hey thanks that fixed it can you answer the 2nd part of my question ? – Sooraj S Aug 30 '16 at 11:47
  • save the qunty value in share pref as like as itemName we stored and fetch using same process . – anu Aug 30 '16 at 11:56
  • cant assign qty as a final variable – Sooraj S Aug 30 '16 at 12:13
  • int value=Integer.parseInt(holder.etItemQuantity.getText().toString()); and then save in share pref. – anu Aug 30 '16 at 12:19
  • Thanks that worked , i have a few more questions on my current project you down to help ? we can possibly move this discussion to some better chat client , hangouts / gtalk / messenger , my mail sooorajjj@gmail.com or you can drop by your mail so i could reach out , thanks – Sooraj S Aug 30 '16 at 16:37
0

I think the problem is this line

 String restoredText = prefs.getString("text", null);
if (restoredText != null) { ... }

I don't see where you put this value in sharepreference and you check != null here so code in that block never be called.

MinWan
  • 94
  • 1
  • 5
  • Oh ohk iam sorry my mistake i have [fixed that](https://github.com/sooorajjj/KOT/commit/b5495a76c14a1d639e3f0f62bcfa2510b06544b5) can you please answer the 2nd part of my question – Sooraj S Aug 30 '16 at 11:41
0

Use following methods to get and set sharedPreferences:

static public boolean setPreference(Context c, String value, String key) {
    SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
    settings = c.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    return editor.commit();
}

static public String getPreference(Context c, String key) {
    SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
    settings = c.getSharedPreferences(PREFS_NAME, 0);
    String value = settings.getString(key, "");
    return value;
}
Nidhi
  • 777
  • 7
  • 17
0

I think you need to use application context while storing values in SharedPreference like this.

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    Editor editor = pref.edit();
Harman
  • 1,168
  • 1
  • 9
  • 19