当我按下微调器时,我看到了我的数据,但是当我尝试选择它时,它没有设置数据吗?

时间:2019-05-27 14:02:42

标签: java android firebase-realtime-database android-spinner

我正在尝试制作一个从Realtime Firebase数据库获取数据的微调器。我可以在日志语句中提取数据,也可以在按下下拉菜单时看到数据。但是,当我尝试在微调器中选择某些内容时,它不会设置数据。另外,当我尝试调用getSelectedItem()方法时,也会出现错误java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

我写的日志中没有空值,因此我很困惑为什么会出现这种错误


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    ArrayList<BankAccount> accounts = new ArrayList<>();


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

    }

    public void transferMoney(View view) {
        Log.d("grinern", "olool"+accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("grinern", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            Log.d("grinern", ""+accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("grinern", ""+accounts);

                ArrayAdapter<BankAccount> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, accounts);
                accountFrom.setAdapter(adapter);
                accountTo.setAdapter(adapter);
                adapter.notifyDataSetChanged();


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();


    }
}

它应该选择我在下拉微调器中按下的任何内容,并将其打印在我的日志中,该日志在我的transferMoney()方法中调用

下面是我的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    tools:context=".TransferOwnAccount">

    <Button
        android:id="@+id/transferButton"
        style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
        android:layout_width="100dp"
        android:layout_height="48dp"
        android:layout_marginTop="80dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/contrast_background"
        android:text="@string/transfer"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToSpinner"
        app:layout_constraintVertical_bias="0.006"
        tools:targetApi="lollipop" />

    <TextView
        android:id="@+id/transferToTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:text="@string/transfer_to"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromSpinner" />

    <TextView
        android:id="@+id/transferFromTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_from"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferAmount" />

    <TextView
        android:id="@+id/transferTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_money"
        android:textColor="#F9FAF9"
        android:textSize="24sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/transferAmount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="99dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/choose_amount"
        android:inputType="textPersonName"
        android:text="@string/choose_amount"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferTitle"
        tools:targetApi="o" />

    <Spinner
        android:id="@+id/transferFromSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromTitle" />

    <Spinner
        android:id="@+id/transferToSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToTitle" />
</android.support.constraint.ConstraintLayout>

下面是我的Firebase数据库中的JSON。

{
  "bankaccounts" : {
    "126" : {
      "accNumber" : "126",
      "balance" : 0,
      "title" : "Default"
    },
    "127" : {
      "accNumber" : "127",
      "balance" : 0,
      "title" : "Budget"
    },
    "128" : {
      "accNumber" : "128",
      "balance" : 0,
      "title" : "Pension"
    }
  },
  "nextNumber" : "128",
  "users" : {
    "1111111111" : {
      "address" : "qwe",
      "cpr" : "1111111111",
      "email" : "qwe",
      "firstname" : "qwe",
      "lastname" : "qwe",
      "password" : "111111",
      "phonenumber" : "793"
    }
  },
  "usersbankaccounts" : {
    "1111111111" : {
      "126" : "Default Account",
      "127" : "Budget Account",
      "128" : "Pension Account"
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您需要将bankaccounts数组列表更改为静态(即使状态更改,也要确保其相同)

然后我将适配器移为一个字段,并在init方法中对其进行了初始化,请检查我提供的代码:

package com.example.bankapp;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    static  ArrayList<BankAccount> accounts = new ArrayList<>();
    ArrayAdapter<BankAccount> adapter;


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

    }

    public void transferMoney(View view) {
        Log.d("test", "olool" + accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("test", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            adapter.notifyDataSetChanged();

                            Log.d("test", "" + accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("test", "" + accounts);


                adapter.notifyDataSetChanged();


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, accounts);
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();
        this.accountFrom.setAdapter(adapter);
        this.accountTo.setAdapter(adapter);

    }
}

然后,您需要确保您的银行帐户中有toString()方法

 @Override
    public String toString() {
        return title + "--- " +accNumber + "  " + balance ;
    }

这应该可以解决问题:)