0

Tenho um recycler view dentro de um fragment em um tablayout, sendo a tab principal. Após efetuar login, ela não carrega os dados, somente carrega se eu mudar de tab e retornar, ou fechar e abrir o APP.

Código:

public class ContatosFragment extends Fragment {
    ListView ltwContatos = null;
    List<Contato> lista = null;

    private RecyclerView recyclerContatos;
    private ContatosAdapterRecycler mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_contatos, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){

        recyclerContatos = getView().findViewById(R.id.recyclerContatos);

        recyclerContatos = getView().findViewById(R.id.recyclerContatos);

        SQLiteHelper db = new SQLiteHelper(getContext());
        lista = db.getContacts();

        mAdapter = new ContatosAdapterRecycler(getContext(), lista);
        recyclerContatos.setAdapter(mAdapter);
        recyclerContatos.setLayoutManager(new LinearLayoutManager(getContext()));

        // tentei com um timer mas não deu muito certo tambem
        new Handler().postDelayed(new Runnable() {
            public void run() {
                refleshListView();
            }
        },100);

        recyclerContatos.addOnItemTouchListener(
            new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override public void onItemClick(View view, int position) {
                    Intent it = new Intent(getActivity(), ChatActivity.class);
                    it.putExtra("contact_user", lista.get(position).getContact_user());
                    it.putExtra("name_contact", lista.get(position).getName_contact());
                    it.putExtra("photo_contact", lista.get(position).getPhoto_contact());
                    startActivity(it);
                }
            })
        );


        FloatingActionButton fab = (FloatingActionButton) getView().findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!CheckConection()){
                    Toast.makeText(getContext(), "Por favor, conecte-se a internet!", Toast.LENGTH_SHORT).show();
                }else{
                    AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
                    alert.setTitle("Adicionar contato");
                    alert.setMessage("Digite o e-mail do contato");

                    final EditText txtEmail = new EditText(getContext());
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT);
                    txtEmail.setLayoutParams(lp);
                    txtEmail.setTextColor(Color.parseColor("#000000"));

                    alert.setView(txtEmail);
                    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String URL = "http://192.168.15.10/chat/add_contact.php";
                            SharedPreferences Preferences = getActivity().getSharedPreferences("userData", Context.MODE_PRIVATE);
                            final String id_user = String.valueOf(Preferences.getInt("id_usuario", 0));

                            Ion.with(getContext())
                                    .load("POST",URL)
                                    .setBodyParameter("email_user", txtEmail.getText().toString())
                                    .setBodyParameter("id_user", id_user)
                                    .asJsonObject()
                                    .setCallback(new FutureCallback<JsonObject>() {
                                        @Override
                                        public void onCompleted(Exception e, JsonObject result) {
                                            if(result.get("retorno").getAsString().equals("YES")){
                                                SQLiteHelper db = new SQLiteHelper(getContext());
                                                db.save_contact(Integer.parseInt(id_user), result.get("contact_user").getAsInt(), result.get("nome_user").getAsString(), result.get("photo_user").getAsString());
                                                refleshListView();
                                                Toast.makeText(getContext(), "Contato cadastrado com sucesso!", Toast.LENGTH_SHORT).show();

                                            }else if(result.get("retorno").getAsString().equals("EMAIL_NAO_ENCONTRADO")){

                                                Toast.makeText(getContext(), "Contato não encontrado", Toast.LENGTH_SHORT).show();
                                                txtEmail.setError("Contato não encontrado");
                                                txtEmail.requestFocus();

                                            }else if(result.get("retorno").getAsString().equals("CONTACT_EXIST")){

                                                Toast.makeText(getContext(), "Você já adicionou este contato", Toast.LENGTH_SHORT).show();
                                            }else if(result.get("retorno").getAsString().equals("SEU_EMAIL")){

                                                Toast.makeText(getContext(), "Você não pode se adicionar como contato!", Toast.LENGTH_SHORT).show();
                                            }

                                        };
                                    });
                        }
                    });

                    alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
                    alert.show();
                }

            }
        });
    }

    private void refleshListView(){
        //SQLiteHelper db = new SQLiteHelper(getContext());
        //this.lista = db.getContacts();
        //ltwContatos.setAdapter(new ContatosAdapter(getContext(), this.lista));
        SQLiteHelper db = new SQLiteHelper(getContext());

        lista.clear();
        lista.addAll(db.getContacts());
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void onResume(){
        super.onResume();
        refleshListView();
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mReceiver, new IntentFilter("CONTACT"));
    }

    @Override
    public void onPause(){
        super.onPause();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refleshListView();
        }
    };

    //checa conexao com internet
    public boolean CheckConection() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        }
        catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }

        return false;
    }
}
2
  • O que é SQLiteHelper? 19/10/2017 às 10:38
  • É um Helper que cuida do sqlite, recebe os dados do webservice e guarda no celular, neste caso ele retorna a lista para o adapter do recycler view 19/10/2017 às 12:50

1 Resposta 1

0

Seu problema está relacionado ao ciclo de vida de um Fragment.

Veja que você está criando a componente do RecyclerView no método onViewCreated(), porém o correto para que a lista apareça desde a primeira vez é criar o componente no onCreateView().

Para exemplificar, veja este link: https://developer.android.com/samples/RecyclerView/src/com.example.android.recyclerview/RecyclerViewFragment.html#l89

onCreateView(): O sistema chama isso quando é o momento de o fragmento desenhar a interface do usuário pela primeira vez. https://developer.android.com/guide/components/fragments.html?hl=pt-br

Espero ter ajudado.

2
  • Perfeito! Obrigado Gustavo, descobri o erro, eu estava fazendo 3 requisiçoes web, sendo uma para logar e assim que ela retornasse mais 2 para preencher contatos, e mensagens (app de chat) porem estava chamando elas ao mesmo tempo e em seguida ja chamando o intent da tabview dos fragments, agora aninhei e chamei a próxima requisição quando a anterior terminar, ficou perfeito e nem precisou forçar reflesh 20/10/2017 às 0:26
  • Perfeito Julio, congrats! :) 24/10/2017 às 16:46

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .