Comment vider complètement un Hashmap

asmalak Messages postés 10 Statut Membre -  
BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   -
Bonjour,
Je veux supprimer tous les éléments d'un Hashmap , voici une partie du code

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

    // associate the button from interface to code
    initInterface();
    addButtonClickListner();
    HistFile = (HistoryFileManager) getIntent().getParcelableExtra(
            MainActivity.PAR_KEY);
    // Adding menuItems to ListView
    // android.R.layout.activity_list_item;
    final ListAdapter adapter = new SimpleAdapter(this, HistFile.menuItems,
            R.layout.list_application, new String[] {
                    HistFile.KEY_NOM_APPLICATION,
                    HistFile.KEY_DATE_CREATION },
            new int[] { R.id.textViewNameApplication,
                    R.id.textViewDateCreation });


    listView1.setAdapter(adapter);
            btn_Supprimer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(v
                    .getContext());

            DialogInterface.OnClickListener listenerYes = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //Qu'est ce que je doit faire là

                    Toast.makeText(getApplicationContext(),
                            "Suppression réussie", Toast.LENGTH_SHORT)
                            .show();
                }
            };

            DialogInterface.OnClickListener listenerNo = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }
            };

            builder.setMessage(R.string.supprimerAllApplications)
                    .setPositiveButton(R.string.yes, listenerYes)
                    .setNegativeButton(R.string.no, listenerNo);

            AlertDialog d = builder.create();
            d.setTitle("Supprimer historique");
            d.show();
        }
    });
}


