This should be really simple and i've been getting close to figuring it out but am starting to loose my sanity. Simply trying to pull data from an api
How do i pull JSON data from an object (inside another object)?
This is the first day i've ever heard of JSON so ill be the first to admit i have very little knowledge about this. Thanks for your time!
This post: JSON parsing in android: No value for x error was super helpful and got me to where i am now which is trying to open "list" then get into "0" so i can gather weather data.
Been using jsonviewer.stack to try to understand this stuff
My code:
public class MainActivity extends AppCompatActivity {
TextView citySpot;
TextView cityTemp;
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// this works flawlessly and gathers the city name
JSONObject container = new JSONObject(result);
JSONObject cityTest = container.getJSONObject("city");
citySpot.setText(cityTest.getString("name"));
// this is my failed attempt to get inside of the "list" folder
JSONObject listList = new JSONObject(result);
JSONObject listTest = listList.getJSONObject("list");
JSONObject listTestOne = listTest.getJSONObject("0");
JSONObject listTestTwo = listTestOne.getJSONObject("main");
cityTemp.setText(listTestTwo.getString("temp"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
citySpot = (TextView) findViewById(R.id.cityName);
cityTemp = (TextView) findViewById(R.id.textView3);
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/forecast/city?id=4161254&APPID=e661f5bfc93d47b8ed2689f89678a2c9");
}
}