Kay Ana
Kay Ana

Reputation: 81

Use global variable to store Android Firebase getKey?

I am working in Firebase for the first time and trying to modify my existing Android (to which I am still relatively new) application to use the Real-time Database it offers. My app sends data at two separate points during the life cycle of the app: when it is opened to store the user's name and when it concludes to store the game score/date. In reading my options and researching how to change from SQL to Firebase DB, it seemed like a great option to use a global variable to store the gameID key that was going to be created, but I can't seem to get it to work. App structure is below.

public class EditTextButtons extends AppCompatActivity implements View.OnClickListener {

    EditText etName;
    Button btnAdd;
    Button btnLastFive;
    Button btnTopFive;

    User globalVar;

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference mDatabase = database.getReference();
    DatabaseReference gamesDB = mDatabase.child("Games");

    /**
     * Called when Activity is first created. Instantiates the database, sets up
     * the content views, and creates the text field and buttons. Also holds commands
     * to insert data into database for username.
     *
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.snake_layout_r);

        etName = (EditText) findViewById (R.id.etName);
        btnAdd = (Button) findViewById (R.id.btnAdd);
        btnLastFive = (Button) findViewById (R.id.btnLastFive);
        btnTopFive = (Button) findViewById (R.id.btnTopFive);

        // set listeners
        btnAdd.setOnClickListener (this);
        btnLastFive.setOnClickListener (this);
        btnLastFive.setOnClickListener (this);

        //Call Application class User
        final User globalVar = (User) getApplicationContext();
    }

    /**
     * Sets up the method to handle button clicks
     * btnAdd calls the method to insert username to database then switch to the game start screen
     * btnLastFive calls the message to display the scores of the last 5 played games
     */
    @Override
    public void onClick(View v) {
        switch (v.getId ( )) {
            case R.id.btnAdd:
                insertIntoDB ();
                Intent i = new Intent (getApplicationContext ( ), Snake.class);
                startActivity (i);
                break;
            case R.id.btnLastFive:
                lastFive ();
                break;
            case R.id.btnTopFive:
                lastFive ();
                break;
            default:
                break;
        }
    }

    /**
     * Sets up the method to insert username into database
     */
    protected void insertIntoDB() {
        String name = etName.getText ().toString ();

        //Username is required
        if(TextUtils.isEmpty (name)) {
            etName.setError("Required");
            return;
        }

        String gameID = gamesDB.push().getKey();
        Log.d ("key", gameID );
        globalVar.setID(gameID);


        Map<String, User> users = new HashMap<String, User> ();
        users.put(gameID, new User(name));
        gamesDB.setValue(users);
    }
}

I have a separate User class which contains the getters/setters and I defined the User class in the Manifest under Application. My problem is, even though my log shows the key is being successfully generated and passed to the gameID variable, the app crashes when I try to store it. Every example for global variables I could find shows them being used solely in the onCreate method, so my first question is can they be used outside of it the way I am trying to do? If so, can anyone see what I have done wrong.

In it's current state, I am receiving a nullPointerException in debug when the "globalVar.setID(gameID);" line is called, but I do not understand why since the gameID variable is being successfully created. Any help is appreciated, I am truly at my wits end.

Upvotes: 0

Views: 564

Answers (1)

advice
advice

Reputation: 5988

First, I would consider renaming User to something more descriptive. Since you're extending Application, I usually just name it App. Because this class isn't just a User, it's your entire Android app, that may contain global variables or user information.

Second, in your onCreate, the reason you're having a NullPointerException is because you're creating a new globalVar variable in that scope.

Change

//Call Application class User
final User globalVar = (User) getApplicationContext();

to

//Call Application class User
globalVar = (User) getApplicationContext();

Upvotes: 1

Related Questions