在Firebase中保存数据时片段重新启动

时间:2017-06-28 16:09:34

标签: android android-fragments firebase firebase-realtime-database firebase-authentication

每次将数据从Fragment发送到Firebase时,都会出现以下问题:

06-28 12:51:36.475 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: ActivityCreate
06-28 12:51:36.475 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: onstart
06-28 12:51:36.475 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: onresume
06-28 12:51:39.071 1224-1449/com.example.fernandosilveira.findpromotion D/FA: Logging event (FE): _s, Bundle[{_o=auto, _sc=PainelControle, _si=3714539327545697095}]
06-28 12:51:44.884 1224-1449/com.example.fernandosilveira.findpromotion D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=8535, _sc=PainelControle, _si=3714539327545697095}]
06-28 12:51:45.020 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: ActivityCreate
06-28 12:51:45.020 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: onstart
06-28 12:51:45.020 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: onresume
06-28 12:51:45.319 1224-1224/com.example.fernandosilveira.findpromotion I/LOG: onStop

当我点击这些开关时:enter image description here

它更新片段并转到初始片段......

以下是我正在使用的课程......

  

Class TabAdapterUsuario

package com.example.fernandosilveira.findpromotion.Adapter;

/**
 * Created by Fernando Silveira on 08/03/2017.
 */


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import com.example.fernandosilveira.findpromotion.Fragment.DestaquesFragment;
import com.example.fernandosilveira.findpromotion.Fragment.HistoricoFragment;
import com.example.fernandosilveira.findpromotion.Fragment.ProximosVoceFragment;


public class TabAdapterUsuario extends FragmentStatePagerAdapter {

    private String[] tituloAbas = {"Próximo a Você","Destaques", "Histórico"};

    public TabAdapterUsuario(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {

        Fragment fragment = null;

        switch (position)
        {
            case 0:
                fragment = new ProximosVoceFragment();
                break;
            case 1:
                fragment = new DestaquesFragment();
                break;
            case 2:
                fragment = new HistoricoFragment();
                break;
        }

        return fragment;

    }

    @Override
    public int getCount()
    {
        return tituloAbas.length;
    }

    @Override
    public CharSequence getPageTitle(int position)
    {
        return tituloAbas[position];
    }

}
  

称为片段的主类

package com.example.fernandosilveira.findpromotion.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fernandosilveira.findpromotion.Activity.FaleConosco;
import com.example.fernandosilveira.findpromotion.Activity.ListaDesejos;
import com.example.fernandosilveira.findpromotion.Activity.Login;
import com.example.fernandosilveira.findpromotion.Activity.MinhaConta;
import com.example.fernandosilveira.findpromotion.Activity.Sobre;
import com.example.fernandosilveira.findpromotion.Activity.TermosUso;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;

import com.example.fernandosilveira.findpromotion.Adapter.TabAdapterAnunciante;
import com.example.fernandosilveira.findpromotion.Adapter.TabAdapterUsuario;
import com.example.fernandosilveira.findpromotion.Model.Usuario;
import com.example.fernandosilveira.findpromotion.R;
import com.example.fernandosilveira.findpromotion.config.ConfiguracaoFirebase;
import com.example.fernandosilveira.findpromotion.helper.Base64Custom;
import com.example.fernandosilveira.findpromotion.helper.SlidingTabLayout;
import com.example.fernandosilveira.findpromotion.R.menu;

public class PainelControle extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener
{
    private FirebaseAuth minhaauth;
    private FirebaseAuth.AuthStateListener minhaAuthStateListener;
    private DatabaseReference firebase ;

    private String tipo;

    private TextView txtnomepainel,txtemailNav,txtv;

    private ProgressBar progressBar;

    private Base64Custom base64Custom;


    private SlidingTabLayout slidingTabLayout;
    private ViewPager viewPager;

