0

I have created an activity in which I implemented a recycler view adapter. I have also created a second activity which should add a value into a SharedPreferences. After that, I want to change the text of a textView based on value of that SharedPreferences. But when I try to set text of that it doesn't work, it doesn't even add a default value of SharedPreferences.

The code inside of a activity which saves the data on click:

public void Done(View view){

        SharedPreferences mPreferences = 
        mContext.getSharedPreferences("Checker",MODE_PRIVATE);
        SharedPreferences.Editor mEditor = mPreferences.edit();

        mEditor.putString("Day1", "complete");
        mEditor.apply();

        //mRecyclerView.setAdapter(fitnessAdapter);

        fitnessAdapter.notifyDataSetChanged();

The code inside of a recycler view adapter: (just the ViewHolder where I use the code)

public class MultiAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private OnNoteListener mOnNoteListener;
    private Context context;

    public MultiAdapter(List<myObject> Parts, OnNoteListener onNoteListener, Context context) {
        this.items = Parts;
        this.mOnNoteListener = onNoteListener;
        this.context = context;}
     private Context context;

public class MainViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView segment;
        OnNoteListener mOnNoteListener;

        private MainViewHolder( View itemView, OnNoteListener onNoteListener, Context context) {
            super(itemView);
            segment = itemView.findViewById(R.id.segment_shredmas);

            SharedPreferences mPreferences = context.getSharedPreferences("Checker",MODE_PRIVATE);
            String daySelector = mPreferences.getString("Day1","Nothing");

            segment.setText("Day "+ daySelector);

            this.mOnNoteListener = onNoteListener;
            itemView.setOnClickListener(this);
        }
        @Override
        public void onClick(View v) {
            mOnNoteListener.onNoteClick(getAdapterPosition());
        }
    }
 @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.segment_shredmas, parent, false);
            return new ShredmasViewHolder(view, mOnNoteListener,[position] 1, [context]context);

PS : I tried both ways of SharedPreferences. But since the old one was the last one I left the code like that

Error messege :

E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@95326f7
E/: [ZeroHung]zrhung_get_config: Get config failed for wp[0x0102]
W/ZrHung.AppEyeUiProbe: Failed to get config from zrhung
Process: com.example....., PID: 15963
    java.lang.RuntimeException: Unable to pause activity {com.example...../com.example.....MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4742)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4691)
        at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4626)
        at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:45)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
        at com.example.....MainActivity.onPause(MainActivity.java:131)
        at android.app.Activity.performPause(Activity.java:7663)
        at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1536)
        at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4726)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4691) 
        at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4626) 
        at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:45) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
        at android.os.Handler.dispatchMessage(Handler.java:112) 
        at android.os.Looper.loop(Looper.java:216) 
        at android.app.ActivityThread.main(ActivityThread.java:7625) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
E/: [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]

EDIT : so I followed its track and it led me to another activity's media player for some reason, but when I deleted that and rerun the app another NullPointer PopedUp :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference so the problem is in the line

so the problem is in the line SharedPreferences mPreferences = mContext.getSharedPreferences("Checker",MODE_PRIVATE);

I know that the mContext is the one with nullException but when I wont use a Context in the code it will save it into different SharedPrefences. And when I want to load some SharedPreferences in recyclerView I have to reference context as I did in the code showed above so it will be in the group.

Kristian
  • 165
  • 2
  • 16
  • keys are different `Day1` and `ShredmasD1` – Pavneet_Singh Jan 16 '20 at 14:40
  • Keys are different I tried to change it if it will take at least the default value. But it doesnt even put the default value into the segment TextView which is weird. – Kristian Jan 16 '20 at 14:44
  • if you can't see `Day ` in your text view then it's the issue with your layout or adapter otherwise a flow issue – Pavneet_Singh Jan 16 '20 at 14:48
  • @Pavneet_Singh I can see `Day` but nothing else is added.. and the app keeps crashin on NullPointerException – Kristian Jan 16 '20 at 14:50
  • then something still needs to be initialised before use so the issue is completely different from the current posted one, follow stack trace and use debugging, will help you to fix the issue – Pavneet_Singh Jan 16 '20 at 14:53
  • @Pavneet_Singh So I tried to find the problem / solution but I could so I tried to extend the code with everything where did I use this SharedPreds with RecyclerView thing. Can you take a look at it please? – Kristian Jan 16 '20 at 18:25
  • The answer so far somehow missed that part: `NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference` ...even when closed, they still could be improved accordingly. – Martin Zeitler Jan 16 '20 at 18:37
  • @MartinZeitler Sir, I know that it keeps on crashin on NullPointerException when I ran the debbug it showed me, thats why I added the error code as well. But I dont know how to solve it. Even after readin the link about NullPointers. Can you write an example of the code or at least point me the right way? Thanks – Kristian Jan 16 '20 at 18:43
  • @Kristian well, the issue obviously is that the instance of `MediaPlayer` is `null` and you are attempting to get it's current position - which is the reason why it crashes. The code you've provided does not feature any `MediaPlayer` and is therefore rather irrelevant. I think that this should be fixable, when knowing what to look for. – Martin Zeitler Jan 16 '20 at 18:47
  • @MartinZeitler You were right, I used the search to find it in the app. I dont know why it does null pointer on totally different activity which works perfectly without it. I also added some of it to the *EDIT* at the very bottom to make it more readable. Can you take a look at that? – Kristian Jan 16 '20 at 19:07
  • @Kristian in that case `mContext` is `null`; depending where it is, `this` or `this.getContext()` might help... if you see the stack-trace, the other one issue as at `MainActivity.onPause()` - so you need to check if the instance of `MediaPlayer` not is `null` there, before trying whatever you do there. – Martin Zeitler Jan 16 '20 at 19:32
  • @MartinZeitler So I searched the internet and found the problem so I added some code to the activity `public Day1(Context context) { this.mContext = context; // receive the context here and now you can safely use it }` so it seems that the object is not empty but now it throws InstatiationException so how do I fix that? – Kristian Jan 17 '20 at 08:54

2 Answers2

1

Use mEditor.commit() instead mEditor.apply() to save your SharedPreferences.

Lucas Moretto
  • 404
  • 1
  • 6
  • 18
0

Your keys using getting and setting sharef prefs value are not the same so you change wrong text in Done method.

mEditor.putString("Day1", "complete"); String daySelector = mPreferences.getString("ShredmasD1","Nothing");

faranjit
  • 1,567
  • 1
  • 15
  • 22