首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android:尝试将数据保存到Firebase数据库时应用程序崩溃

Android:尝试将数据保存到Firebase数据库时应用程序崩溃
EN

Stack Overflow用户
提问于 2017-03-16 02:26:57
回答 2查看 3.2K关注 0票数 -1

我正在尝试将数据保存到Firebase数据库。其实没那么复杂,但我发现每当我点击saveInfoButton的时候,我的应用程序就会崩溃。我对Firebase和Swift/iOS很有经验,但对Android比较陌生。这似乎不会是Firebase的问题。

具体的消息(当我点击按钮时)是:"Restaurant_app已停止,请再次打开应用程序。“

activity_main_page.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_page"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="16dp"
    tools:context="com.example.test.restaurant_app.MainPage">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true">

        <TextView
            android:text="Email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/userEmail" />

        <EditText
            android:layout_margin="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:hint="Enter your name"
            android:id="@+id/nameTextField"
            />

        <EditText
            android:layout_margin="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:hint="address"
            android:id="@+id/addressTextField"
            />
        <EditText
            android:layout_margin="15dp"
            android:id="@+id/ageTextField"
            android:hint="Age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <Button
            android:layout_margin="15dp"
            android:id="@+id/saveInfoButton"
            android:text="Save Information"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <Button
            android:text="Logout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:id="@+id/logoutButton" />
    </LinearLayout>
</RelativeLayout>

UserDetails.java

代码语言:javascript
复制
package com.example.test.restaurant_app;

public class UserDetails {

    public String name;
    public String address;
    public int age;

    public UserDetails(String name, String address, int age) {
        this.name = name;
        this.address = address;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

MainPage.java

代码语言:javascript
复制
package com.example.test.restaurant_app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;

public class MainPage extends AppCompatActivity implements View.OnClickListener {

    private FirebaseAuth mAuth;
    private FirebaseUser user;
    private TextView textViewEmail;
    private Button logoutButton;
    private DatabaseReference dbReference;

    private EditText editTextName, editTextAddress, editTextAge;
    private Button saveInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        mAuth = FirebaseAuth.getInstance();


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);

        logoutButton = (Button) findViewById(R.id.logoutButton);
        textViewEmail = (TextView) findViewById(R.id.userEmail);
        editTextName = (EditText) findViewById(R.id.nameTextField);
        editTextAddress = (EditText) findViewById(R.id.addressTextField);
        editTextAge = (EditText) findViewById(R.id.ageTextField);
        saveInfo = (Button) findViewById(R.id.saveInfoButton);

        if (mAuth.getCurrentUser() == null) {
            finish();
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }

        FirebaseUser user = mAuth.getCurrentUser();
        String name = user.getEmail().toString().trim();
        String welcomeMessage = "Hello, " + name;
        textViewEmail.setText(welcomeMessage);

        logoutButton.setOnClickListener(this);
        saveInfo.setOnClickListener(this);

    }

    public void saveInfo() {
        String name = editTextName.getText().toString();
        String address = editTextAddress.getText().toString();
        int age = Integer.parseInt(editTextAge.getText().toString());

        UserDetails userInfo = new UserDetails(name, address, age);

        dbReference.child("Users").child(user.getUid()).setValue(userInfo);

        Toast.makeText(this, "Information Saved", Toast.LENGTH_LONG).show();

    }

    public void onClick(View view) {
        if (view == logoutButton) {
            finish();
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }
        if (view == saveInfo){
            saveInfo();
        }
        }
    }

错误:

代码语言:javascript
复制
03-15 11:33:41.516 4595-4595/com.example.test.restaurant_app E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                     Process: com.example.test.restaurant_app, PID: 4595
                                                                                     java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
                                                                                         at com.example.test.restaurant_app.MainPage.saveInfo(MainPage.java:65)
                                                                                         at com.example.test.restaurant_app.MainPage.onClick(MainPage.java:77)
                                                                                         at android.view.View.performClick(View.java:5637)
                                                                                         at android.view.View$PerformClick.run(View.java:22429)
                                                                                         at android.os.Handler.handleCallback(Handler.java:751)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

03-15 11:33:41.521 1605-1828/system_process W/ActivityManager:   Force finishing activity com.example.test.restaurant_app/.MainPage

03-15 11:33:41.554 1326-2029/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer

03-15 11:33:41.557 1326-2029/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer

03-15 11:33:41.558 1326-2029/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer

03-15 11:33:41.559 1605-3137/system_process I/OpenGLRenderer: Initialized EGL, version 1.4

03-15 11:33:41.559 1605-3137/system_process D/OpenGLRenderer: Swap behavior 1

03-15 11:33:41.560 1605-3137/system_process W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...

03-15 11:33:41.560 1605-3137/system_process D/OpenGLRenderer: Swap behavior 0

03-15 11:33:42.027 1605-1619/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{7bfe46d u0 com.example.test.restaurant_app/.MainPage t644 f}

03-15 11:33:46.545 2380-5115/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.

03-15 11:33:51.529 1605-1619/system_process W/ActivityManager: Launch timeout has expired, giving up wake lock!
EN

回答 2

Stack Overflow用户

发布于 2017-03-16 02:31:42

看起来dbReference从未初始化过。这将导致行dbReference.child("Users").child(user.getUid()).setValue(userInfo);上的NullPointerException。确保在访问对象之前对其进行了初始化。

票数 1
EN

Stack Overflow用户

发布于 2017-03-16 02:47:20

将以下代码添加到saveInfo方法的顶部或初始化这些变量

FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference dbReference= database.getReference();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42817849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档