【问题标题】:How to work with big HTML String?如何使用大 HTML 字符串?
【发布时间】:2017-03-08 03:58:30
【问题描述】:

我想从网页中获取 HTML,从代码中删除一些标签并使用 TextView 显示它...但是这些 HTML 太大而无法暂时存储到字符串中...

当我尝试这种方式时:

String html = "myBigHTML";
myTextView.setText(fromHtml(html));

编译器说error: constant string too long

如果我将 html 放入 .txt 并尝试这种方式:

InputStream is = getAssets().open("html.txt");

tvTeste.setText(fromHtml(convertStreamToString(is)));

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

它可以工作,但应用程序变得太慢了,几乎死机......而且,如果我将它存储在 .txt 中,我无法使用标签......

.:: 编辑 ::.

我的onCreate()方法被问到...

private TextView tvTeste;
private InputStream is;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_frequencia);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    tvTeste = (TextView)findViewById(R.id.tvTeste);

    try {
        is = getAssets().open("html.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String strLine;

    List<String> stringList = new ArrayList<>();
    try {
        while ((strLine = br.readLine()) != null)   {
            stringList.add(strLine);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    tvTeste.setText(fromHtml(TextUtils.join("",stringList)));
}

【问题讨论】:

  • 除了接受的答案之外,您还可以找到替代解决方案here

标签: java android html


【解决方案1】:

让我们试试这个:HTML 文本的每一行都是一个字符串。每个字符串都在一个字符串列表中。
所以,一些伪代码

List<String> stringList = new ArrayList<>();

while (htmlHandler.next()) {
   stringList.add(fromHtml(htmlHandler.readLine()));
}

myTextView.setText(joinStringArray(stringList));

joinStringArray 使用 StringBuilder 生成单个大字符串对象。
基本上你不应该阅读整个网页,而应该按顺序阅读。

【讨论】:

  • 我已经使用 TextUtils.join("",list) 完成了它...它可以工作,但应用程序也变得非常缓慢
  • 嗯,但是如何加载列表?
  • 它以onCreate() 方法加载...也许我可以在上面放一些“加载对话框”?
  • 当然,加载消息或图标完全没问题。您可以发布 onCreate() 代码吗?如果可能的话,我想看看你是怎么做到的。
  • 好的,我以为你还在从文本文件中读取。你如何生成文本文件?而不是输出到. txt,输出到列表。我在健身房,所以我正在使用电话。等我回家给你举个例子。
【解决方案2】:

另一个要标记的点。您应该避免任何阻碍活动的耗时过程。尝试使用相同的方法,例如 AsyncTask。 请查看https://developer.android.com/reference/android/os/AsyncTask.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 2020-09-08
    • 2015-11-28
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2014-05-15
    相关资源
    最近更新 更多