Mark
Mark

Reputation: 1400

strange NullPointerException on String

I keep getting crashes recorded on GP developer console:

Caused by: java.lang.NullPointerException
at com.xyz.abc.quizstart.calctracks(SourceFile:690)

line 690 has this:

687     public void calctracks(){
688         TextView t = (TextView)findViewById(R.id.trackcounttext);
689         Spinner spin= (Spinner)findViewById(R.id.spinner1);
690         String val ="3"; 
691         questionsperplayer=3;
692         val = spin.getSelectedItem().toString();
693         if(val!=""){
694             questionsperplayer = Integer.parseInt(val);
695             totalrequiredquestionsandanswers=playerList.size()*questionsperplayer*4;
696             t.setText(totalrequiredquestionsandanswers + " music tracks required");
697         }else{
698             t.setText("");
699         }
700         
701     }

I cannot replicate NPE on emulator or on my two phones or tablet. Judging by the number of admob clicks I know many users are using the app fine without this issue. However I get about 8 of these a week.

Surely declaring a string and and setting a value to it cannot cause this?

Any ideas what to try?

Upvotes: 1

Views: 122

Answers (4)

allprog
allprog

Reputation: 16780

The source line the exception mentions is probably from a different version of the app. I suspect the issue is more likely in line 692 in your posted code. If getSelectedItem() returns null.

NOTE: if (val != "") seems to be buggy as you test with val.equals("") for equality of strings. Also, using val.length() == 0 is the best IMHO.

Upvotes: 2

Tarsem Singh
Tarsem Singh

Reputation: 14199

try

if(spin.getSelectedItem()!=null){    
   val = spin.getSelectedItem().toString();
}

if(!val.equals("")){
  questionsperplayer = Integer.parseInt(val);
  totalrequiredquestionsandanswers=playerList.size()*questionsperplayer*4;
  t.setText(totalrequiredquestionsandanswers + " music tracks required");
 }else{
    t.setText("");
    }

Upvotes: 2

Scott Helme
Scott Helme

Reputation: 4799

Place a breakpoint at the start of the function and step through. I suspect that the line number is incorrect.

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You may be not selected the item. Try this one

if(spin.getSelectedItem()!=null)

{

   val = spin.getSelectedItem().toString();

}

Upvotes: 2

Related Questions