列表视图不更新超过一个项目

List View not updating beyond one item

我正在尝试将列表中的一项发送到另一个 activity 的 list.But 第二个 activity 即 MySchedule 不会更新超过一项。 这是我的代码

Activity 我从哪里发送字符串 (没有添加字符串的代码)

public class CloudEvents extends AppCompatActivity {

    static int scheduleId = -1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
     listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                new AlertDialog.Builder(CloudEvents.this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Save Event")
                        .setMessage("Do you want to save this event into your schedule?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            scheduleId++;

                                Toast.makeText(CloudEvents.this,"Saved",Toast.LENGTH_LONG).show();
                                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
                         sharedPreferences.edit().putString("CloudEvent",listView.getItemAtPosition(position).toString()).apply();
                                Intent i = new Intent(CloudEvents.this,MySchedule.class);
                                startActivity(i);


                               //myArrayAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No",null)
                        .show();

                return true;
            }
        });

Activity 接收字符串并制作列表

public class MySchedule extends AppCompatActivity {

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

    final ArrayList<String> schedule = new ArrayList<>();
    final ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);
    String key = "CloudEvent";

    String myEvent ="";

    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
    if(sharedPreferences.contains(key))
    {
        myEvent = sharedPreferences.getString(key,"");
        schedule.add(CloudEvents.scheduleId,myEvent);

    }
    final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);

    scheduleListView.setAdapter(myArrayAdapter);

    scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

            new AlertDialog.Builder(MySchedule.this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Are you sure ?")
                    .setMessage("Do you want to delete this note")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            schedule.remove(position);
                            myArrayAdapter.notifyDataSetChanged();
                            CloudEvents.scheduleId--;

                        }
                    })
                    .setNegativeButton("No",null)
                    .show();

            return true;
        }
    });

}
}

(添加一项后)

Error:Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
                      at java.util.ArrayList.add(ArrayList.java:457)
                      at com.yatin.whatshappeningdtu.MySchedule.onCreate(MySchedule.java:35)

绞尽脑汁好几个小时now.Please帮忙谢谢!

只需尝试 commit() 而不是 apply()

apply() 是在 2.3 中添加的,它提交时不会返回指示成功或失败的布尔值。

commit() returns 如果保存有效则为真,否则为假。

另外请确认用于读取数据的共享偏好实例与写入数据的实例相同。

当您第一次添加项目时,您的 CloudEvents.scheduleId 会从 -1 设置为 0。假设你的字符串是 "FirstEvent" 保存在 sharedpreference 的 CloudEvent 键中,然后在 MySchedule activity 中添加到 schedule arraylist 的 0 位置,并且它工作正常。

现在当你回到 CloudEvents activity 时,你的 CloudEvents.scheduleId 是 0 因为它是 statica 变量,你添加另一个项目让我们说 "SecondEvent",所以 CloudEvents.scheduleId 将从 0 变为 1,并且您将再次在 sharedpreference 中的 CloudEvent 键中保存 "SecondEvent" 字符串,以便先前的值 "FirstEvent" 将被 "SecondEvent" 覆盖意味着在 MySchedule activity 你只会从 sharedpreference 得到 "SecondEvent" ,但是你将它添加到 schedule arraylist 的第一个位置和 schedule arraylist 的第 0 个位置将留空。 现在你正在传递这个 arraylist,在第 0 个位置有 null 值,在 Listview 适配器中,这就是它抛出 IndexOutOfBoundsException 异常的方式。 为了解决这个问题,您可以维护一个ArrayList<String>。在CloudEvents activity中进行以下更改。

private ArrayList<String> eventList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState){

        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
        Collections.addAll(eventList, prefManager.getString("CloudEvent", "").split(","));

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                new AlertDialog.Builder(CloudEvents.this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Save Event")
                        .setMessage("Do you want to save this event into your schedule?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                scheduleId++;

                                eventList.add(listView.getItemAtPosition(position).toString());
                                Toast.makeText(CloudEvents.this, "Saved", Toast.LENGTH_LONG).show();

                                Intent i = new Intent(CloudEvents.this, MySchedule.class);
                                i.putStringArrayListExtra("EventList", eventList);                                   
                                startActivity(i);

                                //myArrayAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No", null)
                        .show();

                return true;
            }
        });
    }

现在 MySchedule activity 进行以下更改。

public class MySchedule 扩展 AppCompatActivity {

    ArrayList<String> schedule = new ArrayList<>();
    SharedPreferences sharedPreferences;

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

        sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);

        schedule = getIntent().getStringArrayListExtra("EventList");
        ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);

        final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);

        scheduleListView.setAdapter(myArrayAdapter);

        scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                new AlertDialog.Builder(MySchedule.this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Are you sure ?")
                        .setMessage("Do you want to delete this note")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                schedule.remove(position);
                                myArrayAdapter.notifyDataSetChanged();

                                String events = "";
                                for(int i=0; i<schedule.size(); i++){
                                    events = events + schedule.get(i);
                                    if(i != (schedule.size() - 1)){
                                        events = events + ",";
                                    }
                                }
                                sharedPreferences.edit().putString("CloudEvent", events).apply();
                            }
                        })
                        .setNegativeButton("No",null)
                        .show();

                return true;
            }
        });

    }
}