0

In the first activity to load in my app I put my JSONArray into Sharedpreferences (as a String):

    //put myJsonArray into shared preferences file as a String
    //Convert back to Json later, in the adapter
    SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    //we want to edit SharedPreferences
    SharedPreferences.Editor editor = sharedPrefs.edit();
    //put the string value into SharedPreferences, with the key "key_value"
    editor.putString("key_value", myJsonArray.toString());
    //commit the string
    editor.commit();

I can get this string in another Activity and convert it back to a JSONArray easily with:

SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String json_array = sharedPrefs.getString("key_value", "0");
        try
        {
            JSONArray jsonArray = new JSONArray(json_array);

        } catch (JSONException e) {
            Log.e("MYAPP", "unexpected JSON exception", e);
        }

But when I put the above code in the onBindViewHolder of my adapter, or anywhere else in my adapter, I am getting: NullPointerException and my app crashes.

Please tell me how I can solve this.

Where it crashes it says:

 java.lang.NullPointerException at com.example.chris.tutorialspoint.SharedReviews.SharedPopulistoReviewsAdapter.onBindViewHolder(SharedPopulistoReviewsAdapter.java:130)

My onBindViewHolder code is:

 @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {


        SharedReview r = the_Shared_reviews.get(position);

        SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String json_array = sharedPrefs.getString("key_value", "0");
        try
        {
            JSONArray jsonArray = new JSONArray(json_array);
            System.out.println("SharedAdapter, the jsonarray is :" + jsonArray);


        } catch (JSONException e) {
            Log.e("MYAPP", "unexpected JSON exception", e);
        }

        ((ReviewHolder) viewHolder).category.setText("Category: " + r.getCategory());
        ((ReviewHolder) viewHolder).name.setText("Name: " + r.getName());
        ((ReviewHolder) viewHolder).phone.setText("Phone: " + r.getPhone());
        ((ReviewHolder) viewHolder).comment.setText("Your Comment: " + r.getComment());

        //set an onClick listener for the row, if it's clicked anywhere
        ((ReviewHolder) viewHolder).itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            //When the review is clicked in PopulistoListView
            //then show that review
            public void onClick(View v) {

                SharedReview sharedReview = (SharedReview) SharedPopulistoReviewsAdapter.getItem(position);

                //we want to pass the review_id of the sharedReview being clicked
                //to the ViewContact activity, and from there post it and get more
                //info for that sharedReview - address, comments etc
                Intent i = new Intent(v.getContext(), ViewContact.class);
                //pass the review_id to ViewContact class
                i.putExtra("review_id", sharedReview.getReviewid());
                v.getContext().startActivity(i);
            }

        });
    }

Line 130 is:

SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);
5
  • Suggest showing the code that crashes, not the code that's working. Include the stack trace and info so we can map the crash line number with your code snippets. Commented Apr 30, 2018 at 20:59
  • @JeffreyBlattman Edited my question. Commented Apr 30, 2018 at 21:06
  • 1
    did you make sure that context is no null? Commented Apr 30, 2018 at 21:18
  • I added now if (context != null) { code in here} and app doesn't crash any more, but it skips over the sharedpreferences part. Commented Apr 30, 2018 at 21:23
  • You can acquire the context from the viewHolder's view. Don't retain the context but instead use ((ReviewHolder) viewHolder).category.getContext() Commented Apr 30, 2018 at 21:34

1 Answer 1

3

This is happening because you have not initialized context. Either you must initialize context by passing context as a parameter when creating the object of the adapter or you can get the context from a view. To get the context from a view change the line to:

SharedPreferences sharedPrefs = ((ReviewHolder) viewHolder).category.getContext().getSharedPreferences("MyData", Context.MODE_PRIVATE);

Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct method to acquire a context. Do this.
thanks, working on it now, don't fully understand what's going on but no errors any more, although my system.out.print is giving no result, must need to initialize context, will mark as correct answer when solved.
Try using android.util.Log class static methods instead of System.out.print.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.