I am using extras to pass a variable between instances, and I initiated the variable but android studio gives me an error saying it may not be initialized...
public class TasteNotePage extends ActionbarMenu {
String beerID = "a";
Dialog dialog = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tastenote_page);
//get beer data
Intent intent = getIntent();
Bundle b = intent.getExtras();
beerID = b.getString("id");
//get beer name, get our review if you have one, get all reviews and set
//check if user has beer
String url2 = "myURL";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userID = prefs.getString("userID", null);
String userURLComp = "x=" + userID;
String beerID = "&z=" + beerID;
The error occurs at beerID in the last line of the code above. Any idea how to fix this?
4 Answers 4
Remove String before the line
beerID = "&z=" + beerID;
The String signals the program that you are creating a new variable local to the method, which hides the attribute beerID from the class. And obviously, when later in the line you try to use its value, it has not been initialized yet.
Comments
The last beerID on the last line is referring to the local variable beerID, rather than the member variable. Either change it to beerID = "&z=" + beerID;, if you want to assign to the member variable, or else change it to String beerID = "&z=" + this.beerID; if you don't.
Comments
You're declaring the variable again in onCreate instead of using the once declared on the class - in this case it is not initialised:
String beerID = "&z=" + beerID;
I guess it should be:
beerID = "&z=" + beerID;
Comments
You initialized beerID twice. Remove one of the String from the second one if they are supposed to be the same variable.