简体   繁体   中英

Firebase realtime database write crash android application

I'm trying to make a simple code to write to firebase realtime database. However when activity that writes to database is opened it crashes the app. This is the code i'm using:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class main_view extends AppCompatActivity {

    Button button = findViewById(R.id.button);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_view);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        final DatabaseReference mRef = database.getReference("message");



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageValue = "Hello world";
                mRef.setValue(messageValue);

            }
        });
    }
}

I have no idea what goes wrong here

You should call findViewById() in the on onCreate method after the layout has been inflated. You initialize the variable button outside onCreate before the layout has been inflated, therefore it is set to null.

Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageValue = "Hello world";
                mRef.setValue(messageValue);

            }
        });
Button button = findViewById(R.id.button);

This line may create problem if you write it directly under the class. Place it inside onCreate().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM