So I have a piece of code where I am making a call to a server to get a large JSON file (about 2MB) and am parsing it using Jackson JSON Parser. The code runs fine, but the problem is I sometimes get an IOException "unexpected end of stream." So I'm guessing I'm losing my connection on my emulator during the streaming. Is there anyway that I can pause the stream and resume it? Or reconnect then resume the stream? Thanks.
private void createDatabase(String downloadUrl)
{
editor = sharedPref.edit();
String fieldName = "";
long id = 0;
String setNumber = "";
String cardName = "";
String type = "";
String attribute = "";
String level = "";
String category = "";
String attack = "";
String defense = "";
String description = "";
try
{
if (isOnline())
{
url = new URL(downloadUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
jsonfactory = new JsonFactory();
jsonParser = jsonfactory.createParser(connection.getInputStream());
while (jsonParser.nextToken() != JsonToken.END_ARRAY)
{
if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME)
{
fieldName = jsonParser.getCurrentName();
// if (fieldName.equals("id"))
// {
// jsonParser.nextToken();
// id = jsonParser.getIntValue();
// }
if (fieldName.equals("Set_Number"))
{
jsonParser.nextToken();
setNumber = jsonParser.getText();
}
else if (fieldName.equals("Card_Name"))
{
jsonParser.nextToken();
cardName = jsonParser.getText();
}
else if (fieldName.equals("Type"))
{
jsonParser.nextToken();
type = jsonParser.getText();
}
else if (fieldName.equals("Attribute"))
{
jsonParser.nextToken();
attribute = jsonParser.getText();
}
else if (fieldName.equals("Level"))
{
jsonParser.nextToken();
level = jsonParser.getText();
}
else if (fieldName.equals("Category"))
{
jsonParser.nextToken();
category = jsonParser.getText();
}
else if (fieldName.equals("Attack"))
{
jsonParser.nextToken();
attack = jsonParser.getText();
}
else if (fieldName.equals("Defense"))
{
jsonParser.nextToken();
defense = jsonParser.getText();
}
else if (fieldName.equals("Description"))
{
jsonParser.nextToken();
description = jsonParser.getText();
}
}
else if (jsonParser.getCurrentToken() == JsonToken.END_OBJECT)
{
id = db.insert(setNumber, cardName, type, attribute, level, category, attack, defense, description);
editor.putLong("lastId", id);
editor.commit();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (connection != null)
connection.disconnect();
if (jsonParser != null)
{
try
{
jsonParser.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Log.d("lastID", "" + sharedPref.getLong("lastId", -1));
if (sharedPref.getLong("lastId", -1) == 5980)
{
editor.putBoolean("databaseExists", true);
editor.commit();
}
}