team1name is initialized in the begining of the widget class
String team1name= null;
But when I return a string from the getAcronym() and assign to team1name, I get a null pointer exception. How do I resolve this
Here’s the code
public void onReceive(Context context, Intent intent){
Bundle extras = intent.getExtras();
if (extras == null) {
return;
}
team1name = extras.getString("team1name");
team2name = extras.getString("team2name");
team1score = extras.getString("team1score");
team2score=extras.getString("team2score");
player1=extras.getString("player1");
player2=extras.getString("player2");
extras=null;
team1name=getAcronym(team1name); // Null Pointer Exception
team2name=getAcronym(team2name);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.team1name, team1name);
remoteViews.setTextViewText(R.id.team2name,
ComponentName cn = new ComponentName(context, MyWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
}
String getAcronym(String teamName){
if(teamName.equals("Australia")){
teamName="AUS";
}else if(teamName.equals("Pakistan")){
teamName="PAK";
}else if(teamName.equals("India")){
teamName="IND";
}else if(teamName.equals("England")){
teamName="ENG";
}else if(teamName.equals("Sri Lanka")){
teamName="SL";
}else if(teamName.equals("South Africa")){
teamName="RSA";
}
return teamName;
}
Your
getAcronym(String teamName)method does not do any null checking. Add the line:before you start checking for the string value, and this should alleviate your problems.
Might be work checking to see why teamName is being passed through as null, if it is intentional then this solution will work fine. If you should always be sending a valid teamName through, then there is somewhere in your code before you get to your widget where it is not being assigned properly.
Also, if your strings are not constant, i.e they could conceivably be “England” or “england”, you should do a comparison where the case is ignored to catch these instances.
i.e