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

时间:2017-02-16 10:04:40

标签: android listview arraylist android-arrayadapter

我试图在长时间点击到另一个活动的列表时发送一个列表项。但是第二个活动,即MySchedule不会更新超出一个项目。 这是我的代码

我发送字符串的活动 (没有添加字符串代码)

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;
            }
        });

活动接收字符串并制作列表

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)

现在正在绞尽脑汁。请帮助谢谢!

2 个答案:

答案 0 :(得分:0)

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

在2.3中添加了

apply(),它提交时没有返回表示成功或失败的布尔值。

如果保存起作用,

commit()将返回true,否则返回false。

另请确认用于读取数据的共享首选项实例与写入数据的实例相同。

答案 1 :(得分:0)

第一次添加项目时,CloudEvents.scheduleId从-1设置为0。假设您的字符串"FirstEvent"保存在共享偏好的CloudEvent键中,然后在MySchedule个活动中,它被添加到schedule arraylist的0位置,并且它可以正常工作。

现在,当您返回CloudEvents活动时,您的CloudEvents.scheduleId为0,因为它是statica变量,而您添加了另一个项目,例如"SecondEvent",因此CloudEvents.scheduleId会更改从0到1,您将在"SecondEvent"密钥中再次将CloudEvent字符串保存在共享首选项中,以便之前的值"FirstEvent"将覆盖"SecondEvent",这意味着MySchedule您只能从共享偏好中获得"SecondEvent"活动,但是您要在schedule arraylist的第一个位置添加此活动,而schedule arraylist的第0个位置将保留为空。 现在,您在Listview适配器中传递此arraylist,其中null值位于第0位,这就是它抛出IndexOutOfBoundsException异常的方式。 要解决此问题,您可以维护一个ArrayList<String>。在CloudEvents活动中进行以下更改。

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活动中进行以下更改。

公共类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;
            }
        });

    }
}