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.