Error validating data in firebase database

1

I'm trying to validate whether a date already exists or not at the bank. The situation that occurs is as follows, I have a screen with a calendarview, when selecting a date it is displayed in a textview. After the date has been chosen, I click on the schedule button, with this the user, the resource (selected in a spinner) and the date (selected in the calendarview) are inserted into my database in the firebase. However, I want to validate whether the date selected, already exists in the database or not. If it does, it will display a message that this date is not available, if there is no calendar normally. But when I do this validation with the code below, an error occurs on the android monitor and my application closes. Can someone help me? Hugs. Here is the android studio, database, and android monitor bug code.

package br.com.douglasprogtg.appcond;

import android.app.DatePickerDialog;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.Spinner;
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.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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.com.douglasprogtg.appcond.dao.Mensagem;
import br.com.douglasprogtg.appcond.dao.MensagemList;
import br.com.douglasprogtg.appcond.dao.Recurso;

public class AgendarRecursoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    String TAG = "AgendarRecursoActivity";
    String nomeRecurso;

    TextView txtData;
    CalendarView calendario;

    Recurso recurso;

    TextView txtNome;
    Button btnAgendarRecurso;
    Spinner recursoSpinner;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    private FirebaseAuth mAuth;

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

        mAuth = FirebaseAuth.getInstance();

        FirebaseUser user = mAuth.getCurrentUser();

        //databaseReference = FirebaseDatabase.getInstance().getReference()
        //.child("recursos").child(user.getUid()).child("");

        calendario = (CalendarView) findViewById(R.id.calendarioRecurso);
        txtData = (TextView) findViewById(R.id.txtDataCalendario);
        txtNome = (TextView) findViewById(R.id.txtEmailUsuarioRecurso);
        btnAgendarRecurso = (Button) findViewById(R.id.btnAgendarRecurso);
        recursoSpinner = (Spinner) findViewById(R.id.spinner);

        txtNome.setText(user.getEmail());
        //txtData.setText("Data");

        databaseReference = FirebaseDatabase.getInstance().getReference();

        databaseReference.child("recursos").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                final List<String> recursoNome = new ArrayList<String>();

                for (DataSnapshot recursoSnapshot : dataSnapshot.getChildren()) {
                    //Pega título do nó
                    String recursoSnap = recursoSnapshot.getKey();

                    //Adiciona na lista
                    recursoNome.add(recursoSnap);
                }

                //Pega lista e poe no spinner
                ArrayAdapter<String> recursosAdapter = new ArrayAdapter<String>(AgendarRecursoActivity.this, android.R.layout.simple_spinner_item, recursoNome);
                recursosAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                recursoSpinner.setAdapter(recursosAdapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        calendario.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                String date = dayOfMonth + "/" + (month + 1) + "/" + year;
                Log.d(TAG, "onSelectedDayChange: " + date);

                txtData.setText(date);
            }
        });

        btnAgendarRecurso.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recurso = new Recurso();
                recurso.setNomeUsuario(txtNome.getText().toString());
                recurso.setDataRecurso(txtData.getText().toString());
                recurso.setNomeRecurso(recursoSpinner.getSelectedItem().toString());

                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
                FirebaseUser user = mAuth.getCurrentUser();

                databaseReference.child("recursos").child(recursoSpinner.getSelectedItem().toString()).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for(DataSnapshot snapshot: dataSnapshot.getChildren()) {

                            if(snapshot.child("dataRecurso").getValue().toString().equals(recurso.getDataRecurso())){  //error in android monitor is here

                                Toast.makeText(AgendarRecursoActivity.this, "Data indisponível", Toast.LENGTH_SHORT).show();

                            }

                            else{

                                reservarRecurso();

                            }

                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });



            }
        });
    }

    public void reservarRecurso(){

        databaseReference.child("recursos").child(recursoSpinner.getSelectedItem().toString()).push().setValue(firebaseDatabase, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                //Problem with saving the data
                if (databaseError != null) {
                    Toast.makeText(AgendarRecursoActivity.this, "Erro ao agendar recurso! Data não disponível", Toast.LENGTH_LONG).show();
                } else {
                    //Data uploaded successfully on the server
                    databaseReference.child("nomeUsuario").setValue(txtNome.getText().toString());
                    databaseReference.child("dataRecurso").setValue(txtData.getText().toString());
                    Toast.makeText(AgendarRecursoActivity.this, "Recurso agendado com sucesso!", Toast.LENGTH_LONG).show();
                    retornaTela();
                }
            }
        });

    }

    public void agendar(View v) {
        calendario = (CalendarView) findViewById(R.id.calendarioRecurso);
        SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
        String dataRecurso = formatoData.format(new Date(calendario.getDate()));

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        nomeRecurso = parent.getItemAtPosition(position).toString();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public void retornaTela(){
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
    }

}

    
asked by anonymous 10.10.2017 / 13:48

1 answer

0

Your problem is related to some null object (NullPointerException), check the objects that you do '.toString ()' in your 'btnAgendarResource.setOnClickListener ...' that probably will be there. p>     

11.10.2017 / 00:37