Nguyễn Trung Hiếu Nguyễn Trung Hiếu - 6 months ago 9
Java Question

How to convert multiple String Array to ArrayList<FileItems> in Java

I have mListResult have size = 10;

I have a Contructor FileItems

This is class FileItems

public class FileItems {

private String mTitle;
private String mFileId;

public FileItems(String mTitle, String mFileId) {
this.mTitle = mTitle;
this.mFileId = mFileId;
}

public FileItems() {
}

public String getTitle() {
return mTitle;
}

public void setTitle(String mTitle) {
this.mTitle = mTitle;
}

public String getFileId() {
return mFileId;
}

public void setFileId(String mFileId) {
this.mFileId = mFileId;
}


}

this is Activity

List<FileItems> mListFileItems=new ArrayList<FileItems>();
String mFileArray[] = new String[mResultList.size()];
String mDownloadUrl[] = new String[mResultList.size()];
FileItems fileItems = new FileItems();
int i = 0;
for (File tmp : mResultList) {
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
mDownloadUrl[i] = tmp.getId();
i++;
fileItems.setTitle(tmp.getTitle());
fileItems.setFileId(tmp.getId());
mListFileItems.add(fileItems);
}


I use Debug Tesst

DebugTool.logD("LISTTTTTT " + mFileArray.length());
DebugTool.logD("LISTTTTTT " + mDownloadUrl.length());
DebugTool.logD("LISTTTTTT " + mListFileItems.size());
DebugTool.logD("LISTTTTTT " + mListFileItems.get(1).getTitle());
DebugTool.logD("LISTTTTTT " + mListFileItems.get(0).getTitle());
DebugTool.logD("LISTTTTTT " + mListFileItems.get(2).getTitle());


This is result

05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT 10
05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT 10
05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT 10
05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT Test1.pptx
05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT Test1.pptx
05-13 10:31:17.063 3561-3561/test.com D/TAG: LISTTTTTT Test1.pptx


I use code above. It return only a element. Please Help me!!!

Answer

You are getting same result because the object you are setting values in loop is always same(means not new object)

    FileItems fileItems = null;
    int i = 0;
    for (File tmp : mResultList) {

        mFileArray[i] = tmp.getTitle();
        mDownloadUrl[i] = tmp.getId();
        i++;

        fileItems=new FileItems();//create new object for every new item

        fileItems.setTitle(tmp.getTitle());
        fileItems.setFileId(tmp.getId());
        mListFileItems.add(fileItems);
    }

happyCoding;