Recycler view does not load when the app opens for the first time

0

I have recycler view within fragment in tablayout , being the main tab. After logging in, it does not load the data, only loads if I change tabs and return, or close and open APP.

Code:

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;
    }
}
    
asked by anonymous 19.10.2017 / 02:11

1 answer

0

Your issue is related to the life cycle of a Fragment.

See that you are creating the RecyclerView component in the onViewCreated () method, but the correct one for the list to appear the first time is to create the component in onCreateView ().

For example, see this link: link

  

onCreateView ():   The system calls this when it is time for the fragment to draw the user interface for the first time.    link

I hope I have helped.

    
19.10.2017 / 15:10