Как решить «компонент базы данных Firebase нет» ошибка? - PullRequest
0 голосов
/ 07 ноября 2019

Я получаю эту ошибку, когда нажимаю на второй фрагмент в ящике навигации в приложении. Второй фрагмент, где я пытаюсь подключиться к базе данных Firebase. Я не понимаю почему, потому что я использовал плагин Google в build.gradle, использовал последний путь к классу и попытался поместить все необходимые зависимости в build.gradle. У кого-нибудь есть подсказка и помогите мне с этим?

2019-11-07 18:39:44.356 21884-21884/com.example.appv1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.appv1, PID: 21884
    java.lang.NullPointerException: Firebase Database component is not present.
        at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source)
        at com.google.firebase.database.FirebaseDatabase.getInstance(com.google.firebase:firebase-database@@19.2.0:114)
        at com.google.firebase.database.FirebaseDatabase.getInstance(com.google.firebase:firebase-database@@19.2.0:57)
        at com.example.appv1.SecondFragment.onCreateView(SecondFragment.java:62)

build.gradle (app)

apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"

    defaultConfig {
        applicationId "com.example.appv1"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }


    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        testImplementation 'junit:junit:4.12'
        implementation 'androidx.appcompat:appcompat:1.0.0'

        implementation 'com.google.android.material:material:1.0.0'


        implementation 'androidx.coordinatorlayout:coordinatorlayout:1.0.0-alpha1'
        implementation "androidx.constraintlayout:constraintlayout:1.1.3"


        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

        androidTestImplementation 'androidx.test:runner:1.1.0'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'


        // Displaying images
        implementation 'com.github.bumptech.glide:glide:3.6.1'

        // Firebase
        //implementation 'com.google.firebase:firebase-database:9.6.0'
        //implementation 'com.google.firebase:firebase-auth:9.6.0'
        implementation 'com.google.firebase:firebase-database:19.2.0'
        implementation 'com.google.firebase:firebase-auth:19.1.0'
        implementation 'com.google.firebase:firebase-analytics:17.2.1'
        implementation 'com.google.firebase:firebase-firestore:21.2.1'

        // FirebaseUI
        implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
    }

    apply plugin: 'com.google.gms.google-services'
}

buil.graddle

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath 'com.google.gms:google-services:4.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

У меня есть этовнутри фрагмента, который вызывает ошибку:

 mFirebaseDatabase = FirebaseDatabase.getInstance();

 mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");

Я также пытался использовать FirebaseApp.initializeApp(this); как во фрагменте, так и в MainActivity, но получаю ту же ошибку.

Редактировать:

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FirebaseApp.initializeApp(getApplicationContext());

        setContentView(R.layout.activity_main);


        /**
         *  Navigation drawer
         */

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.sign_out_menu) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        FragmentManager fragmentManager=getSupportFragmentManager();
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_sign_in){
            fragmentManager.beginTransaction().replace(R.id.content_frame, new LogInFragment()).commit();
        }

        if (id == R.id.nav_add) {
            fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
            // Handle the camera action
        } else if (id == R.id.nav_second_layout) {
            fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();

        } else if (id == R.id.nav_third_layout) {
            fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();

        }  else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

SecondFragment.java

 @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);


        myView=inflater.inflate(R.layout.nav_second_layout, container, false);
        mUsername = ANONYMOUS;


        // Initialize Firebase components
        mFirebaseDatabase = FirebaseDatabase.getInstance();

        mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");


        // Initialize references to views
        mProgressBar = (ProgressBar) myView.findViewById(R.id.progressBar);
        mMessageListView = (ListView)myView.findViewById(R.id.messageListView);
        mPhotoPickerButton = (ImageButton) myView.findViewById(R.id.photoPickerButton);
        mMessageEditText = (EditText) myView.findViewById(R.id.messageEditText);
        mSendButton = (Button) myView.findViewById(R.id.sendButton);

        // Initialize message ListView and its adapter
        List<FriendlyMessage> friendlyMessages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(SecondFragment.this.getActivity(), R.layout.item_message, friendlyMessages);
        mMessageListView.setAdapter(mMessageAdapter);

        // Initialize progress bar
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);

        // ImagePickerButton shows an image picker to upload a image for a message
        mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Fire an intent to show an image picker
            }
        });

        // Enable Send button when there's text to send
        mMessageEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().length() > 0) {
                    mSendButton.setEnabled(true);
                } else {
                    mSendButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

        // Send button sends a message and clears the EditText
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Send messages on click
                FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
                mMessagesDatabaseReference.push().setValue(friendlyMessage);

                // Clear input box
                mMessageEditText.setText("");
            }
        });

        return myView;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu) ;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...