1

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?

asked Nov 3, 2013 at 0:22

4 Answers 4

2

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.

answered Nov 3, 2013 at 0:26
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Nov 3, 2013 at 0:26

Comments

0

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;
answered Nov 3, 2013 at 0:26

Comments

0

You initialized beerID twice. Remove one of the String from the second one if they are supposed to be the same variable.

answered Nov 3, 2013 at 0:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.