Andy
Andy

Reputation: 99

Value assigned remains null

Here is a piece of code which befuddles me: I have a String name reviewChoisi which carries a value (for instance review3). In the method below, I cannot use it to set the MediaPlayer mp:

    public void playCheck(){

    zoneAffichage = (TextView)findViewById(R.id.zone_trado_scrollable);
    maReponse = (EditText)findViewById(R.id.EditTextMaReponse);

    Resources res = getResources();

    final int resRaw = res.getIdentifier(reviewChoisi, "raw", getPackageName());

    final MediaPlayer mp = MediaPlayer.create(this, resRaw);

    final Button monBouton = (Button)findViewById(R.id.check);
    monBouton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {
                lireXMLSolution(reviewChoisi);
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            if ( maReponse.getText().toString().equalsIgnoreCase(laSolution) ) {
                mp.start();
                zoneAffichage.setText(Html.fromHtml("<font color=\"blue\">right</font>"));

            }
            else{
                zoneAffichage.setText(Html.fromHtml("<font color=\"red\">wrong</font>"));
            }

        }
    });
}

The crash happens at line

        final int resRaw = res.getIdentifier(reviewChoisi, "raw", getPackageName());

I tried tests with a variable son in various places, but it didn't change anything.

Help welcome.

Upvotes: 0

Views: 53

Answers (2)

Andy
Andy

Reputation: 99

Finally a solution was to put the use of reviewChoisi inside the body of onClick(View v) {...}, with the following code

final int resRaw = getResources().getIdentifier(reviewChoisi, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(ReviewActivity.this, resRaw);

Upvotes: 0

geokavel
geokavel

Reputation: 619

son is declared in the function playCheck, once you run that function, the variable is destroyed. Since onClick events will be occurring after the function has run, the son variable will already have been destroyed, and you won't be able to use it. You still have access to the other variables because, they are global variables. The reason the compiler requires son to be final for it to work is because, if it is final it's value won't change, so the program can save it's value and reuse it. However, my guess is that when you set son equal to reviewChoisi, reviewChoisi has not yet been created, so the value that get saved for son is null.

Upvotes: 1

Related Questions