Create a weather app that processes JSON requests. The app will need to adhere t
ID: 3929491 • Letter: C
Question
Create a weather app that processes JSON requests. The app will need to adhere to the following:
-- Allow the user to input a major city in the U.S.
-- Connect to the free Web site: OpenWeatherMap.org to retrieve weather data
-- Create a ListView that displays 10 days of weather data for that city.
Please upload a screenshots that show the weather app working in the emulator. The screenshots need to show that the app and all component parts work. As a minimum, upload the following for your weather app:
Two different screenshots, each showing the results of a different city entered by the user.
Explanation / Answer
Below is the code that uses the JSON requests that links to the weather website to get the data.
import java.io.BufferedReader;
import java.net.URL;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class FetchData {
private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/";
public static JSONObject getJSON(Context con, String city){
try {
URL link = new URL(String.format(OPEN_WEATHER_MAP_API, city));
HttpURLConnection con = (HttpURLConnection)link.openConnection();
con.addRequestProperty("x-api-key",con.getString(R.string.open_weather_maps_app_id));
BufferedReader buffer = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer str = new StringBuffer(1024);
String temp ="";
while((temp=buffer.readLine())!=null)
str.append(temp).append(" ");
reader.close();
JSONObject result = new JSONObject(str.toString());
if(result.getInt("cod") != 200){
return null;
}
return result;
}catch(Exception ex){
return null;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.