0

I am currently converting an ArrayList to a String to send it to a DB so I can retrieve it on the other end and convert it back to an ArrayList later.

My thought process is to convert it to a string currently by doing the following

for(Integer o: questions) questionString += o + ",";

questions is the ArrayList and looks like this: [4, 4]

When I look at my database it looks like this null4,4,

How would I go about removing null at the start and the last , so it looks like 4,4 on the database?

On the other end I can then get it by using the following:

ArrayList myList = new ArrayList<String>(Arrays.asList(arrayQuestions.split(",")));

( I am using SQLite which is a requirement for my college project )

IAmAndy
  • 121
  • 2
  • 12
  • 3
    Hint: do you know how to check whether something is null? (`if (o == null)` in this case, or `if (o != null)` to test whether it's not null.) I'd also strongly recommend *always* using braces for loops, as an aside. – Jon Skeet Apr 08 '21 at 14:52
  • Well, why not having a table that will keep each element of your list in a single row? Give more details on what you want to do so we can guide you. Show the project question. – Tarik Apr 08 '21 at 14:54
  • @Tarik Sorry, it's a quiz project. We have to give the user two attempts at quiz so to get the questions from the previous quiz im storing the question_ID's in an ArrayList to be stored in the DB but I found out SQLite doesn't let you use setArray(). My thought process is to store them as a String so on the other end I can parse them back into an ArrayList – IAmAndy Apr 08 '21 at 14:58
  • This looks like it. https://stackoverflow.com/questions/36705880/concatenate-string-values-with-delimiter-handling-null-and-empty-strings – Amit Jain Apr 08 '21 at 15:01
  • Store them one by one in a table with a single column. – Tarik Apr 08 '21 at 15:07

3 Answers3

1

Just check if "o" is null.

if (o == null)
cwittah
  • 349
  • 1
  • 3
  • 17
1

You should initialize questionString to "" before the loop;

String questionString = "";
WilsonPena
  • 1,451
  • 2
  • 18
  • 37
1

You're using SQL (SQLite specifically). That means you should avoid storing an ArrayList as a String.

Instead, you want to look into database normalization and the relational model. Rather than having a single row with a list in it, you should use multiple rows for each list element.

A248
  • 690
  • 7
  • 17