TextView shows STRING_TOO_LARGE

nikolouzos :

I have been trying to set a large string (25k+ characters) to a TextView for a while now but I've been getting a "STRING_TOO_LARGE" output.

I read somewhere that setting the string in run time might help solve that problem, so I modified my code but that didn't seem to help. I also tried setting the resource id directly in setText() but that didn't do anything as well.

I use the following method in my Activity to show the terms_dialog:

private void showTermsPopup() {
    Dialog termsDialog = new Dialog(this);
    termsDialog.setContentView(R.layout.terms_dialog);
    termsDialog.getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT);

    // Cancel the dialog if you touch the background
    termsDialog.setCanceledOnTouchOutside(true);

    // Add the terms string to the dialog
    TextView termsText = termsDialog.findViewById(R.id.termsTextView);
    String terms = getResources().getString(R.string.terms);
    termsText.setText(terms);

    // Show the dialog
    termsDialog.show();
}

This is the terms_dialog.xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:padding="8dp"
        android:scrollbarSize="0dp">

        <TextView
            android:id="@+id/termsTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</android.support.constraint.ConstraintLayout>

And this is the result I am getting (sensitive info whited out).

nikolouzos :

As pointed out by the link that @HB. gave me, you cannot have a string that is larger than 32,767 bytes (encoded in UTF-8) in your APK file.

So, what I did, was to create a txt file in the assets folder named terms.txt and I put the string in it. Then, using the following function I converted the file to a String:

private String getTermsString() {
    StringBuilder termsString = new StringBuilder();
    BufferedReader reader;
    try {
        reader = new BufferedReader(
                new InputStreamReader(getAssets().open("terms.txt")));

        String str;
        while ((str = reader.readLine()) != null) {
            termsString.append(str);
        }

        reader.close();
        return termsString.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

And I just assigned it to the TextView.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75115&siteId=1