cj1098
cj1098

Reputation: 1610

splitting a string into an array of strings

So I currently store a bunch of string titles together into a file on the user's phone and then read it later (when they relaunch the app). I'm trying to read back the string and split it on the delimiter I set for it but for some reason it splits it and then doubles the string...

So for example if I stored these strings

Ricky(har)Bobby(har)is(har)cool(har)

(har) is the delimiter I use to store them. (for example)

For some reason, when I use the split function on "har"

It gives me an array of strings, but doubles how many I stored... So the array of strings would have two Ricky's two Bobby's two is's and two cool's. I'm at a loss for what's going on to be honest. Been staring at this for hours... anyone have any idea?

line = BR.readLine();
            String[] each = line.split("<TAG>");
            for (int i = 0; i < each.length; i++) {
                listOfCourses.add((each[i]));
                //Toast.makeText(context, each[i], Toast.LENGTH_SHORT).show();
            }

Here's the function that stores the data to the user's phone

//adds data into the classes file on user's phone
    public void addClassesIntoFile(Context context, ArrayList<String> classList) {
        try {
            FileOutputStream fos = context.openFileOutput(CLASSLIST_FILENAME,
                    Context.MODE_PRIVATE | Context.MODE_APPEND);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            for (int i = 0; i < classList.size(); i++) {
                osw.write(classList.get(i) + "<TAG>");
            }
            osw.flush();
            osw.close();
        } catch (FileNotFoundException e) {
            // catch errors opening file
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Upvotes: 1

Views: 734

Answers (2)

Ifrit
Ifrit

Reputation: 6821

I don't believe your split function is the problem and instead think it's with some other part of your code.

  1. Is the String before you conduct the split correct? Or do you see duplications in it?
  2. I imagine the problem is with your addClassIntoFile method. Since you are appending into the File, be sure you aren't re-adding values that are already there. Unless you delete that file at some point, it'll persist the next time the app is launched.
  3. Finally make sure you aren't calling addClassIntoFile more then you meant too. IE, accidentally invoking it more then once on a given object.

If I'm incorrect on all this, then please post an example of what the String looks like before a split so we can be sure the given regex is correct.

Upvotes: 2

William Kinaan
William Kinaan

Reputation: 28799

Replace:

String[] each = line.split("<TAG>")` 

with this:

String[] each= line.split("[(har)]");

if the wrong still, tell me please

Upvotes: 0

Related Questions