Si8
Si8

Reputation: 9235

getResources() is throwing an error

I have the following code which is used for creating a custom ListView in my app with two tabs:

package com.test.testing;

import android.content.Context;
import android.text.Html;

public class SetRows {
    int image;
    String name;
    String id;

    public int getImage () {
        return image;
    }

    public void setImage (int image) {
        this.image = image;
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public String getID () {
        return id;
    }

    public void setID (String id) {
        this.id = id;
    }

    public SetRows(int image, String name, String id) {

        super();
        this.image = image;
        this.name = Html.fromHtml(getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

}

The following line:

this.name = Html.fromHtml(getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;

gives me the following error:

The method getResources() is undefined for the type SetRows

Upvotes: 0

Views: 262

Answers (4)

DigCamara
DigCamara

Reputation: 5578

You need to change your code so you have a reference to the current context, which, in turn, will give you access to getResources.

For instance

public SetRows(Context currentContext,int image, String name, String id) {

        super();

        this.image = image;
        this.name = Html.fromHtml(currentContext.getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

You'd have to change the instantiation of the class to

contents.add(new SetRows(this,inIconShow, sColor, sExplain)); 

Upvotes: 1

Ahmad
Ahmad

Reputation: 72673

Pass in a Context through the constructor and call:

context.getResources(...);

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93902

getResources() is a method available for all classes that extends the Context class. Your class doesn't.

The common workaround is to pass an instance of your context when creating your SetRows object.

public SetRows(Context context, int image, String name, String id) {

        super();
        this.image = image;
        this.name = Html.fromHtml(context.getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

Then in your activity, you can just do :

new SetRows(this, /****/);

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39477

When you do

getResources()

it means

this.getResources()

Here this is an instance of SetRows (your class), and your class SetRows has no method named getResources.

This is what the error means.

Upvotes: 1

Related Questions