Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Boa noite,
Sou novo em programação android e estou precisando de ajuda, preciso fazer um apk que conecte a um webservice via json. O apk que estou fazendo é de horoscopo, e encontrei o Json já pronto e online. Só que minha aplicação fecha ao atualizar as informações alguém poderia me informar o que ta de errado em meu código e me ajudar.
Segue o AsynTask para conectar com o serviço e o link do Json ja pronto é este: http://developers.agenciaideias.com.br/horoscopo.
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 1;
try {
final String FORECAST_BASE_URL =
"[http://developers.agenciaideias.com.br/horoscopo/json";](http://developers.agenciaideias.com.br/horoscopo/json)
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri uri = Uri.parse(FORECAST_BASE_URL)
.buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(uri.toString());
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// [http://openweathermap.org/API#forecast](http://openweathermap.org/API#forecast)
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
String[] returnStrs = new String[0];
try {
return TesteJson.getSignosFromJson(
forecastJsonStr, numDays);
} catch (JSONException e) {
e.printStackTrace();
}
return returnStrs;
}
}
E aqui tento pegar as informações do Json;
public class TesteJson {
private static String getReadableDateString(long time){
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
public static String[] getSignosFromJson(String forecastJsonStr, int numDays)
throws JSONException {
final String signos = "signos";
final String nome = "nome";
final String data = "data";
final String msg = "msg";
final String periodo = "periodo";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray SignosArray = forecastJson.getJSONArray(signos);
String[] resultSet = new String[numDays];
for(int i =0; i < SignosArray.length(); i++){
String dia;
String nomeSigno;
String mensagem;
String per;
JSONObject dayForecast = new JSONObject(String.valueOf(i));
long dataTime = dayForecast.getLong(data);
dia = getReadableDateString(dataTime);
JSONObject signoNome = dayForecast.getJSONObject(nome);
nomeSigno = SignosArray.getString(Integer.parseInt(nome));
JSONObject msgsigno = dayForecast.getJSONObject(msg);
mensagem = SignosArray.getString(Integer.parseInt(msg));
JSONObject periodoJson = dayForecast.getJSONObject(periodo);
per = SignosArray.getString(Integer.parseInt(periodo));
resultSet* = dia + "\n" + nomeSigno + "\n" + mensagem;*
}
return resultSet;
}
}
Carregando comentários...