Recycler view does not load when the app first opens

Asked

Viewed 242 times

0

I have a recycler view within a fragment in a tablayout, being the main tab. After logging in, it does not load the data, only loads if I change tab and return, or close and open the 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;
    }
}
  • What is SQLiteHelper?

  • It is a Helper that takes care of the sqlite, receives the data from the webservice and stores on the mobile, in this case it returns the list to the Adapter of the Recycler view

1 answer

0


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

Note that you are creating the Recyclerview component in the onViewCreated() method, but the right thing for the list to appear from the first time is to create the component in onCreateView().

For example, see this link: https://developer.android.com/samples/RecyclerView/src/com.example.android.recyclerview/RecyclerViewFragment.html#l89

onCreateView(): The system calls this when it is time for the fragment to draw the user interface for the first time. https://developer.android.com/guide/components/fragments.html?hl=pt-br

I hope I’ve helped.

  • Perfect! Thanks Gustavo, I discovered the error, I was making 3 requests web, one to log in and as soon as she returned 2 more to fill contacts, and messages (chat app) however I was calling them at the same time and then already calling the tab of the Fragments, now I nested and called the next request when the previous one finished, it was perfect and did not need to force reflesh

  • Perfect Julio, Congrats! :)

Browser other questions tagged

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