Monday, September 17, 2018

Show List of Countries using API

package net.samaysoftware.listviewdemo;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import utility.HttpManager;
import utility.RequestPackage;

public class CountryList extends AppCompatActivity {
    ListView listView;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_country_list);
        listView = (ListView) findViewById(R.id.lvDynamicCountries);

        new MyTask().execute();

    }
    class MyTask extends AsyncTask<String, String, String>{

        ProgressDialog pd = null;
        @Override        protected String doInBackground(String... strings) {
            RequestPackage rp = new RequestPackage();
            rp.setMethod("GET");
            rp.setUri("https://restcountries.eu/rest/v2/all");
            String ans = HttpManager.getData(rp);
            return ans;
        }

        @Override        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(CountryList.this);
            pd.setIndeterminate(true);
            pd.setMessage("Loading....");
            pd.setCancelable(false);
            pd.setTitle("Please Wait");
            pd.show();
        }

        @Override        protected void onPostExecute(String ans) {
            super.onPostExecute(ans);

            ArrayList<String> arrlist = new ArrayList<>();

            try {
                JSONArray rootarr = new JSONArray(ans);

                for(int i = 0; i <rootarr.length(); i++){
                    JSONObject obj = rootarr.getJSONObject(i);
                    String countryname = obj.getString("name");
                    arrlist.add(countryname);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            ArrayAdapter<String> aa = new ArrayAdapter<String>(CountryList.this, android.R.layout.simple_list_item_1, android.R.id.text1, arrlist);
            listView.setAdapter(aa);



            pd.dismiss();
        }
    }
}

No comments:

Post a Comment

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view