2 réponses

  1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 930
     
    0
    1. asmalak Messages postés 10 Statut Membre
       
      j'essayé avec ça , mais il y a un problème "Unfortunately,nom_application has stopped"
      0
    2. asmalak Messages postés 10 Statut Membre
       
      FATAL EXCEPTION:main

      Java.lang.NullPoiterException Attempt to invoke virtual method void 'java.Hashmap.clear()' on a null object reference
      0
    3. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 930
       
      euh...le message ne veut pas dire que ta hashMap est null?
      0
    4. asmalak Messages postés 10 Statut Membre
       
      non elle n'est pas null !!
      0
  2. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 930
     
    Sans code, pas facile de t'aider...
    0
    1. asmalak Messages postés 10 Statut Membre
       
      une partie de MainActivity
      public class MainActivity extends Activity {

      static String nom_application,api,string_messagerie,string_repertoire,string_calculatrice,string_calendrier,string_mms;
      static String string_phone,string_gallery,string_navigateur,description_application,String_IP;
      Button btn_HistApp;
      Button btn_saveApp;
      // déclaretion des checkBox , radioButton ,....


      public final static String PAR_KEY = "com.pfe.bls.par";

      HistoryFileManager HistFile = new HistoryFileManager();

      btn_HistApp.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
      Intent myintent = new Intent(v.getContext(),
      HistoriqueActivity.class);
      Bundle mBundle = new Bundle();

      HistFile.putMenuItems();
      mBundle.putParcelable(PAR_KEY, HistFile);
      myintent.putExtras(mBundle);

      startActivityForResult(myintent, operation);
      }
      });

      btn_saveApp.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
      List<String> listInfo = new ArrayList<String>();
      String dateCreation, heureCreation;
      dateCreation = new SimpleDateFormat("dd/MM/yyyy").format(System
      .currentTimeMillis());
      heureCreation = new SimpleDateFormat("HH:mm:ss").format(System
      .currentTimeMillis());

      listInfo.add(dateCreation + "," + heureCreation);

      listInfo.add(edit_AppName.getText().toString());

      if (rb_ApiLocal.isChecked())
      listInfo.add(Integer.toString(sdkVersion));
      if (rb_Api18.isChecked())
      listInfo.add("18");
      if (rb_Api19.isChecked())
      listInfo.add("19");
      if (rb_Api20.isChecked())
      listInfo.add("20");

      listInfo.add(edit_AppDescr.getText().toString());

      if (cb_Calc.isChecked())
      listInfo.add(HistFile.KEY_CALCULATRICE);
      else
      listInfo.add("0");

      if (cb_Cal.isChecked())
      listInfo.add(HistFile.KEY_CALENDRIER);
      else
      listInfo.add("0");

      if (cb_Msg.isChecked())
      listInfo.add(HistFile.KEY_MESSAGERIE);
      else
      listInfo.add("0");

      if (cb_Rep.isChecked())
      listInfo.add(HistFile.KEY_REPARTOIRE);
      else
      listInfo.add("0");

      if (cb_Mms.isChecked())
      listInfo.add(HistFile.KEY_Mms);
      else
      listInfo.add("0");

      if (cb_Appel.isChecked())
      listInfo.add(HistFile.KEY_APPEL);
      else
      listInfo.add("0");

      if (cb_Galerie.isChecked())
      listInfo.add(HistFile.KEY_Galerie);
      else
      listInfo.add("0");

      if (cb_Navig.isChecked())
      listInfo.add(HistFile.KEY_Navigateur);
      else
      listInfo.add("0");

      HistFile.addApplication(listInfo);

      if (HistFile.getCountApplication() == 0)
      btn_HistApp.setEnabled(false);
      else
      btn_HistApp.setEnabled(true);

      operation = HistFile.getCurrentID();
      }});

      partie de la calsse HistoriqueActivity



      public class HistoriqueActivity extends Activity {

      private HistoryFileManager HistFile;
      Intent myintent;
      HashMap<String, String> Info;


      Button btn_Supprimer;
      TextView textView;
      ListView listView1;

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

      // associate the button from interface to code
      initInterface();
      addButtonClickListner();
      HistFile = (HistoryFileManager) getIntent().getParcelableExtra(
      MainActivity.PAR_KEY);
      // Adding menuItems to ListView
      // android.R.layout.activity_list_item;
      final ListAdapter adapter = new SimpleAdapter(this, HistFile.menuItems,
      R.layout.list_application, new String[] {
      HistFile.KEY_NOM_APPLICATION,
      HistFile.KEY_DATE_CREATION },
      new int[] { R.id.textViewNameApplication,
      R.id.textViewDateCreation });

      listView1.setAdapter(adapter);

      listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parentAdapter, View view,
      int position, long id) {

      Info = (HashMap<String, String>) listView1
      .getItemAtPosition(position);

      String msg = "Nom Application : "
      + Info.get(HistFile.KEY_NOM_APPLICATION) + "\n"
      + "Date création : "
      + Info.get(HistFile.KEY_DATE_CREATION) + "\n"
      + "Version SDK :" + Info.get(HistFile.KEY_VERSION_SDK)
      + "\n" + "Description :"
      + Info.get(HistFile.KEY_DESCRIPTION) + "\n"
      + "Services :";
      if (Info.get(HistFile.KEY_CALCULATRICE).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_CALCULATRICE);

      if (Info.get(HistFile.KEY_CALENDRIER).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_CALENDRIER);

      if (Info.get(HistFile.KEY_MESSAGERIE).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_MESSAGERIE);

      if (Info.get(HistFile.KEY_REPARTOIRE).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_REPARTOIRE);

      if (Info.get(HistFile.KEY_Mms).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_Mms);

      if (Info.get(HistFile.KEY_APPEL).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_APPEL);

      if (Info.get(HistFile.KEY_Galerie).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_Galerie);

      if (Info.get(HistFile.KEY_Navigateur).compareTo("0") != 0)
      msg = msg + "\n - " + Info.get(HistFile.KEY_Navigateur);

      AlertDialog.Builder builder = new AlertDialog.Builder(
      HistoriqueActivity.this);

      DialogInterface.OnClickListener listenerYes = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
      int code = Integer.parseInt(Info.get(HistFile.KEY_ID));
      setResult(code);
      HistoriqueActivity.this.finish();
      }
      };

      DialogInterface.OnClickListener listenerNo = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
      }
      };

      builder.setMessage(msg)
      .setPositiveButton(R.string.SelectYes, listenerYes)
      .setNegativeButton(R.string.SelectNo, listenerNo);

      AlertDialog d = builder.create();
      d.setTitle("Informations");
      d.show();

      }

      });


      //récupération du bouton delete d'un item
      Button btn_DeleteItem = (Button)findViewById(R.id.buttonDeleteItem);

      }
      });




      btn_Supprimer.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
      AlertDialog.Builder builder = new AlertDialog.Builder(v
      .getContext());

      DialogInterface.OnClickListener listenerYes = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {

      Info.clear();

      Toast.makeText(getApplicationContext(),
      "Suppression réussie", Toast.LENGTH_SHORT)
      .show();
      }
      };

      DialogInterface.OnClickListener listenerNo = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
      // User cancelled the dialog
      }
      };

      builder.setMessage(R.string.supprimerAllApplications)
      .setPositiveButton(R.string.yes, listenerYes)
      .setNegativeButton(R.string.no, listenerNo);

      AlertDialog d = builder.create();
      d.setTitle("Supprimer historique");
      d.show();
      }
      });

      }

      private void initInterface() {
      /*
      • Ici vousdevez faire toute les associations entre l'interface et le * code cource */ btn_Retour = (Button) findViewById(R.id.btnRetour); btn_Actualiser = (Button) findViewById(R.id.bntActualiser); btn_Supprimer = (Button) findViewById(R.id.bntSupprimer); textView = (TextView) findViewById(R.id.textView); listView1 = (ListView) findViewById(R.id.listView1); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.historique, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}


    2. la classe HistoryFileManager



      @SuppressLint("SdCardPath")
      public class HistoryFileManager implements Parcelable {





      private String filePath = "/data/data/com.pfe.bls/historique.xml";
      private File xmlFile = null;

      public Document doc = null;
      private DocumentBuilder dBuilder;
      private DocumentBuilderFactory dbFactory;

      private int CurrentID = -1;

      public ArrayList<HashMap<String, String>> menuItems;

      public int getCurrentID() {
      return CurrentID;
      }

      public void setCurrentID(int ID){
      this.CurrentID = ID;
      }

      public int getCountApplication() {
      Element item = doc.getDocumentElement();
      NodeList listApplication = item.getElementsByTagName("Application");
      return listApplication.getLength();
      }

      public void addApplication(List<String> listInfo) {
      // ajouter l'application dans le le fichier xml
      }






      public List<String> getCurrentApplication() {
      List<String> listInfo = new ArrayList<String>();
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("Application");
      for (int i = 0; i < nList.getLength(); i++) {
      Element nNode = (Element) nList.item(i);
      if (Integer.parseInt(nNode.getAttribute(KEY_ID)) == CurrentID) {
      listInfo.add(nNode.getElementsByTagName(KEY_DATE_CREATION)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_NOM_APPLICATION)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_VERSION_SDK)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_DESCRIPTION)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_CALCULATRICE)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_CALENDRIER).item(0)
      .getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_MESSAGERIE).item(0)
      .getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_REPARTOIRE).item(0)
      .getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_Mms)
      .item(0).getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_APPEL).item(0)
      .getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_Galerie).item(0)
      .getTextContent());
      listInfo.add(nNode.getElementsByTagName(KEY_Navigateur).item(0)
      .getTextContent());
      }
      }
      return listInfo;
      }

      public void putMenuItems() {
      menuItems = new ArrayList<HashMap<String, String>>();
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("Application");

      for (int i = 0; i < nList.getLength(); i++) {
      // creating new HashMap
      HashMap<String, String> map = new HashMap<String, String>();
      Element nNode = (Element) nList.item(i);
      map.put(KEY_ID, nNode.getAttribute(KEY_ID));
      map.put(KEY_DATE_CREATION,
      nNode.getElementsByTagName(KEY_DATE_CREATION).item(0)
      .getTextContent());
      map.put(KEY_NOM_APPLICATION,
      nNode.getElementsByTagName(KEY_NOM_APPLICATION).item(0)
      .getTextContent());
      map.put(KEY_VERSION_SDK, nNode
      .getElementsByTagName(KEY_VERSION_SDK).item(0)
      .getTextContent());
      map.put(KEY_DESCRIPTION, nNode
      .getElementsByTagName(KEY_DESCRIPTION).item(0)
      .getTextContent());
      map.put(KEY_CALCULATRICE,
      nNode.getElementsByTagName(KEY_CALCULATRICE).item(0)
      .getTextContent());
      map.put(KEY_CALENDRIER, nNode.getElementsByTagName(KEY_CALENDRIER)
      .item(0).getTextContent());
      map.put(KEY_MESSAGERIE, nNode.getElementsByTagName(KEY_MESSAGERIE)
      .item(0).getTextContent());
      map.put(KEY_REPARTOIRE, nNode.getElementsByTagName(KEY_REPARTOIRE)
      .item(0).getTextContent());
      map.put(KEY_Mms,
      nNode.getElementsByTagName(KEY_Mms).item(0)
      .getTextContent());
      map.put(KEY_APPEL, nNode.getElementsByTagName(KEY_APPEL).item(0)
      .getTextContent());
      map.put(KEY_Galerie, nNode.getElementsByTagName(KEY_Galerie).item(0)
      .getTextContent());
      map.put(KEY_Navigateur, nNode.getElementsByTagName(KEY_Navigateur).item(0)
      .getTextContent());
      // adding HashList to ArrayList
      menuItems.add(map);
      }
      }









      private int getID() {
      int maxID = 0;

      if (getCountApplication() == 0)
      return maxID+1;
      else {
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("Application");
      for (int i = 0; i < nList.getLength(); i++) {
      Element nNode = (Element) nList.item(i);
      int localID = Integer.parseInt(nNode.getAttribute(KEY_ID));
      if (localID > maxID)
      maxID = localID;
      }
      return maxID + 1;
      }
      }



      //Partie obligatoire qui est relative au traitement de la sérialisation.
      //Parcelable permet de faire passer des données entre les activité.
      //En fait MainActivity.java instancie la classe HistoryFileManager.java et dans la
      //classe HistoryActivity.java on a spécifiquement besoin de la variable menuItems
      //pour pouvoir afficher les info avec le ListView

      public static final Creator<HistoryFileManager> CREATOR = new Creator<HistoryFileManager>() {
      @Override
      public HistoryFileManager createFromParcel(Parcel source) {
      HistoryFileManager mHistFile = new HistoryFileManager();
      mHistFile.filePath = source.readString();
      mHistFile.menuItems = (ArrayList<HashMap<String, String>>) source
      .readSerializable();
      return mHistFile;
      }

      @Override
      public HistoryFileManager[] newArray(int size) {
      return new HistoryFileManager[size];
      }
      };

      @Override
      public int describeContents() {
      // TODO Auto-generated method stub
      return 0;
      }

      @Override
      public void writeToParcel(Parcel arg0, int arg1) {
      // TODO Auto-generated method stub
      arg0.writeString(filePath);
      arg0.writeSerializable(menuItems);
      }


0
  1. BunoCS Messages postés 436 Date d'inscription   Statut Modérateur Dernière intervention   3 930 > asmalak Messages postés 10 Statut Membre
     
    Euh....Juste la partie concernant la HashMap me suffira, merci
    ;)
    0