Run an Asynctask within a fragment with a listview

0

I have a Asynctask that gets data from a webservice and this data the user sees through a lisview, but now I want to enter the listview in a fragment . but I can not achieve it. Well the fragment appears where I am using VIewPAger that is automatically generated by Android Studio.

Fragment

 public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

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

            View rootView = inflater.inflate(R.layout.fragment_swipe_carros, container, false);
            //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            new AsyncRetrieve().execute();
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Carro 1";
                case 1:
                    return "Carro 2";
                case 2:
                    return "Carro 3";
                case 3:
                    return "Carro 4";
                case 4:
                    return "Carro 5";
            }
            return null;
        }
    }
    private class AsyncRetrieve extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(swipe_carros.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tCargando cuentas...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }


        @Override
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://bdauditorio.esy.es/ver_cuentas_expositor/vercuentasexpo.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {


                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");


                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();


                if (response_code == HttpURLConnection.HTTP_OK) {


                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }


                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }


        }


        @Override
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
                final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(swipe_carros.this);
                alertaDeError.setTitle("Error");
                alertaDeError.setMessage("Ups, no se han podido cargar las cuentas. Intentelo de nuevo.");
                alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertaDeError.create();
                alertaDeError.show();
            } else {
                //Existen Datos
                List<String> preguntas = new ArrayList<String>();
                //Parsea la respuesta obtenida por el Asynctask
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(result);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject preguntaDatos = null;
                        try {
                            preguntaDatos = jsonArray.getJSONObject(i);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        try {
                            assert preguntaDatos != null;
                            pregrespcomment =" Cuenta expositor " + "\n" +"- Correo electronico: "+ preguntaDatos.getString("email_expositor") + "\n"+"- Contraseña: " + preguntaDatos.getString("password_expositor");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        preguntas.add(pregrespcomment);

                    }

                    //crear el Adapter.
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(swipe_carros.this, android.R.layout.simple_list_item_1, preguntas);
                    //Asignas el Adapter a tu ListView para mostrar los datos.
                    mostrarr.setAdapter(adapter);
                    mostrarr.getAdapter().getCount();
                    Toast.makeText(getApplicationContext(), "Total de cuentas expositor creadas: " + mostrarr.getAdapter().getCount() , Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    e.printStackTrace();

                    final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(swipe_carros.this);
                    alertaDeError.setTitle("Error");
                    alertaDeError.setMessage("Ups, no existen cuentas para mostrar. Intentelo de nuevo.");
                    alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    alertaDeError.create();
                    alertaDeError.show();
                }
            }
        }


    }

And the Asynctask is outside the fragment but in the same class and the associated XML only contains the 'listview. The question is where do I use the asynctask and how do I execute it within the fragment.

    
asked by Ashley G. 08.10.2017 в 00:55
source

1 answer

0

I have reorganized your code and at AsyncTask remove the static , remember that when you declare something as static, it belongs to the class and not the object.

AsyncTask is your generic receives three types of data, this is generic AsyncTask<String, String, String> . The first data type defines the parameter that AsyncTask receives when it is called, if it is defined as type Void AsyncTask<Void, String, String> AsyncTask does not receive any type of parameter.

When you call AsyncTask you have to pass a parameter to it because you have defined it, if you do not want to pass a parameter when calling it, define the first type of data in the generic as Void .

public static class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {}


    public static PlaceholderFragment newInstance(int sectionNumber) {
    PlaceholderFragment fragment = new PlaceholderFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_lista_detalle_carros, container, false);
        // TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        ListView mostrar=(ListView) rootView.findViewById(R.id.lista);

        // Los llamas así. Al llamarlo antes te daba error porque lo estabas declarando
        // static. y lo estatic solo puede ser llamado directamente desde la clase, no 
        // desde un objeto y una instancia es un objeto.
        new AsyncRetrieve.execute();

        return rootView;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "CARRO 1";
                case 1:
                    return "CARRO 2";
                case 2:
                    return "CARRO 3";
                case 3:
                    return "CARRO 4";
                case 4:
                    return "CARRO 5";
            }
            return null;
        }
    }

    /*
     * Al definir el primer tipo de dato como Void, AsyncTask no recibe
     * parametros al ser llamado con el metodo execute().
     */
    private class AsyncRetrieve extends AsyncTask<Void, String, String> {

        ProgressDialog pdLoading = new ProgressDialog(lista_detalle_carros.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tCargando cuentas...");
            pdLoading.setCancelable(false);
            pdLoading.show();
        }


        @Override
        protected String doInBackground(String... params) {

            try {
                url = new URL("http://bdauditorio.esy.es/ver_cuentas_expositor/vercuentasexpo.php");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }

            try {


                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");


                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();


                if (response_code == HttpURLConnection.HTTP_OK) {


                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }


                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }
        }


        @Override
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
                final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(lista_detalle_carros.this);
                alertaDeError.setTitle("Error");
                alertaDeError.setMessage("Ups, no se han podido cargar las cuentas. Intentelo de nuevo.");
                alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertaDeError.create();
                alertaDeError.show();
            } else {
                //Existen Datos
                List<String> preguntas = new ArrayList<String>();
                //Parsea la respuesta obtenida por el Asynctask
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(result);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject preguntaDatos = null;
                        try {
                            preguntaDatos = jsonArray.getJSONObject(i);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        try {
                            assert preguntaDatos != null;
                            pregrespcomment =" Cuenta expositor " + "\n" +"- Correo electronico: "+ preguntaDatos.getString("email_expositor") + "\n"+"- Contraseña: " + preguntaDatos.getString("password_expositor");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        preguntas.add(pregrespcomment);

                    }

                    //crear el Adapter.
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(lista_detalle_carros.this, android.R.layout.simple_list_item_1, preguntas);
                    //Asignar el Adapter a tu ListView para mostrar los datos.
                    mostrarr.setAdapter(adapter);
                    mostrarr.getAdapter().getCount();
                    Toast.makeText(getApplicationContext(), "Total de cuentas expositor creadas: " + mostrarr.getAdapter().getCount() , Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    e.printStackTrace();

                    final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(lista_detalle_carros.this);
                    alertaDeError.setTitle("Error");
                    alertaDeError.setMessage("Ups, no existen cuentas para mostrar. Intentelo de nuevo.");
                    alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    alertaDeError.create();
                    alertaDeError.show();
                }
            }
        }
    }
}
    
answered by 08.10.2017 в 02:01