How to initialize the components of a layout in the onCreate of a Fragment?

Asked

Viewed 132 times

1

I created a Fragment to show a list of items, but I need to initialize two components a listview and a Progressbar on onCreate but I don’t have the reference of the layout file they are. How do I boot them into onCreate? Below follows the code.

public class HerosFragment extends Fragment {

    private static final int CODE_GET_REQUEST = 1024;
    private static final int CODE_POST_REQUEST = 1025;

    //Variaveis dos componentes
    EditText editTextHeroId, editTextName, editTextRealname;
    RatingBar ratingBar;
    Spinner spinnerTeam;
    ProgressBar progressBarList;
    ListView listView;

    FloatingActionButton fabAddHero;

    //vamos usar essa lista para exibir herói na lista
    List<Hero> heroList;

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

        //Preciso inicializar esses dois componentes mas não consigo
        progressBarList = (ProgressBar) findViewById(R.id.progressBarList);
        listView = (ListView) findViewById(R.id.listViewHeroes);

        heroList = new ArrayList<>();
        readHeroes();
    }

    //Recupera os dados dos herois do banco de dados
    private void readHeroes() {
        PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
        request.execute();
    }

    //Para atualizar a lista de herois
    private void refreshHeroList(JSONArray heroes) throws JSONException {
        //limpa herois anteriores
        heroList.clear();

        //Cria uma nova lista com os herois atualizados do JSON de resposta
        for (int i = 0; i < heroes.length(); i++) {
            //getting each hero object
            JSONObject obj = heroes.getJSONObject(i);

            //adiciona os herois a lista
            heroList.add(new Hero(
                    obj.getInt("id"),
                    obj.getString("name"),
                    obj.getString("realname"),
                    obj.getInt("rating"),
                    obj.getString("teamaffiliation")
            ));
        }

        //cria um adapter com a lista de herois
        CustomAdapterHero adapter = new CustomAdapterHero(this.getActivity(), heroList);
        listView.setAdapter(adapter);
    }

    //classe interna para executar solicitação de rede estendendo um AsyncTask
    private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {

        //o URL onde precisa enviar a solicitação
        String url;

        //Os parametros
        HashMap<String, String> params;

        //O código do pedido para definir se é um GET ou POST
        int requestCode;

        //Construtor para inicializar os valores
        PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
            this.url = url;
            this.params = params;
            this.requestCode = requestCode;
        }

        //Quando a tarefa começou a exibir uma barra de progresso
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBarList.setVisibility(View.VISIBLE);
        }

        //Este método dará a resposta do pedido
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBarList.setVisibility(GONE);
            try {
                JSONObject object = new JSONObject(s);
                if (!object.getBoolean("error")) {
                    //atualizando o herolista após cada operação
                    //então nós conseguimos uma lista atualizada
                    refreshHeroList(object.getJSONArray("heroes"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //A operação da rede será realizada em segundo plano
        @Override
        protected String doInBackground(Void... voids) {
            RequestHandler requestHandler = new RequestHandler();

            if (requestCode == CODE_POST_REQUEST)
                return requestHandler.sendPostRequest(url, params);


            if (requestCode == CODE_GET_REQUEST)
                return requestHandler.sendGetRequest(url);

            return null;
        }
    }

}

1 answer

0


You need to inflate the fragment layout in the method onCreateView. Example:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_heroes, container, false);
    progressBarList = (ProgressBar) rootView.findViewById(R.id.progressBarList);
    listView = (ListView) rootView.findViewById(R.id.listViewHeroes);
    return rootView;

}

Substitute fragment_heroes by name of the layout of your Fragment.

The other actions you’re doing on onCreate, you’ll probably have to do them on onResume, or in the onViewCreated.

Browser other questions tagged

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