-1

Here is my LogcatI want to store a string value that is inside an if block and i want to access the value outside of it. Now i tried with this code but it is giving me error and app force closed by saying "Print ln needs a message". It is a broadcast receiver class and this code is in OnReceive method. I tried with this code:

if (!available)
for (String key : contactNumber.keySet()) {
   String msgSender = contactNumber.get(key);
   extractedContact = Utilities.extractNumbers(key);
   preferences = context.getSharedPreferences("progress",Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = preferences.edit();
   editor.putString("number", extractedContact);
   editor.apply();
   }

String showNumber = preferences.getString("number", "");
Toast.makeText(context, showNumber + "Hello",   Toast.LENGTH_LONG).show();

Now I just want to store that extracted contact value in shared pref and then I am retrieving it outside an if Blocks but it is giving me error. Can anyone know whats the issue? How can i retrieve the stored value

Arslan Ali
  • 371
  • 5
  • 20

3 Answers3

1

try to add below line before getting value from preferences.

as below,

      preferences = context.getSharedPreferences("progress",Context.MODE_PRIVATE);
     String showNumber = preferences.getString("number", "");
     Toast.makeText(context, showNumber + "Hello",   Toast.LENGTH_LONG).show();
Vickyexpert
  • 3,147
  • 5
  • 21
  • 34
0

It means Preference not initialized, there is need intialize out of

for (String key : contactNumber.keySet()) {
..
}

So,

       if (!available)
    {
   preferences = context.getSharedPreferences("progress",Context.MODE_PRIVATE);

        for (String key : contactNumber.keySet()) {
           String msgSender = contactNumber.get(key);
           extractedContact = Utilities.extractNumbers(key);

           SharedPreferences.Editor editor = preferences.edit();
           editor.putString("number", extractedContact);
           editor.apply();
           }

        String showNumber = preferences.getString("number", "");
        Toast.makeText(context, showNumber + "Hello",   Toast.LENGTH_LONG).show();

    ...
    }// if (!available) close bracket

thanks..

Kush
  • 1,080
  • 11
  • 15
-3

Replace this line of code

editor.apply();

by

editor.commit();

Sats
  • 875
  • 6
  • 12
  • Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. – Aman Jain Jun 27 '16 at 09:27