Android – Ülkeler (JSON)

Merhaba arkadaşlar bu yazımızda api kullanıp JSON parse ederek bir program yazacağız.

Apimiz http://restcountries.eu/ adresindeki apimiz olacak. Api’yi incelemek gerekirse ;

[
    {
        "name": "Estonia",
        "capital": "Tallinn",
        "altSpellings": [
            "EE",
            "Eesti",
            "Republic of Estonia",
            "Eesti Vabariik"
        ],
        "relevance": "0",
        "region": "Europe",
        "subregion": "Northern Europe",
        "translations": {
            "de": "Estland",
            "es": "Estonia",
            "fr": "Estonie",
            "ja": "エストニア",
            "it": "Estonia"
        },
        "population": 1313271,
        "latlng": [
            59,
            26
        ],
        "demonym": "Estonian",
        "area": 45227,
        "gini": 36,
        "timezones": [
            "UTC+02:00"
        ],
        "borders": [
            "LVA",
            "RUS"
        ],
        "nativeName": "Eesti",
        "callingCodes": [
            "372"
        ],
        "topLevelDomain": [
            ".ee"
        ],
        "alpha2Code": "EE",
        "alpha3Code": "EST",
        "currencies": [
            "EUR"
        ],
        "languages": [
            "et"
        ]
    }
]

Bu apide dikkat etmemiz gerek array olarak başlamış. O yüzden apiyi parse ederken bunu göz önünde bulundurmalıyız.

Koda başlarken şunu belirtmek isterim düz bir program olmasın istedim en azından arama yapınca başka bir ekranda göstersin dedim. Bunun için öncelikle bir kaç şey yapmamız lazım;
Sıra sıra anlatmak gerekirse layout’a sağ tıklayıp “New”-“Activity”-“Blank Activity” seçip ismini veriyoruz. Daha sonra “AndroidManifest.xml” i düzenlememiz gerekir.
Burada yapmamız gereken activity-one taglarının altında birde “intent-filter” diye ekstra bir tag vardır. Bunu kopyalayıp activity-two ya ekliyoruz. category tagının sonundaki LAUNCHER yazısını silip DEFAULT yapıyoruz, android:name ise activity-second.xml de ki tools:context=’den sonraki kısmı kopyalayıp yapıştırıyoruz. Yani son olarak şöyle bir şekile bürünmesi gerekir;

Adsız.jpg

MainActivity kodlarına gelirsek ;

public void onButtonClickListener(){
        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                String gonder=editText.getText().toString();
                bundle.putString("sehir",gonder);

                Intent intent = new Intent("com.example.arslan.countryapp.secondActivity");
                intent.putExtras(bundle);

                startActivity(intent);
            }
        });
    }

Burada yaptığımız şey ile EditText’ten aldığımız veriyi second activity’e gönderiyoruz ve second-activity’i ekrana çağırıyoruz.

Second Activity’e gelirsek;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        txt_alman= (TextView) findViewById(R.id.textView14);
        txt_fra= (TextView) findViewById(R.id.textView15);
        txt_jap= (TextView) findViewById(R.id.textView16);
        txt_ita= (TextView) findViewById(R.id.textView17);

        txt_ulke = (TextView) findViewById(R.id.textView3);
        txt_dil = (TextView) findViewById(R.id.textView9);
        txt_baskent = (TextView) findViewById(R.id.textView5);
        txt_nufus = (TextView) findViewById(R.id.textView7);

        txt_org = (TextView) findViewById(R.id.textView19);
//ilk activity'den gönderdiklerimizi aldık.
        Bundle bundle = getIntent().getExtras();
        sehir = bundle.getString("sehir");
//JsonParse yapacağımız classı çalıştırdık.
        JsonParse jsonParse = new JsonParse();
        new JsonParse().execute();
    }

protected class JsonParse extends AsyncTask<Void, Void, Void>{
        String ulke;
        String capital;
        String alm,fr,ja,it;
        int pop;
        String dil,org;
        @Override
        protected Void doInBackground(Void... params) {
            String result = null;
            try {
                URL url = new URL("https://restcountries.eu/rest/v1/name/"+sehir);
                BufferedReader bufferedReader = null;
                StringBuilder sb = new StringBuilder();
                bufferedReader = new BufferedReader(
                    new InputStreamReader(url.openStream()));
                String line = null;
                while((line = bufferedReader.readLine())!= null){
                    sb.append(line).append("\n");
                }
                result = sb.toString();
                bufferedReader.close();
//bizim jsonumuz array olarak başladığı için array olarak aldık ilk verimizi
                JSONArray jsonArray = new JSONArray(result);
//Daha sonra tek bir index olduğu için ilk veriden name tagını aldık
                ulke = jsonArray.getJSONObject(0).getString("name");


                JSONObject jsonObject = jsonArray.getJSONObject(0);
                capital = jsonObject.getString("capital");

                JSONObject jsonArray2 = jsonObject.getJSONObject("translations");

                alm = jsonArray2.getString("de");
                fr = jsonArray2.getString("fr");
                ja = jsonArray2.getString("ja");
                it = jsonArray2.getString("it");


                pop = jsonObject.getInt("population");
                dil = jsonObject.getString("demonym");
                org = jsonObject.getString("nativeName");


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            txt_ulke.setText(ulke);
            txt_nufus.setText(String.valueOf(pop));
            txt_org.setText(org);
            txt_dil.setText(dil);
            txt_alman.setText(alm);
            txt_fra.setText(fr);
            txt_ita.setText(it);
            txt_jap.setText(ja);
            txt_baskent.setText(capital);
            super.onPostExecute(aVoid);
        }

Screenshot_2016-06-22-16-11-35.png          Screenshot_2016-06-22-16-11-40.png

Uygulama arayüzü ise bu şekilde olmuş olacak tabi siz isteğinize göre değiştirebilirsiniz 🙂

Uygulama dosyasını buradan indirebilirsiniz.

Kolay Gelsin 🙂

Yorum bırakın