    private  Usuario usuario;
    private TabAdapterAnunciante tabAdapterAnunciante;
    private  TabAdapterUsuario tabAdapterUsuario;
    private ConfiguracaoFirebase configuracaoFirebase;



    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // buscar instancia do usuario
        minhaauth = FirebaseAuth.getInstance();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_painel_controle);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_principal);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        slidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
        viewPager = (ViewPager) findViewById(R.id.vp_pagina);
        //Configurar sliding tabs
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorAccent));
        //Configurar adapter
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View hView =  navigationView.getHeaderView(0);
        txtnomepainel = (TextView)hView.findViewById(R.id.txtNomePainel);
        txtemailNav = (TextView)hView.findViewById(R.id.txtEmailNav);
        txtv = (TextView)hView.findViewById(R.id.txtv);
        progressBar = (ProgressBar)hView.findViewById(R.id.prgbarnav);
        tabAdapterAnunciante = new TabAdapterAnunciante(getSupportFragmentManager());
        tabAdapterUsuario = new TabAdapterUsuario(getSupportFragmentManager());


        txtnomepainel.setVisibility(View.GONE);
        txtemailNav.setVisibility(View.GONE);
        txtv.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);

        Bundle extra = getIntent().getExtras();
        if (extra!= null)
        {
            String nom = extra.getString("nome");
            String ema = extra.getString("email");
            tipo = extra.getString("tipo");
            txtemailNav.setText(ema);
            txtnomepainel.setText(nom);
            progressBar.setVisibility(View.GONE);
            txtv.setVisibility(View.VISIBLE);
            txtemailNav.setVisibility(View.VISIBLE);
            txtnomepainel.setVisibility(View.VISIBLE);
        }

        if (tipo.equals("anunciante"))
        {
            //  invocar menu
            navigationView.inflateMenu(menu.menu_anunciante);
            //invocar tab
            viewPager.setAdapter(tabAdapterAnunciante);
            //atribuir tab ao layout
            slidingTabLayout.setViewPager(viewPager);
            navigationView.setNavigationItemSelectedListener(this);

        }
        else if(tipo.equals("usuario"))
        {
            //  invocar menu
            navigationView.inflateMenu(menu.menu_usuario);
            //invocar tab
            viewPager.setAdapter(tabAdapterUsuario);
            //atribuir tab ao layout
            slidingTabLayout.setViewPager(viewPager);
            navigationView.setNavigationItemSelectedListener(this);
        }

    }

    @Override
    public void onBackPressed()

    {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START))
        {
            drawer.closeDrawer(GravityCompat.START);
        } else

        {

            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item)
    {
        int id = item.getItemId();

        if (id == R.id.minhaconta)
        {
            startActivity(new Intent(PainelControle.this, MinhaConta.class));
        } else if (id == R.id.listadedesejos)
        {
            startActivity(new Intent(PainelControle.this, ListaDesejos.class));
        } else if (id == R.id.faleconosco)
        {
            startActivity(new Intent(PainelControle.this, FaleConosco.class));
        } else if (id == R.id.sobre)
        {
            startActivity(new Intent(PainelControle.this, Sobre.class));
        } else if (id == R.id.termosdeuso)
        {
            startActivity(new Intent(PainelControle.this, TermosUso.class));
        }else if (id == R.id.logout)
        {
            DeslogarUser();
        }

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

    public void DeslogarUser()
    {
        //busca a instancia do usuario e desloga o usuario
        FirebaseAuth.getInstance().signOut();
        startActivity(new Intent(PainelControle.this, Login.class));
        finish();
        overridePendingTransition(R.anim.anim_fadein, R.anim.anim_fadeout);
        Toast.makeText(getApplicationContext(), "Usuario Desconectado!", Toast.LENGTH_LONG).show();
    }



}
  

将数据发送到Firebase时发生此片段更新错误的类

package com.example.fernandosilveira.findpromotion.Fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Switch;

import com.example.fernandosilveira.findpromotion.Model.CategoriaProd;
import com.example.fernandosilveira.findpromotion.Model.Usuario;
import com.example.fernandosilveira.findpromotion.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * A simple {@link Fragment} subclass.
 */
public class DestaquesFragment extends Fragment {
    private Usuario usuario;

    private ArrayAdapter arrayAdapter;
    private ListView listView;
    private CategoriaProd categoriaProd;
    private ArrayList<String> addDestaques = new ArrayList<>();
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference ref = database.getReference();
    private String meuUid;
    private ArrayList<String> list = new ArrayList<>();
    private Switch stGames, stBrinquedos, stColecionavéis, stEsporteeLazer, stArteeAntiguidade, stInstrumentosMusicais, stFotografia, stAssinaturaseRevistas, stArtigosReligiosos;
    private Switch stBebesCia, stCasaDecoracao, stConstrucaoFerramentas, stEletrodomesticos, stPetShop, stLivros, stCDs, stDVDs, stBluRay, stFilmeDigital, stHDDVD, stDiscosVinil, stMusicaDigital, stVHS, stFitasK7Gravadas;
    private Switch stModaeAcessorios, stPerfumariaCosmeticos, stSaude, stJoiasRelogios, stSexShop, stAlimentosBebidas, stIndustriaComercioNegocios, stAutomoveisVeiculos, stInformatica, stEletronicos, stTelefonia;
    private String Teste = "";
    private ValueEventListener valueEventListener;
    private ChildEventListener childEventListener;


