Fragment updates when I select data in Firebase

Asked

Viewed 125 times

0

I have 3 fragments inside a display pager and, whenever my database changes, it restarts the fragment.

Tabadapteradvertiser class

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 = {"Categorias","Próximo a Você", "Histórico"};

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

    @Override
    public Fragment getItem(int position)
    {

        Fragment fragment = null;

        switch (position)
        {
            case 0:
                fragment = new DestaquesFragment();
                break;
            case 1:
                fragment = new ProximosVoceFragment();
                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];
    }
}

Class controlling the 3 fragments

package com.example.fernandosilveira.findpromotion.Activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
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.util.Log;
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.Adapter.TabAdapterAnunciante;
import com.example.fernandosilveira.findpromotion.Adapter.TabAdapterUsuario;
import com.example.fernandosilveira.findpromotion.Geofence.ServicoLocalCliente;
import com.example.fernandosilveira.findpromotion.R;
import com.example.fernandosilveira.findpromotion.helper.SlidingTabLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class PainelControle extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener
{
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference ref = database.getReference();
    private TextView txtnomepainel,txtemailNav,txtv;
    private ProgressBar progressBar;
    private SlidingTabLayout slidingTabLayout;
    private ViewPager viewPager;
    private TabAdapterAnunciante tabAdapterAnunciante;
    private  TabAdapterUsuario tabAdapterUsuario;
    private String nome = "";
    private String email = "";
    private String tipo="";
    private String telefone = "";
    private static final String TAG = PainelControle.class.getSimpleName();
    private int MULTIPLA_PERMISSÃO_PEDIDO_CODIGO = 1;
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Sistema","onStart(); Painel controle");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Sistema","onStop(); Painel controle");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.d("Sistema","onCreate(); Painel controle");
        setContentView(R.layout.activity_painel_controle);
        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);

        // configurar toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_principal);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        //configurar abas
        slidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
        viewPager = (ViewPager) findViewById(R.id.vp_pagina);
        tabAdapterUsuario = new TabAdapterUsuario(getSupportFragmentManager());
        tabAdapterAnunciante = new TabAdapterAnunciante(getSupportFragmentManager());
        txtnomepainel.setVisibility(View.GONE);
        txtemailNav.setVisibility(View.GONE);
        txtv.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        Bundle extra = getIntent().getExtras();
        if (extra!= null)
        {
            nome = extra.getString("nome");
            email = extra.getString("email");
            tipo = extra.getString("tipo");
            telefone = extra.getString("telefone");
            txtemailNav.setText(email);
            txtnomepainel.setText(nome);
            progressBar.setVisibility(View.GONE);
            txtv.setVisibility(View.VISIBLE);
            txtemailNav.setVisibility(View.VISIBLE);
            txtnomepainel.setVisibility(View.VISIBLE);
        }
        if (tipo.equals("anunciante"))
        {
            //stopService(new Intent(getApplicationContext(), ServicoLocalCliente.class));
            //  invocar menu
            navigationView.inflateMenu(R.menu.menu_anunciante);
            //invocar tab
            viewPager.setAdapter(tabAdapterAnunciante);
            //atribuir tab ao layout
            navigationView.setNavigationItemSelectedListener(this);
        }
        else if(tipo.equals("usuario"))
        {
            iniciarGeofenceService();
            //  invocar menu
            navigationView.inflateMenu(R.menu.menu_usuario);
            //invocar tab
            //viewPager.setAdapter(tabAdapterUsuario);
            viewPager.setAdapter(tabAdapterUsuario);
            //atribuir tab ao layout
            navigationView.setNavigationItemSelectedListener(this);
        }
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorPrimaryDark));
        slidingTabLayout.setViewPager(viewPager);
        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();
    }

    @Override
    public void onBackPressed()
    {
        Log.d("Sistema","onBackPressed(); Painel controle");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START))
        {
            drawer.closeDrawer(GravityCompat.START);
        } else

        {

            super.onBackPressed();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.d("Sistema","onSaveInstanceState(); Painel controle");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("Sistema","onConfigurationChanged(); Painel controle");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d("Sistema","onRestoreInstanceState(); Painel controle");
    }

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

        if (id == R.id.minhaconta)
        {
            Intent intent = new Intent(PainelControle.this, MinhaConta.class);
            intent.putExtra("nome",nome);
            intent.putExtra("email",email);
            intent.putExtra("telefone",telefone);
            intent.putExtra("tipo",tipo);
            startActivity(intent);

        } 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));
        stopService(new Intent(getApplicationContext(), ServicoLocalCliente.class));
        finish();
        overridePendingTransition(R.anim.anim_fadein, R.anim.anim_fadeout);
        Toast.makeText(getApplicationContext(), "Usuario Desconectado!", Toast.LENGTH_LONG).show();
    }
    private void iniciarGeofenceService() {

        Intent intent = new Intent(this, ServicoLocalCliente.class);

        Log.i(TAG, "Início do serviço do cliente de localização");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            boolean hasPermissionAccesssFineLocation = ContextCompat.checkSelfPermission(getApplicationContext(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            boolean hasPermissionAccesssCoarseLocation = ContextCompat.checkSelfPermission(getApplicationContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            if (!hasPermissionAccesssFineLocation || !hasPermissionAccesssCoarseLocation)
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION}, MULTIPLA_PERMISSÃO_PEDIDO_CODIGO);
            else
                startService(intent);
        } else {

            startService(intent);
        }


    }

}

