Проблемы с подключением Firebase - PullRequest
0 голосов
/ 01 марта 2019

Приведенный ниже код приводит к сбою моего приложения, прежде чем оно получает возможность запуска:

public class MainActivity extends AppCompatActivity {

    EditText txtname,txtage,txtphone,txtheight;
    Button btnsave;
    DatabaseReference reff;
    Schedule schedule;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtname=(EditText)findViewById(R.id.txtname);
        txtage=(EditText)findViewById(R.id.txtage);
        txtphone=(EditText)findViewById(R.id.txtphone);
        txtheight=(EditText)findViewById(R.id.txtheight);
        btnsave=(Button)findViewById(R.id.btnsave);
        schedule=new Schedule();
        reff=FirebaseDatabase.getInstance().getReference().child("Schedule");
        btnsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int agea=Integer.parseInt(txtage.getText().toString().trim());
                Float hit=         
                Float.parseFloat(txtheight.getText().toString().trim());
                Long phn=Long.parseLong(txtphone.getText().toString().trim());

                schedule.setName(txtname.getText().toString().trim());
                schedule.setAge(agea);
                schedule.setHt(hit);
                schedule.setPh(phn);
                reff.child("schedule1").setValue(schedule);
                Toast.makeText(MainActivity.this, "Data inserted successfully", 
                Toast.LENGTH_LONG).show();
            }
        });



        Toast.makeText(MainActivity.this, "Firebase connection Success", 
        Toast.LENGTH_LONG).show();
      }
}

Я новичок в Firebase и не уверен, в чем я ошибаюсь, код запускается, когда моя строка reff = firebaseзакомментировано, поэтому должна быть проблема с тем, как я ссылаюсь, но, очевидно, код ничего не делает без подключения к базе данных, если кто-то может помочь.

Журналы от сбоя в соответствии с просьбой:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notihng/com.example.notihng.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.notihng. Make sure to call FirebaseApp.initializeApp(Context) first. 

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946) 

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 

at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 

at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 

at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 

at android.os.Handler.dispatchMessage(Handler.java:106) 

at android.os.Looper.loop(Looper.java:201) 

at android.app.ActivityThread.main(ActivityThread.java:6806) 

at java.lang.reflect.Method.invoke(Native Method) 

at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 

Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.notihng. Make sure to call FirebaseApp.initializeApp(Context) first. 

at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.4:240) 

at com.google.firebase.database.FirebaseDatabase.getInstance(com.google.firebase:firebase-database@@16.0.6:67) 

at com.example.notihng.MainActivity.onCreate(MainActivity.java:28) 

at android.app.Activity.performCreate(Activity.java:7210) 

at android.app.Activity.performCreate(Activity.java:7201) 

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272) 

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926) 

... 11 more 

Файл приложения Gradle:

 apply plugin: 'com.android.application'
 apply plugin: 'com.google.gms.google-services'

 android {
     compileSdkVersion 28
     defaultConfig {
         applicationId "com.example.notihng"
         minSdkVersion 21
         targetSdkVersion 28
         versionCode 1
         versionName "1.0"
         testInstrumentationRunner 
 "android.support.test.runner.AndroidJUnitRunner"
     }
     buildTypes {
         release {
             minifyEnabled false
             proguardFiles getDefaultProguardFile('proguard-android- 
optimize.txt'), 'proguard-rules.pro'
         }
     }
 }

 dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
     implementation 'com.android.support:appcompat-v7:28.0.0'
     implementation 'com.android.support:support-v4:28.0.0'
     implementation 'com.android.support.constraint:constraint- 
      layout:1.1.3'
     implementation 'com.google.firebase:firebase-database:16.0.6'
     testImplementation 'junit:junit:4.12'
     androidTestImplementation 'com.android.support.test:runner:1.0.2'
     androidTestImplementation 
     'com.android.support.test.espresso:espresso- 
      core:3.0.2'
    }
    apply plugin: 'com.google.gms.google-services'

Ответы [ 2 ]

0 голосов
/ 02 марта 2019

Понял, ребята, спасибо за помощь.Это были зависимости в проекте gradle, когда я изменил их на classpath 'com.android.tools.build:gradle:3.3.1' classpath 'com.google.gms: google-services: 3.0.0' Он предложил мне установитьновые файлы SDK.Не уверен, что исправления по умолчанию просто не работали или загрузка файлов была исправлением, но теперь все равно работает, еще раз спасибо.

0 голосов
/ 02 марта 2019

Отчет о сбое ясно говорит о проблеме в вашем коде.

Убедитесь, что сначала вызвали FirebaseApp.initializeApp (Context)

Прежде чем использовать его, необходимо сначала его инициализировать, как показано ниже.

FirebaseApp.initializeApp(this);

В вашем файле build.gradle есть два объявления о добавлении следующего плагина.

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

Я хотел бы предложить вам удалить первый.Держите один в конце вашего файла Gradle.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...