2016-04-14 1 views
1

Я пытаюсь обновить представление списка после того, как пользователь удалил запись. Я нашел, что мне нужно было использовать notifyDataSetChanged(). Но для этого мне нужно сначала обновить arrayList (правильно?). Но я не могу это изменить, потому что этот список объявлен окончательным.Обновление окончательного списка перед обновлением arrayAdapter/listView

Это окончательный, потому что он мне нужен в методе getView, и в противном случае Android Studio жалуется на то, что не сможет получить доступ к нему через внутренний класс.

Соответствующий код:

 final List<String> arrayList = mydb.getAllAlarms(); 
     final List<String> timesList = mydb.getAllAlarmTimes(); 
     final ArrayList<Integer> arrayListID = mydb.getAllAlarmIDs(); 

     boolean isEmpty = false; 
     if (arrayList.isEmpty()) { //default 
      arrayList.add("You have no alarms"); 
      timesList.add(""); 
      isEmpty = true; 
     } 

     //initialise arrayadapter to show stuff in the listview 
     final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), 
       android.R.layout.simple_list_item_2, android.R.id.text1, arrayList) { 
      public View getView(int position, View convertView, ViewGroup parent) { 

       TextView text1 = (TextView) convertView.findViewById(android.R.id.text1); 
       TextView text2 = (TextView) convertView.findViewById(android.R.id.text2); 
       text1.setText(arrayList.get(position)); 
       text2.setText(timesList.get(position)); 
       return convertView; 
      } 
     }; 

     final ListView listView = (ListView) findViewById(R.id.listView1); 
     listView.setAdapter(arrayAdapter); //set our custom adapter to the listview 

     if (!isEmpty) { //only set clicklistener if there are alarms 
      //set clicklistener for items in the listview 
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       //... 
      }); 
      listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
       @Override 
       public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 

        //first, find the corresponding database id 
        final int idToDelete = arrayListID.get(position); 

        //show dialog 
        AlertDialog.Builder alert = new AlertDialog.Builder(
          MainActivity.this); 
        alert.setTitle("Delete alarm"); 
        alert.setMessage("Are you sure?"); 
        alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          mydb.deleteAlarm(idToDelete); 
          //cancel alarm as well 
          ShowAlarm.cancelAlarmIfExists(getApplicationContext(), idToDelete); 

          dialog.dismiss(); 

         } 
        }); 

        //... 
        alert.show(); 

        //PROBLEM LIES HERE 

        //reload listview 
//     arrayList = mydb.getAllAlarms(); //not possible because final List 

        arrayAdapter.clear(); 
        arrayAdapter.addAll(arrayList); 

        arrayAdapter.notifyDataSetChanged(); 
//     listView.invalidateViews(); 
//     listView.setAdapter(arrayAdapter); 

        return true; 
       } 
      }); 

     } 
+0

Скопируйте этот список в другой список и использовать, чтобы установить adapter –

+0

Вы можете сделать это 'arrayAdapter.addAll (mydb.getAllAlarms());' или 'arrayList.clear(); arrayList.addAll (mydb.getAllAlarms()); '. Нет необходимости повторно инициализировать список, чтобы изменить его. – Titus

+0

@Titus Ah Я не знал, что вам не нужно редактировать тот же самый массив. Кажется логичным, как-то listView по-прежнему не обновляется, хотя после 'clear()' и 'addAll'. – PHPirate

ответ

1

вы можете использовать arrayAdapter.getItem(position);, чтобы получить объект из ArrayList и выполнить операцию так, что он будет правильно отражен

+0

, пожалуйста, воздержитесь от него также –

+0

Конечно, возвышение друг друга здесь и там заслуживает;) – PHPirate

 Смежные вопросы

  • Нет связанных вопросов^_^