    public DestaquesFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootview = inflater.inflate(R.layout.fragment_destaques, container, false);

        if (rootview != null) {
            stGames = (Switch) rootview.findViewById(R.id.swtGames);
            stBrinquedos = (Switch) rootview.findViewById(R.id.swtBrinquedos);
            stColecionavéis = (Switch) rootview.findViewById(R.id.swtColecionaveis);
            stEsporteeLazer = (Switch) rootview.findViewById(R.id.swtEsporteeLazer);
            stArteeAntiguidade = (Switch) rootview.findViewById(R.id.swtArteeAntiguidade);
            stInstrumentosMusicais = (Switch) rootview.findViewById(R.id.swtInstrumentosMusicais);
            stFotografia = (Switch) rootview.findViewById(R.id.swtFotografia);
            stAssinaturaseRevistas = (Switch) rootview.findViewById(R.id.swtAssinaturaseRevistas);
            stArtigosReligiosos = (Switch) rootview.findViewById(R.id.swtArtigosReligiosos);
            stBebesCia = (Switch) rootview.findViewById(R.id.swtBebeseCia);
            stCasaDecoracao = (Switch) rootview.findViewById(R.id.swtCasaeDecoracao);
            stConstrucaoFerramentas = (Switch) rootview.findViewById(R.id.swtConstrucaoeFerramentas);
            stEletrodomesticos = (Switch) rootview.findViewById(R.id.swtEletrodomesticos);
            stPetShop = (Switch) rootview.findViewById(R.id.swtPetShop);
            stLivros = (Switch) rootview.findViewById(R.id.swtLivros);
            stCDs = (Switch) rootview.findViewById(R.id.swtCDs);
            stDVDs = (Switch) rootview.findViewById(R.id.swtDVDs);
            stBluRay = (Switch) rootview.findViewById(R.id.swtBluRay);
            stFilmeDigital = (Switch) rootview.findViewById(R.id.swtFilmeDigital);
            stHDDVD = (Switch) rootview.findViewById(R.id.swtHDDVD);
            stDiscosVinil = (Switch) rootview.findViewById(R.id.swtDiscosdeVinil);
            stMusicaDigital = (Switch) rootview.findViewById(R.id.swtMusicaDigital);
            stVHS = (Switch) rootview.findViewById(R.id.swtVHS);
            stFitasK7Gravadas = (Switch) rootview.findViewById(R.id.swtFitasK7Gravadas);
            stModaeAcessorios = (Switch) rootview.findViewById(R.id.swtModaeAcessorios);
            stPerfumariaCosmeticos = (Switch) rootview.findViewById(R.id.swtPerfumariaeCosmeticos);
            stSaude = (Switch) rootview.findViewById(R.id.swtSaude);
            stJoiasRelogios = (Switch) rootview.findViewById(R.id.swtJoiaseRelogios);
            stSexShop = (Switch) rootview.findViewById(R.id.swtSexShop);
            stAlimentosBebidas = (Switch) rootview.findViewById(R.id.swtAlimentoseBebidas);
            stIndustriaComercioNegocios = (Switch) rootview.findViewById(R.id.swtIndustriaComercioeNegocios);
            stAutomoveisVeiculos = (Switch) rootview.findViewById(R.id.swtAutomoveisVeiculos);
            stInformatica = (Switch) rootview.findViewById(R.id.swtInformatica);
            stEletronicos = (Switch) rootview.findViewById(R.id.swtEletronicos);
            stTelefonia = (Switch) rootview.findViewById(R.id.swtTelefonia);


        }
        return rootview;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
        stGames.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {

                if (isChecked == true)
                {
                    list.add("Games");
                } else
                {
                    list.remove("Games");
                }
                final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                ref.child("usuarios").child(user.getUid()).child("destaques").setValue(list);
            }
        });
        stBrinquedos.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    list.add("Brinquedos");
                } else {
                    list.remove("Brinquedos");
                }
                final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                ref.child("usuarios").child(user.getUid()).child("destaques").setValue(list);
            }
        });
        Log.i("LOG","ActivityCreate");

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("LOG","onstart");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("LOG","onStop");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("LOG","onresume");

    }
}

我是编程新手,你可能会遇到多个错误......

0 个答案:

没有答案