Estou tentando adicionar dados no DB dentro de uma AsyncTask. Nela eu pego a InputStream vindo de um httpURLConnection, interpreto o JSON e salvo no SQLite local. Porém eu nem sei se essa é a melhor "pratica" a se fazer...
URL url = new URL(URL);
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
httpURLConnection.setRequestProperty("Accept", "*/*");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream())) {
wr.write(data);
wr.flush();
} catch (Exception e) {
Log(Tags.WSERROR, e.getMessage());
}
int status = httpURLConnection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getErrorStream();
Log(Tags.WSERROR, "Code: " + httpURLConnection.getResponseCode() + "\t\tMsg: " + httpURLConnection.getErrorStream());
} else {
inputStream = httpURLConnection.getInputStream();
}
mapItens(inputStream);
if (inputStream == null) {
return null;
}
O metodo MapItens cuida da interpretação dos dados e de salvar no DB local, esta assim:
Map<String, String> mapPedidos(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String linha;
StringBuffer buffer = new StringBuffer();
while ((linha = reader.readLine()) != null) {
buffer.append(linha + "\n");
}
Log(Tags.WSINFO, "Itens - " + buffer.toString());
if (buffer.length() == 0) {
return null;
}
List<Itens> registers = new ArrayList<>();
try {
JSONObject req = new JSONObject(buffer.toString());
Log(Tags.WSINFO, "Itens são: " + req.toString());
JSONArray locs = req.getJSONArray("DADOS");
Log(Tags.WSINFO, "locs SIZE: " + locs.length());
for (int i = 0; i < locs.length(); ++i) {
JSONObject rec = locs.getJSONObject(i);
Itens it = new Pedido();
it.nome = rec.getString("IT_NOME");
it.desc = rec.getString("IT_DESC");
registers.add(it);
}
} catch (JSONException e) {
Log(Tags.WSERROR, e.getMessage());
} finally {
for (Itens i : registers) {
Log(Tags.WSINFO, "Item : " + i.nome + " sendo criado!");
boolean r = i.create();
if (r)
Log(Tags.WSINFO, i.nome + " created!");
else
Log(Tags.WSINFO, i.nome + " error");
}
Log(Tags.WSINFO, "Count in DB: " + getInstance().getCount());
getInstance().CloseDB();
}
ArrayList<Itens> p = Itens.getAll();
Log(Tags.WSINFO, "Select nos itens iniciando");
if (p != null)
for (Itens pe : p) {
Log(Tags.WSINFO, "Itens " + pe.nome);
}
Log(Tags.WSINFO, "Select nos itens finalizando");
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (reader != null) {
reader.close();
}
return getData;
}
Eu fiz essa mesma lógica em outra classe para obter outras informações de outro webservice. Ela funciona perfeitamente.
Outro ponto é que não há exception na inserção dos dodos no DB, o resultado sai como true, o getCount() da tabela me retorna numero de resgistros positivos. Em todos os logs, as informações são mostradas corretamente. Quando eu faço o select, o ArrayList de itens vem nulo, aparentemente. O maior problema é que no restante de todo aplicativo, esses metodos de select do SQLite funcionam normalmente.