"Troubleshooting: Android - getSharedPreferences method not Resolving

Hello, I am facing an issue with getSharedPreferences not resolving. I have searched for solutions extensively but nothing seems to fix it. How can I implement getSharedPreferences in onclick inside ViewHolder?

Here is the code snippet from MyHolder.class:

 public class MyHolder extends RecyclerView.ViewHolder {

    TextView nametxt;
    ImageView img;
    TextView url;
    TextView channel;
    Context c;


    public MyHolder(View itemView) {
        super(itemView);


        nametxt= (TextView) itemView.findViewById(R.id.nameTxt);
        img= (ImageView) itemView.findViewById(R.id.movieImage);
        url= (TextView) itemView.findViewById(R.id.urltxt);
        channel= (TextView) itemView.findViewById(R.id.channel);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), VideoPlayerActivity.class);
                SharedPreferences prefs = getSharedPreferences("My_Prefs", MODE_PRIVATE);
                String user = prefs.getString("user", "");

                String urls= url.getText().toString()+user+user+channel.getText().toString();
                intent.putExtra("urls", urls);


                v.getContext().startActivity(intent);

            }
        });



    }




}

Answer №1

Revise the following code block:

SharedPreferences preferences = getPreferences("My_Preferences", MODE_PRIVATE);

Update it to:

SharedPreferences preferences = context.getPreferences("My_Preferences", MODE_PRIVATE);

Answer №2

Swap out this piece of code

SharedPreferences prefs = getSharedPreferences("My_Prefs", MODE_PRIVATE);

Give this alternative a shot using context, retrieve context from your view referenced as v

SharedPreferences prefs = v.getContext().getSharedPreferences("My_Prefs", MODE_PRIVATE);

Answer №3

One way to retrieve shared preferences is by using the context object, which can be accessed as v.getContext

Answer №4

this method is also effective.

SharedPreferences settings = getActivity().getSharedPreferences("My_Settings", MODE_PRIVATE);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

The reflight response received an unexpected HTTP status code of 500

Recently, I've been working on utilizing the Yelp Fusion API by making a simple ajax call. I started off by using the client_id and client_secret provided by Yelp to successfully obtain an access token through a 'POST' request in Postman, fo ...

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

Improved method for categorizing items within an Array

Currently working on developing a CRUD API for a post-processing tool that deals with data structured like: { _date: '3/19/2021', monitor: 'metric1', project: 'bluejays', id1: 'test-pmon-2', voltageConditio ...

Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file. My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this? app.js (function() { var app = angula ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. https://i.sstatic.net/8Yhaw.png The code snippet I have used is as follows: var db = require('./../routes/db'); ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Employing VUE.js for content retrieval

Is there an issue rendering 2 messages in vue.js on the front end? <template v-for="item in items"> <span>{{ afterpayMessage }}: {{ item.price }} with AfterPay</span> </template> <script> var afterpay = new Vue({ e ...

Getting open cv image on an android device

Looking to transmit a photo from OpenCV saved in a cv::Mat object to an Android phone and display it in an ImageView on the Android side. I have managed to send the photo data, receiving them as an array of integers (int[]) on Android. However, my issue ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

Retrieve particular data points from the object based on its unique identifier

Hey there, I'm facing an issue with Angular where I need to retrieve a specific object from an array based on its ID. I'm quite lost on how to approach solving this problem. var Obj = [ { Id: "1", shape: "circle", color: "red" }, { Id: " ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

Steps for generating instances of an HTML page and dynamically adding them to a list on the main page

I have a main HTML page and I need to insert a dynamically generated list from a template in another HTML file that I created. The template for each item in the list is located on a separate HTML page. My goal is to create multiple instances of this HTML ...

Waiting for the outcome of a function that calls itself repeatedly

The solve function provided here is designed to sort elements in an array based on their frequency and value. However, when dealing with longer input arrays, it encounters a 'Cannot read property' error which disrupts the sorting process. To add ...

Send the JSON file to the server by uploading it

Situation Currently, I'm dealing with a page comprising questions structured as shown below: sections:[{ section: 1, questions:[{ question: 1, attachment: [FormData Object] ... }, { question: 2, ...

"Seems like the Search View feature is failing to search through my

While the code below seems to be working fine, there is an issue with the search functionality. When attempting to search for a value, the application fails to respond as expected when typing letters into the searchview to filter the gridview. Regards, Kr ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

Clicking the identical button on multiple overlapping elements using Selenium and Node.js

Working with Selenium has presented a challenge when trying to close multiple HTML elements that share the same "close" button and overlap each other. The initial approach of looping through them individually to close seemed unsuccessful. The first step i ...

Introduction to Android Layouts for Beginners

As a beginner in Android development, I have encountered an issue with layouts. When I create my app in Eclipse, it looks great on a Nexus S (4 in., 480 x 800) and on my Exhibit 2 4G (3.7 in., 480 x 800), but it appears terrible on the Nexus 7. The buttons ...