Asynchronous task never stops running

4

It's my first time explaining a programming problem in such a prestigious forum, so, I apologize if my question and explanation is not correct but I need help and I can not find a solution.

I am developing an app for Android on a puzzle, the case is that every time a player plays he must put a name and it is written in a database remote The problem I have when I give the option to list times (which is list players) I run the query correctly to the database but the asynchronous task never ends and does not continue running.

To be more exact, the ProgressDialog bar is never removed even after reaching the OnPostExecute method, although the BackGround tasks ended.

I have tried to finish the task by force but it does not do anything and I am sure that it carries out the operations because I have Log messages throughout the code and it shows me what is running.

Here I leave the code:

MAIN FRAGMENT

public class FragmentListaJugadores extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public FragmentListaJugadores() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment FragmentListaJugadores.
 */
// TODO: Rename and change types and number of parameters
public static FragmentListaJugadores newInstance(String param1, String param2) {
    FragmentListaJugadores fragment = new FragmentListaJugadores();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public static final String UPLOAD_URL = "http://158.49.96.138/josecarlos/selectJugadores.php";
ArrayList<Jugador> jugadores;
ListAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_lista_jugadores, container, false);
    ListView lista = (ListView) view.findViewById(R.id.listSelect);
    jugadores = new ArrayList<Jugador>();
    adapter = new ListAdapter(getActivity(), R.layout.list_jugador, jugadores);
    lista.setAdapter(adapter);

    return inflater.inflate(R.layout.fragment_lista_jugadores, container, false);
}
//METODO CON EL QUE EJECUTO LA TAREA ASINCRONA
public void onStart(){
    super.onStart();
    SeleccionarJugador sj=new SeleccionarJugador();
    sj.execute();
}


    //TAREA ASINCRONA 
    class SeleccionarJugador extends AsyncTask<Void, Void, String> {

        ProgressDialog loading;
        String result = new String();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(getActivity(), "Obteniendo datos...", "Por favor Espere...", true, true);
        }

        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();

        }

        @Override
        protected String doInBackground(Void... params) {
            Log.i("INF", "LLega al background");
            selectJug();//LLAMO A UN METODO EXTERNO DONDE REALIZO LA CONEXION

            return result;
        }
    }

 //METODO QUE CONECTA CON LA BBDD Y RECOGE LOS DATOS CON UN JSON
public void selectJug(){
    URL url;
    String result = "";
    try {
        url = new URL(UPLOAD_URL);

        Log.i("INF","LLega a send url "+UPLOAD_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(150000);
        conn.setConnectTimeout(150000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        InputStream os = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(os));


        String line;

        while ((line = reader.readLine()) != null) {
            result+=line+"\n";
        }
        Log.i("INF", "result es " + result);//ME ASEGURO QUE SE HAN COGIDO CORRECTAMENTE
        os.close();
        conn.disconnect();//UNA VEZ COGIDOS LOS DATOS CIERRO LA CONEXION
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        Log.i("json","Salio de consulta");
        result=result.substring(result.indexOf("["));
        JSONArray jArray = new JSONArray(result.toString());
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);
            Log.i("INF", "id " + json_data.getString("Id") + " nombre " + json_data.getString("Nombre") + " mov " + json_data.getString("Movimientos") + " tiempo " + json_data.getString("Tiempo"));//ME ASEGURO QUE NO SE PIERDEN LOS DATOS DESPUES DE LA CONEXION
            Jugador p = new Jugador();
            p.setId(json_data.getInt("Id"));
            p.setNombre(json_data.getString("Nombre"));
            p.setMov(json_data.getString("Movimientos"));
            p.setTiempo(json_data.getString("Tiempo"));
            jugadores.add(p);//AÑADO LO JUGADORES A UNA LISTA PARA MOSTRARLOS
        }
    } catch (Exception e) {
        Log.e("ERROR", "Error pasting data " + e.toString());
    }
}

}

LIST ADAPTER

 public class ListAdapter extends ArrayAdapter<Jugador>{
 int groupid;
 ArrayList<Jugador> records;
Context context;

public ListAdapter(Context context, int vg, ArrayList<Jugador>records) {
    super(context,vg,records);
    this.context = context;
    groupid = vg;
    this.records = records;
}



public View getView(int position, View convertView, ViewGroup parent) {
    Log.i("INF","ha entrado en listAdapter");
    View row=convertView;
    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(groupid, parent, false);
        TextView textName = (TextView) row.findViewById(R.id.pro_nombre);
        textName.setText(records.get(position).getNombre());
        TextView textMov = (TextView) row.findViewById(R.id.pro_mov);
        textMov.setText(records.get(position).getMov());
        TextView textTiempo = (TextView) row.findViewById(R.id.pro_tiempo);
        textTiempo.setText(records.get(position).getTiempo());
    }
    return row;
}
}

LAYOUT OF THE LIST FRAGMENT

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.josecarlos.puzzlepractica.FragmentListaJugadores">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listSelect"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="50dp" />
</RelativeLayout>

</FrameLayout>

ADAPTER LAYOUT

 <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >

<TextView
    android:id="@+id/pro_nombre"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginRight="10dp"
    android:textSize="20sp"
    android:text="nombre" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:id="@+id/pro_mov"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:text="movimientos" />

<TextView
    android:id="@+id/pro_tiempo"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:textSize="20sp"
    android:layout_alignParentRight="true"
    android:text="tiempo" />


</RelativeLayout>

I hope you have explained me correctly and that you can help me with my problem.

    
asked by JoseCa 18495 27.12.2016 в 23:05
source

2 answers

1

in the SelectPlayer class in the onPostExecute method

@Override
protected void onPostExecute(String s)
{
    super.onPostExecute(s);
    try
    {
        sj.finalize(); //agrega esto 
        loading.dismiss();

    }
    catch (Throwable throwable)
    {
        throwable.printStackTrace();
    }
}

There must be something similar, I hope I helped you

    
answered by 13.05.2017 в 21:14
0

Try to create the variable ProgressDialog loading; at the level of the main class

and in the method onPostExecute pon

loading.hide(); 

instead of loading.dismmis();

    
answered by 06.03.2017 в 18:19