Problems using string for resources

Asked

Viewed 150 times

3

I’m creating an app quiz, the link is https://github.com/luisbalmant/QuickQuiz-Science.

I’m trying to use the getString(R.string.nome) to migrate the java class strings and then be able to use 2 languages.

In other places I managed to pull the strings and is working showing the texts when I run the app on mobile, but the moment I try to use the string in questions the app simply does not open more.

public class Questions {

        public String mQuestions[] = {

// Funciona
                "Pergunta número 1 xxxxxxx",

// NÃO FUNCIONA
                getString(R.string.Q1_function_insulin),

        };

=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=//=/=/=/=/=/=/=/=

Updating:

I made the following changes and it didn’t work:

My Mainactivity.java:

public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions;

    private String mAnswer;
    private int mScore = 0;
    private int mQuestionsLength;

    Random r;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mQuestions = new Questions(this);
        mQuestionsLength = mQuestions.mQuestions.length;

        r = new Random();

My other Questions.java file

import android.content.Context;

public class Questions extends MainActivity {

    Context context;
    public Questions(Context context)
    {
        this.context = context;
    }

    public String mQuestions[] = {

            "Pergunta número 1 xxxxxxx",
            context.getString(R.string.Q1_function_insulin),
            "Outra Pergunta número 2",

    };

3 answers

1

Try this way:

public class Questions {

    private Context context;
    private Integer[] mQuestions = new Integer[]{R.string.Q1_function_insulin, R.string.Q2_any_name};

    public Questions(Context context) {

        this.context = context;
    }

    public String get(int q_number) {
        String question = null;
        try {
            question = context.getString(mQuestions[q_number - 1]);
        } catch (IndexOutOfBoundsException e) {
            Log.e("Question", "Invalid question number: " + q_number);
        }
        return question;
    }
}

In Oncreate declare the class Questions:

Questions mQuestions = new Questions(this);

Get the questions:

String question1 = mQuestions.get(1); //obtém a questão 1 e assim por diante...

0

The answers already contained can solve the problem, but see below a logical explanation regarding the problem.

The getString() is a method that is contained in the abstract class Context. The reason it’s not working is because you don’t extend this class in the method Questions.

For example, if you create your class public class Questions extends Activity, will function correctly within the method onCreate. See below the scheme:

Activity
    |
    +----> extends ContextThemeWrapper
                       |
                       +----> extends ContextWrapper 
                                        |
                                        +----> extends Context 

Like you said yourself, "In the other places I managed to pull the strings...", precisely because these "..other places.." you are correctly extending the class that contains the method you are using.

Now the solution, there are several, as you can see the answers in your question.

  • Even doing so the problem will continue to exist if the class Questions is instantiated at the time it is declared (as attribute), in this case so private Questions mQuestions = new Questions(this);. The problem is that at that point the context is null. The only solution is to instantiate it in the onCreate() or in another place after it.

  • @ramaral so I said "within the onCreate method". = D

  • Yes but in that case you do not need to pass the contex. The class Questions, as it is a Inner class(not Static) of Activity, you have access to the context/Activity method. All your explanation does not apply in this context.

  • @ramaral The explanation is focusing on why the getString method didn’t work. Do you think it’s unnecessary to demonstrate this to the user?! I will leave the solution part disabled and then edit in a clearer form.

  • The reason, in this case, why getString() does not "work" is because Context is null. It is not because the class does not extend from Context or because one is not passed to the constructor.

  • @ramaral I think the two things right?!

  • It’s not. Look at the Jefferson answer, a context is passed and it still won’t work.

  • Hello ramaral and @acklay. First thank you for all the explanations. I’m starting learning now and from what I understand here and reading in some materials I saw that a possible solution is to instantiate it in onCreate(), but I don’t know how to do that. I tried several things, but as I am learning I read and I go in the code and "kick" and keep going wrong. Is there any simpler alternative than me suddenly relocating or redoing my public String mQuestions[] = {... ?

  • @Luísbalmant I tested the Questions class and it works by making the changes I mentioned in my reply, which is no more than instantiating it in onCreate(). If it doesn’t work, it’s because you now have another error (I haven’t tested your entire code). Add a comment with the error.

  • @ramaral, thanks for your attention and patience. I’m not sure if I could find the error but I think it’s as follows: Error running Questions: The Activity 'Questions' is not declared in Androidmanifest.xml

  • I added in Androidmanifest.xml the following: <Activity android:name=". Questions" /> and a message appears that does not have a default constructor

  • @Luísbalmant I think I ended up confusing you and totally messing up your head. It’s hard to even explain here. Ramaral’s response is the most appropriate for your case. I gave just one example of how it could work extending the Activity class in its Questions class; Try to do it calmly, read a little more and understand the life cycle of how an Activity works; know the concept of Abstraction, Encapsulation and Inheritance?! Try to read a little more to understand better. I think it will buy more time instead of trying to go kicking. Soon you will laugh at your own questions. he

  • @acklay. Thank you, I will do what you recommended. The worst was that I took another tip and now my code is all messed up... I have to deliver this in the course I’m doing and tried to use strings to support 2 languages... But the way it is, I’d better do it without strings and then do it without kicking. I will take your advice and read the concepts, because I don’t know how it works. Thank you for your help. It is very good to know that the programming "people" help themselves so much. Thanks, hug. When I solve I come back here and put the solution.

Show 8 more comments

0

At the time you are using the method getString() the context is null.

Note that you are instantiating the Questions class at the time of the declaration.

public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions = new Questions();

    private String mAnswer;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        r = new Random();
        ...
        ...
    }
    ...
    ...
} 

Although Activity indirectly extends Context, the implementation is delegated to a Context that is passed to the constructor.
How initialization is done in the field declaration,

private Questions mQuestions = new Questions();

it is done before the constructor is executed, hence Context is null.

To solve create the instance in the method onCreate():

public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions;

    private String mAnswer;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mQuestions = new Questions();

        r = new Random();
        ...
        ...
    }
    ...
    ...
} 
  • Hello, thank you for your attention. I tried to make the changes "private Questions mQuestions;" and "mQuestions = new Questions();" but I was unsuccessful. I wonder where I could be more wrong?

  • If you’ve made the changes I’ve indicated, it has to work, unless now you have another mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.