2013-06-25 7 views
0

J'ai une application et chaque fois qu'un utilisateur démarre l'application, il crée une nouvelle entrée dans la base de données. En outre, il devrait y avoir une fonction qui supprime le registre de l'utilisateur lorsque l'utilisateur se ferme. Pour ces 2 fonctions j'ai 2 asynctasks. le premier fonctionne bien, ce qui crée l'utilisateur dans la base de données. Cependant, bien qu'il n'y ait aucune erreur, l'asynctask qui devrait supprimer l'utilisateur ne fait rien quand onDestroy() est appelé. J'ai testé avec onPause() et l'application supprime l'utilisateur mais je ne sais pas pourquoi ne fonctionne pas onDestroy(). Voici le code correspondant que j'utilise:Android: Asynctask ne fonctionne pas lorsqu'il est appelé onDestroy

public class Titulacion extends Activity { 

    @Override 
public void onDestroy(){ 
super.onDestroy(); 
new Borrar().execute(); 
// UIHelper.killApp(true); 
    } 

    public static int titulacion; 
    Button bAceptar; 
    RadioGroup radGrp; 
    RadioButton radBot1; 
    RadioButton radBot2; 
    RadioButton radBot3; 
    RadioButton radBot4; 
    ImageButton bAdmin; 
    static int nTest = 0; 
    private ProgressDialog pDialog; 
    private static final String TAG_SUCCESS = "success"; 
    JSONParser jsonParser = new JSONParser(); 
    private static final int DIALOG_CONFIRMAR_USUARIO = 0; 
    int level = -1; 
    String levelstring; 
    int pid; 
    static String pids; 
    BroadcastReceiver batteryReceiver; 
    String url = "10.0.0.13"; 
    private static String url_crear = "http://10.0.0.13/subida/create_candidato.php"; 
    private static final String url_delete = "http://10.0.0.13/subida/delete_candidato.php"; 

    @SuppressLint("NewApi") 
    static String device_id = Build.SERIAL; 
    static String PDA = device_id.substring(device_id.length() - 6); 


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

     setContentView(R.layout.titulacion); 
     batteryReceiver = new BroadcastReceiver() { 
      int scale = -1; 
      int voltage = -1; 
      int temp = -1; 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); 
       levelstring = String.valueOf(level)+"%"; 
       scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); 
       temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); 
       voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); 
      } 
     }; 
     IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 
     registerReceiver(batteryReceiver, filter); 




     radGrp = (RadioGroup) findViewById(R.id.titGroup); 
     radBot1 = (RadioButton) findViewById(R.id.bot_superior); 
     radBot2 = (RadioButton) findViewById(R.id.bot_medio); 
     radBot3 = (RadioButton) findViewById(R.id.bot_tecnico); 
     radBot4 = (RadioButton) findViewById(R.id.bot_administrativo); 
     bAdmin = (ImageButton) findViewById(R.id.administradorinit); 
     bAceptar = (Button) findViewById(R.id.BtnAceptar); 
     StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); 

     boolean isReachable = false; 
     try{ 
      isReachable = InetAddress.getByName("10.0.0.13").isReachable(1000); 
     } catch (Exception e){ 
      Log.e("InetAddress", e.getMessage()); 




     }finally { 
      if (isReachable) { 
       new CreateCandidato().execute(); 


      }else{ 
       Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show(); 
      } 

     } 


     bAceptar.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (radBot1.isChecked()) { 
        titulacion = 1; 
        Intent i = new Intent(Titulacion.this, Ident.class); 
        startActivity(i); 
        unregisterReceiver(batteryReceiver); 

       } else if (radBot2.isChecked()) { 
        titulacion = 2; 
        Intent i = new Intent(Titulacion.this, Ident.class); 
        startActivity(i); 
        unregisterReceiver(batteryReceiver); 

       } 

       else if (radBot3.isChecked()) { 

        titulacion = 3; 
        Intent i = new Intent(Titulacion.this, MenuInterna.class); 
        startActivity(i); 
        unregisterReceiver(batteryReceiver); 

       } 

       else if (radBot4.isChecked()) { 
        titulacion = 4; 
        Intent i = new Intent(Titulacion.this, MenuSup.class); 
        startActivity(i); 
        unregisterReceiver(batteryReceiver); 

       } 
      } 
     }); 
     bAdmin.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(Titulacion.this, Admin.class); 
       startActivity(i); 
       unregisterReceiver(batteryReceiver); 

      } 
     }); 
    } 
    class CreateCandidato extends AsyncTask<String, String, String> { 


     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Titulacion.this); 
      pDialog.setMessage("Actualizando .."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 


     protected String doInBackground(String... args) { 

      try { 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("nserie", PDA)); 
      params.add(new BasicNameValuePair("bateria", levelstring)); 


      JSONObject json = jsonParser.makeHttpRequest(url_crear, 
        "POST", params); 

      Log.d("Create Response", json.toString()); 



       pid = json.getInt("id"); 
       pids = String.valueOf(pid); 


       int success = json.getInt(TAG_SUCCESS); 


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

      return null; 
     } 

     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 


     } 

    } 
    class Borrar extends AsyncTask<String, String, String> { 


     @Override 
     protected void onPreExecute() { 

     super.onPreExecute(); 
     Log.d("LLEGA1", "LLEGA1"); 

    } 


     protected String doInBackground(String... args) { 

      // Check for success tag 
      int success; 
      try { 

      } catch (Exception e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      try { 


       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("id", Titulacion.getPID())); 


       JSONObject json = jsonParser.makeHttpRequest(
         url_delete, "POST", params); 


       Log.d("Delete Product", json.toString()); 

       success = json.getInt("success"); 

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

      return null; 
     } 


     protected void onPostExecute(String file_url) { 
      Log.d("llega", "LLEGA"); 



     } 

    } 

Merci pour votre aide

+0

si ma réponse est aidé à u ne pas oublier de l'accepter –

Répondre

1

Votre activité est détruite mais le AsyncTask fait son travail (travail en arrière-plan). Il n'y aura pas de ANR parce que vous ne faites aucun arrière-plan sur l'interface utilisateur. Si vous mettez à jour une vue sur votre interface utilisateur une fois AsyncTask terminée, il y aura un NULLPOINTERException. Mais, ce ne serait pas une bonne idée d'exécuter AsyncTask dans onDestroy().

utilisation asyntask dans onDestroy() à la place, vous pouvez avoir une activité qui étend IntentService et donner un appel à cette activité de OnDestroy

+0

Ok Merci Dixit Patel, je vais essayer pour en savoir plus dans IntentService – Katherine99

Questions connexes