One of the Fragments

package com.example.fernandosilveira.findpromotion.Fragment;


import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
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.ListView;

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.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;

/**
 * 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 ArrayList<String> destaques = new ArrayList<>();

    private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    private String meuUid;
    private ValueEventListener valueEventListener;
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference ref = database.getReference();
    private SwipeRefreshLayout swrCat;


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

    @Override
    public void onStart() {
        super.onStart();
        Log.d("Sistema","onStart(); DestaquesFragment");
        //ref.child("usuarios").child(meuUid).child("destaques").addValueEventListener(valueEventListener);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("Sistema","onCreateView(); DestaquesFragment");
        final View view = inflater.inflate(R.layout.fragment_destaques, container, false);
        listView = (ListView) view.findViewById(R.id.listdestaq);
        atualizar();
        arrayAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_checked ,destaques );
        listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter( arrayAdapter );
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckedTextView checkedTextView = (CheckedTextView) view;
                if (checkedTextView.isChecked()) {
                    addDestaques.add(destaques.get(position));
                    ref.child("usuarios").child(meuUid).child("destaques").setValue(addDestaques);
                } else {
                    addDestaques.remove(addDestaques.indexOf(destaques.get(position)));
                    ref.child("usuarios").child(meuUid).child("destaques").setValue(addDestaques);
                }
            }
        });

        return view;
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("Sistema","onStop(); DestaquesFragment");

    }

    @Override
    public void onPause() {
        super.onPause();
        //ref.child("usuarios").child(meuUid).child("destaques").removeEventListener(valueEventListener);
        Log.d("Sistema","onPause(); DestaquesFragment");

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("Sistema","onResume(); DestaquesFragment");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("Sistema","onConfigurationChanged(); DestaquesFragment");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("Sistema","onDetach(); DestaquesFragment");
    }

    public void atualizarLista()
    {
        destaques.clear();
        for (String ui: categoriaProd.todasSubCat)
        {destaques.add(ui);}
        for(String uid:destaques)
        {
            if(addDestaques.contains(uid)){
                listView.setItemChecked(destaques.indexOf(uid), true);
            } else {
                listView.setItemChecked(destaques.indexOf(uid), false);
            }
        }
    }
    public void atualizar()
    {
        if (user != null)
        {
           meuUid = user.getUid();
           ref.child("usuarios").child(meuUid).child("destaques").addListenerForSingleValueEvent(new ValueEventListener() {
               @Override
               public void onDataChange(DataSnapshot dataSnapshot) {
                   addDestaques.clear();
                   //Listar contatos
                   for (DataSnapshot dados : dataSnapshot.getChildren())
                   {addDestaques.add(dados.getValue().toString());}
                   atualizarLista();
               }
               @Override
               public void onCancelled(DatabaseError databaseError) {

               }
           });
        }
    }
    public void atualizarlista()
    {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null)
        {
            meuUid = user.getUid();
            valueEventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Limpar lista
                    addDestaques.clear();
                    //Listar contatos
                    for (DataSnapshot dados : dataSnapshot.getChildren())
                    {addDestaques.add(dados.getValue().toString());}
                    atualizarLista();
                    arrayAdapter.notifyDataSetChanged();
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            };
        }

    }
}

When I click on one of the items it restarts the main Activity and restarts the fragment, but it does not return to the current fragment

inserir a descrição da imagem aqui

Here are the categories

  • 1

    This is the Stack Overflow in Portuguese, translate your doubt or publish it in the english

  • Strange this behavior of closing and opening the app, you took a look at Logcat to see if something pops up? Put a Debug point on your Listview Onitemclicklistener and see if it enters the code.

  • 1

    So, I was racking my brain with this ,the only solution I found was to change the"highlights" knot to the first bank knot...ai worked perfectly.. can’t tell the solution to the problem

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.