我試圖從URL獲取一個字符串並通過Gson創建一個對象。我得到從這個URL:http://gotachles.co.il/data.php字符串,然後我必須將其轉換爲HTML之後,將其發送到Gson。問題是我的字符串可能太長(150萬字),並且在從HTML調用時應用會凍結。 (嘗試過,並且對較小的字符串工作正常)。巨大的字符串到HTML
TachlesStringGetter:
class TachlesStringGetter extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String myJSONString = null;
try {
myJSONString = new Scanner(new URL(
"http://gotachles.co.il/data.php").openStream(), "UTF-8")
.useDelimiter("\\A").next();
Log.i("TACHLESSTRINGGETTER", "got sucessfuly");
Log.i("TACHLESSTRINGGETTER", "" + myJSONString.length());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("TACHLESSTRINGGETTER", "RETURN");
return myJSONString;
}
}
的HTML的AsyncTask:
public class FromHTML extends AsyncTask<String, String, String> {
private Spanned spanned;
private String result;
@Override
protected String doInBackground(String... html) {
Log.i("FROMHTML", "STARTING");
spanned = Html.fromHtml(html[0]);
result = spanned.toString();
Log.i("FROMHTML", "Returning");
return result;
}
}
調用它這樣:
public void Jsonnn() {
// sending to anynctask
try {
myJSONString2 = new TachlesStringGetter().execute(myJSONString2)
.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
// // from html
if (myJSONString2 != null) {
Log.i("WEBVIEWCLASS", "DOING HTML STUFF");
try {
afterHTML = new FromHTML().execute(myJSONString2).get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
Log.i("FINALLY", "STARTING SEOND FINALLY");
try {
Gson gson = new Gson();
JsonObj obj = gson.fromJson(afterHTML, JsonObj.class);
Toast.makeText(getApplicationContext(), obj + "", 2000)
.show();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "oops jsno!",
1000).show();
}
}
}// first finnaly
}// second finnaly
}
很抱歉的低劣的代碼:d
您是否嘗試過使用StringBuilder而不是String? – domi 2015-02-09 01:39:23
如何做到這一點的任何例子? – Max 2015-02-12 18:06:31
查看我的回答,最大。 – domi 2015-02-12 19:18:13