t_godd
t_godd

Reputation: 194

on add previous element getting replaced in 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.

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]

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

Upvotes: 0

Views: 2521

Answers (3)

Smokez
Smokez

Reputation: 382

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.

Upvotes: 2

Inder Sharma
Inder Sharma

Reputation: 15

Put these two lines

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

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

in @Override public void onClick(View v) { }

May this will help.

Upvotes: 0

Aksiom
Aksiom

Reputation: 1585

Maybe you should remove the line 64

entryLogs = new ArrayList<DiaryLogs>();

and initialize the ArrayList on the line 22

ArrayList<DiaryLogs> entryLogs;

Maybe it helps :)

Upvotes: 0

Related Questions