添加前一个元素在 ArrayList 中被替换 [英] on add previous element getting replaced in ArrayList

查看:51
本文介绍了添加前一个元素在 ArrayList 中被替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行了调试.在 entryLogs.add(dl); 之后我可以清楚地看到在 entryLogs 的值中.第一个数据被替换,第二个数据被插入到 ArrayList 中.

did debugging. I can clearly see after entryLogs.add(dl); in the value of entryLogs. the first data is replaced and a second has been inserted to the ArrayList.

发生的事情是每次我输入新值时,它都会将它添加到 ArrayList 中,但将第一个条目替换为与第二个条目相同的条目.例如:我添加 A 并点击它添加 A.再次,添加 B 并点击它添加 B.但在 Arraylist 中的值是 [17/4/2014:20:29 B, 17/4/2014:20:29 B]

what is happening is every time i enter new value it adds it in the ArrayList but replaces the the first entry to be same as the second entry. for example: I add A and onclick it adds A. again, add B and onclick it add B. but in the Arraylist the value is [17/4/2014:20:29 B, 17/4/2014:20:29 B]

请建议需要做什么.完整代码可以在这里找到:https://github.com/tirthoguha/DroidProject/blob/myDiary/src/com/example/s0217980_diary/Monday_fragment.java

Please suggest what needs to be done. Entire code can be found here: https://github.com/tirthoguha/DroidProject/blob/myDiary/src/com/example/s0217980_diary/Monday_fragment.java

entryLogs = new ArrayList<DiaryLogs>();

            timeText = (EditText) getView().findViewById(R.id.dateTimeEText);

            entryText = (EditText) getView().findViewById(R.id.diaryEntryEText);

            Button saveBtn = (Button) getView()
                    .findViewById(R.id.saveDiaryEntryBtn);
            saveBtn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    timeEntry = timeText.getText().toString();

                    entryEntered = entryText.getText().toString();

                    dl = new DiaryLogs(1, timeEntry, entryEntered);

                    entryLogs.add(dl);

推荐答案

DiaryLogs.java 类中,你将字符串 timeEntry 和 entryEntered 声明为 static

In the class DiaryLogs.java you declare the strings timeEntry and entryEntered as static

static String timeEntry;
static String entryEntered;

去掉静态修饰符,你会没事的.对于该类的任何 实例,静态对象将具有相同的值(即使没有它的实例也可以访问),因此如果您在另一个对象中设置该值,则每个实例都将使用该值.

Remove the static modifier and you'll be fine. Static objects will have the same value for any instance of that class (and are accessible even without having an instance of it), so if you set the value in another object, every instance will use that value.

这篇关于添加前一个元素在 ArrayList 中被替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