How to set values in a Fragment instead of an Activity using Drawer menu?

0

I created a sliding menu in my application and was able to call a fragment when I select the menu options but I'm having trouble printing the values in this fragment instead of using an Activity to display the data. Below the application code.

public class MainActivity extends AppCompatActivity {

    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;

    // como o mesmo botão é usado para criar e atualizar
    // precisamos rastrear se é uma atualização ou operação de criação
    // para isso, temos esse booleano
    boolean isUpdating = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Pegando referencia dos componentes
        editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextRealname = (EditText) findViewById(R.id.editTextRealname);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);

        //buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);

        progressBarList = (ProgressBar) findViewById(R.id.progressBarList);
        listView = (ListView) findViewById(R.id.listViewHeroes);

        heroList = new ArrayList<>();

        fabAddHero = (FloatingActionButton)findViewById(R.id.fabAddHero);
        fabAddHero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(MainActivity.this, AddHeroActivity.class);
                startActivity(it);
            }
        });
        //Método que retorna a lista de herois da base de dados
        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
        HeroAdapter adapter = new HeroAdapter(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")) {
                   // Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
                    //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;
        }
    }

    //Classe interna que cria uma adapter para exibir a lista de herois
    class HeroAdapter extends ArrayAdapter<Hero> {

        //our hero list
        List<Hero> heroList;

        //constructor to get the list
        public HeroAdapter(List<Hero> heroList) {
            super(MainActivity.this, R.layout.layout_hero_list, heroList);
            this.heroList = heroList;
        }

        //Metodo que retorna a lista de heroes
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);

            //Pegando referencia dos componentes
            TextView textViewName = listViewItem.findViewById(R.id.textViewName);
            TextView textViewRealname = listViewItem.findViewById(R.id.textViewRealname);

            //Pegando referencia dos textViews update e delete
            TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);

            final Hero hero = heroList.get(position);

            textViewName.setText(hero.getName());
            textViewRealname.setText(hero.getRealname());

            //Se o textview clicado for o update
            textViewUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(MainActivity.this, EditHeroActivity.class);
                    intent.putExtra("hero", hero);
                    startActivity(intent);
                }
            });

            return listViewItem;
        }
    }
}
    
asked by anonymous 17.01.2018 / 20:44

1 answer

1

To pass the pro fragment data you use arguments, like this:

MyFragment myFragment = new MyFragment();

Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);

To get the values inside the fragment, you use:

getArguments().getInt("someInt", 0);
    
18.01.2018 / 11:24