sandalone
sandalone

Reputation: 41759

String error "constant string too long"

There is a 100,000-character text that need to be displayed. If I put it into String object, I get an error "constant string too long". The same is with StringBuffer object.

StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Long text here........"); //<-- error

Is there a solution to this beside cutting the text into smaller texts?

Upvotes: 11

Views: 40452

Answers (4)

jascadev
jascadev

Reputation: 29

I had same problem and the solution was the very big string literal that was assigned to one constant, to split it to several smaller literals assigned to new constants and concatenate them.

Example:

Very big string that can not compile:

private static String myTooBigText = "...";

Split it to several constants and concatenate them that compiles:

private static String mySmallText_1 = "...";
private static String mySmallText_2 = "...";
...
private static String mySmallText_n = "...";

private static String myTooBigText = mySmallText_1 + mySmallText_2 + ... + mySmallText_n;

Upvotes: 1

ali asghar tofighian
ali asghar tofighian

Reputation: 349

Strings Longer than 64k are not allowed to be used directly in java, but you can use them indirectly.

  • Step 1) click on your string
  • Step 2) press Alt + Enter keys together
  • Step 3) Select Extract String resource
  • Step 4) Name the resource and hit enter key.

That is it. It will generate a string for you in strings.xml If you already have string in your strings.xml you can use this code to retrieve it:

String yourStr = getString(R.string.sampleBigString);

Upvotes: 6

Rahul Jain
Rahul Jain

Reputation: 276

Yes constant String has a limit in java.

So what you can do is copy your String in a text file and put in root of Assets folder and read from file by the following method.

public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
    fIn = context.getResources().getAssets()
            .open(fileName, Context.MODE_WORLD_READABLE);
    isr = new InputStreamReader(fIn);
    input = new BufferedReader(isr);
    String line = "";
    while ((line = input.readLine()) != null) {
        returnString.append(line);
    }
} catch (Exception e) {
    e.getMessage();
} finally {
    try {
        if (isr != null)
            isr.close();
        if (fIn != null)
            fIn.close();
        if (input != null)
            input.close();
    } catch (Exception e2) {
        e2.getMessage();
    }
}
return returnString.toString();
}

Upvotes: 2

Sai
Sai

Reputation: 3957

I think the length of constant strings in java is limited to 64K -- however, you could construct a string at run time that is bigger than 64K.

Upvotes: 11

Related Questions