Add Permission in AndroidMainFest.xml File
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.bhaumik.simplejsonparshing.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </RelativeLayout>
MainActivity.java
package com.example.bhaumik.simplejsonparshing; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String url = "http://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a1"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { parseData(response.body().string()); } }); } private void parseData(String string) { try { JSONObject object = new JSONObject(string); JSONObject coord = object.getJSONObject("coord"); double longitude = coord.getDouble("lon"); double latitude = coord.getDouble("lat"); Log.d("LogX","Values :-> " + longitude + " " + latitude); JSONArray jsonArray =object.getJSONArray("weather"); for(int i=0; i<jsonArray.length(); i++) { JSONObject objects = jsonArray.getJSONObject(i); int id = objects.getInt("id"); String main = objects.getString("main"); String desc = objects.getString("description"); String icon = objects.getString("icon"); Log.d("LogX","Values :-> " + id + " " + main + " " + desc + " " + icon); } } catch (JSONException e) { e.printStackTrace(); } } }
0 comments:
Post a Comment