Giter Club home page Giter Club logo

worldcountrydata's Introduction

World Country Data, flags, currency and more - an open source android library for getting country flags and other country attributes

CodeFactor Android CI with Gradle


An Android library that contains 'all' the flags of the countries of the world This is to be used for android projects where the developer is interested in getting the flag of a particular country for any reason.

  • A flag is obtained as a drawable resource (int).
  • A flag can be set to an ImageView using XML
  • There is possibility to get all the countries and their flags by invoking just two methods.

System requirement

  • Android minSdkVersion = 15
  • Android targetSdkVersion = 33

Known Limitations

This library has been known to crash apps if you set shrinkResources true in your build settings. See step 2.3 below on how to deal with this!

This library will also result to a larger APK size of your app! It however gives you the advantage that it does not require any network calls


Usage

  1. Add JitPack in your repository build file build.gradle (Project appname)
allprojects {
    repositories {
        //...
        maven { url 'https://jitpack.io' }
    }
}

2.1 Add the dependency in your build.gradle (Module: app)

dependencies {
    //...
    implementation 'com.github.blongho:worldCountryData:$version'
}

Replace $version with vXXX for the most stable version you want to use see releases

Proguard rules

2.2 Add this in your proguard-rules.pro

-keep

class com

.blongho.** {
    *;
}
-keep

interface com

.blongho.**
#
If you
keep the line number information , uncomment this to
# hide the original source file name.
# -renamesourcefileattribute SourceFile
-keeppackagenames com.blongho.country_data
-keepclassmembers

class com

.blongho.country_data.* {
    public *;
}
-keep

class com

.blongho.country_data.R$ * {
    *;
}

2.3 In your build.gradle (Module: app)

android {
    ...

    buildTypes {
        release {
            minifyEnabled true
            //shrinkResources false // if you set this to true, the application will crash
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

    }

    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }

    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
    ...
}

  1. Build your project (and make sure gradle has successfully synced) Buid >> Clean Project, Build >> Rebuild Project

  2. Load all the flags of the world by calling. Do this once in the application context.

World.init(getApplicationContext()); // Initializes the libray and loads all data

This inititializes the data. All countries are read, and their flags loaded

  1. Get the flag of a country(dynamically)
  • You can get the flag of a country by using the two iso alpha2 or alpha3 or the country name or the numeric code.
// Demonstrating with Sweden
//The attribute is case-insensitive "se == SE == sE == Se"

// use alpha2
final int flag=World.getFlagOf("se"); // use "se" or "sE" or "SE" or "Se"

// use alpha3
final int flag=World.getFlagOf("swe");

// Use country name
final int flag=World.getFlagOf("sweden");

// use country name
final int flag=World.getFlagOf(752);

// Set the image of an imageView
final ImageView swedishFlag=(ImageView)findViewById(R.id.flagImageView);
        swedishFlag.setImageResource(flag);

/*
The value of flag is either
- the flag of the country if it is loaded in the library
OR
- a demo flag of the globe (This provides a fall-back and help your app not crash due to nullPointerException)
*/
  • You can hard-code the country flag if you know the alpha2 code of the country. Eg. to set the flag of Sweden, you could do
<ImageView android:id="@+id/flagImageId" android:layout_width="@dimens/imageWidth"
        android:layout_height="@dimens/imageHeight"
        android:src="@drawable/se" /> <!-- Sets this image to the Swedish flag -->
  • In java code, you could statically do same as
// Set the image of an imageView
final ImageView swedishFlag=(ImageView)findViewById(R.id.flagImageView);
        swedishFlag.setImageResource(R.drawable.se);
  1. Get a Country with attributes like "id":4,"name":"Afghanistan","alpha2":"af","alpha3":"afg", flag:imageResource"
final Country afghanistan=World.getCountryFrom("af|afg|afghanistan|4|kabul");
// Log.d(TAG, afghanistan.toString()); 
  1. Get a list of all the countries with their identifiers
final List<Country> countries=World.getAllCountries();
// This list cannot be modified but you can get its contents
  1. Get list of countries from a continent
final List<Country> africanCounties=World.getCountriesFrom(Continent.AFRICA);
///final List<Country> filteredCountries = World.getCountriesFrom(Continent.[AFRICA|ASIA|EUROPE|OCEANA|SOUTH_AMERICA|NORTH_AMERICA])
// Continent is an enum that has all the continents of the world

NEW

  1. Get the list of languages spoken in a given country
final List<String> languages=World.getLanguagesFrom("af|afg|afghanistan|4|kabul");
//or 
final Country afghanistan=World.getCountryFrom("af|afg|afghanistan|4|kabul");
final List<String> languages=afghanistan.getLanguages();
// Returns comma separated list of country languages e.g [Swedish (sv-SE), Northern Sami (se), Southern Sami (sma), Finnish (fi-SE)]

Link to javadoc --> javadoc link

All the steps above are demonstrated in this project --> world country flag demo


| Demonstrating dynamic retrieval of country flags | |:--:| | Live retrieval of Country data |


Get this sample app in the playstore Country Data Demo at playstore

Data sources for the project

All country flags

Most of the flags came from flagpedia.net. This site does not contain all the countries in the world so some where downloaded from wikipedia after quering the country name

Countries and their iso alpha values

All country names were download from Geonames using a Python project written by Bernard Longho aka @blongho. Check it out Countries data by blongho

Getting different dimensions of the flags

Some guys from Egypt made some awesome App icon generator which generates android drawables as well as iOS images(if you want) in different dimensions. It is super fast and can do batch processing of images.


Contribution guidelines

Please feel free to add more flags or modify any thing that would make this library more useful. The various ways of contribution are specified in CONTRIBUTING.md


Sponsors

JetBrains

Contact

Feel free to contact me to discuss anything related to development in particular and life in general.

worldcountrydata's People

Contributors

akrami1997 avatar blongho avatar eagskunst avatar fatonhoti avatar md0092651 avatar sal0max avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

worldcountrydata's Issues

test

still getting issues in signup apk file

Problem with implementation

Describe the bug
Cannot implement the library.
implementation 'com.github.blongho:worldCountryData:v1.5'
implementation 'com.github.blongho:worldCountryData:1.5'

Error

Failed to resolve: com.github.blongho:worldCountryData:1.5
Show in Project Structure dialog
Affected Modules: app

Android Studio 4.0

Flag cut off in ImageView.

Hi. I use the svg to this ImageView tag.

<ImageView
			android:id="@+id/flag"
			android:layout_width="30dp"
			android:layout_height="20dp"
			android:layout_marginEnd="5dp"
			android:contentDescription="@string/empty"
			android:layout_gravity="center_vertical"
			android:scaleType="centerCrop"/>

For example, use american flag. The result is not all the flag is fit inside the ImageView.

tried to use adjustViewBounds, still no. tried all scale types, nothing worked such that the flag did not fit in the image view.

please seee result.
flag

e.g. US and PH flag are cut off.

thoughts?

minsdk should be 21

hi correct me if im wrong

shouldn't min sdk be 21 instead of the current 15? there would be no point to have those vector images since it will still generate pngs.

EU flag not accessible

The newly added eu flag is not accessible via World.getFlagOf("EU"). Only the globe is retrieved.

Signed app Crash

Debug app working fine but singed apk getting crash due to this World.init(applicationContext).
Any suggestions?

Wrong plural for Euro

Describe the bug
Euro can be a tough one. There's an entire Wikipedia article about it:
https://en.wikipedia.org/wiki/Language_and_the_euro

Nevertheless, in this case (English) and when wanting to use the correct (not the used) plural form of the European currency, it clearly is Euro.

"In the English-language version of European Union legislation, the unit euro, without an s, is used for both singular and plural."
https://en.wikipedia.org/wiki/Language_and_the_euro#English

To Reproduce
Look at https://github.com/blongho/worldCountryData/blob/master/country_data/src/main/res/raw/com_blongho_country_data_currencies.json
e.g.:

  {
    "country": "FI",
    "name": "Euros",
    "code": "EUR",
    "symbol": ""
  },

Expected behavior
Should be "name": "Euro",

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference

Describe the bug
I am getting an error that is NullPointerException. It is in WorldData.java file where in this library.

To Reproduce

  1. just write World.init(applicationContext) in App file or an Activity file.

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
Screen Shot 2022-11-30 at 12 24 49

Screen Shot 2022-11-30 at 12 24 59

Additional context
I hadn't been getting this error before but now I am getting. It is weird I also use this library in my another app and this library is working as well there.

Build fails on pipeline

The build on pipeline fails because of the below reason

Failed to transform worldCountryData-1.5.2.jar (com.github.blongho:worldCountryData:1.5.2) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
> Could not find worldCountryData-1.5.2.jar (com.github.blongho:worldCountryData:1.5.2).
Searched in the following locations:
https://jitpack.io/com/github/blongho/worldCountryData/1.5.2/worldCountryData-1.5.2.jar

sing-up apk not working with your lib - When we set minifyEnabled true

Thanks for you lib its grt work in debug mode app

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

implementation 'com.google.android.material:material:1.1.0'
implementation 'com.github.blongho:worldCountryData:v1.5'

        World.init(this);

not getting flag = World.getFlagOf("CountryName");

please help on that , I want to set minifyEnabled true when I create sign-up apk file

Not able to retrieve Kosovo "XKX".

Describe the bug
Even though values are correct we are not able to retrieve Country or Flag with the code "XKX" or "XK" (Kosovo). I can see that the Country is in the .json and there is a vector of the flag, but for some reason when we try to fetch this it fallbacks to the earthglobe icon and the name "World". Other values/countries that were tested the same way work fine.

To Reproduce
Steps to reproduce the behavior:

  1. Initialize World
  2. Call World.getCountryFrom("XKX") and World.getFlagOf("XKX")
  3. Check that we indeed get the flag of Kosovo and not the Earthglobe icon aswell as the country name and not "World".

Expected behavior
Expected behaviour is that we manage to get the Country and its name/flag etc.

Smartphone (please complete the following information):

  • Samsung S10
  • Android 11

Fallback drawable

Hi, would be to nice to have an option to have a custom fallback drawable or we can set a default flag as fallback

worldCountryData-1.4.aar is missing from the Jitpack repository

Describe the bug
The file worldCountryData-1.4.aar is missing from Jitpack.

To Reproduce
Try to build a project with a dependency on version 1.4

implementation 'com.github.blongho:worldCountryData:1.4'

It will result in the error message Failed to resolve: worldCountryData-1.4.

Expected behavior
Sucessful resolution of dependencies when using version 1.4.

Additional context

$ curl https://jitpack.io/com/github/blongho/worldCountryData/1.4/
build.log
worldCountryData-1.4-sources.jar
worldCountryData-1.4-sources.jar.md5
worldCountryData-1.4-sources.jar.sha1
worldCountryData-1.4.pom
worldCountryData-1.4.pom.md5
worldCountryData-1.4.pom.sha1

As you can see in the file listing above worldCountryData-1.4.aar is missing from the repository despite being mentioned in the build.log.

[JITPACK] Version 1.3 unavailable

Hello there,

I wanted to upgrade to 1.3 but I noticed that it isn't available on Jitpack.
The build logs shows an error trying to run the publish.gradle script.

I couldn't find this file in the repository, should it be there or is that a Jitpack generated file ?

Some countries doesn`t have flags

Hello!

I am using function:
World.getFlagOf(item.CodeAlpha2)

Works fine, but some countries and regions does not have flags:

  • Saint Maarten
  • Turkmenistan
  • Gibraltar
  • French Polynesia
  • New Caledonia
  • Wallis and Futuna
  • Indonesia
  • Guernsey
  • Ghana
  • Hong Kong
  • Macao

Thank you.

Inconsistent currency names

Currency names are somewhat inconsistent.

Like Dollar. The majority is named Dollar:

  • Bahamian Dollar
  • Barbadian Dollar
  • ...
  • Trinidad and Tobago Dollar
  • US Dollar
  • Zimbabwe Dollar

Where those are either dollar or Dollars:

  • Antarctican dollar
  • Hong Kong dollar
  • Australian Dollars
  • New Zealand Dollars

To Reproduce
Check out https://github.com/blongho/worldCountryData/blob/master/country_data/src/main/res/raw/com_blongho_country_data_currencies.json

Expected behavior
All currencies should follow the same naming convention.
In this case, change all to dollar as this seems to be the right way:

Loads of flags missing with SVG update

I love that the library now supports svg. Sadly (and this is how I noticed) some flags are not available as svg. Most crucial missing one might again be the EU flag.

From quick test, these flags are missing in the svg (1.5.1 Version):

-EU!
-Antarctica
-French Polynesia
-Ghana
-Gibraltar
-Guernsey
-HongKong
-Indonesia
-Macau
-New Caledonia
-St. Martin
-Turkmenistan
-Wallis & Futuna

I hope at least the EU flag can be added:) Also in case you need a reference:
https://github.com/madebybowtie/FlagKit/tree/master/Assets/SVG

Check this git. It is a cool flag library for IOS which has the svg assets:)

Failed to resolve issue

I am getting the ERROR: Failed to resolve

Whether I am using io.github.blongho:worldCountryData:1.3 or

implementation 'com.github.blongho:worldCountryData:1.2.0'

Added the maven repo to the gradle dependency, cleaned, rebuild project, invalidate cache & restart, but just cant seem to get this working?!
Can't seem to figure out how to solve this. Any help?

Amazing work!!! Could you give some tips to create flag xml?

Amazing work! I really appreciate it!

I used Vector Asset in Android Studio to generate xml files showing different countries' flags via SVGs.

But there is a problem. I try to use EU FLAG SVG to obtain EU FLAG XML and I will lost some five-pointed stars in vector drawable preview. The same goes for the US FLAG SVG. What they have in common is that they have lots of five-pointed stars.

So, could you share some tips about creating XML files via SVG files applying to Android applications?
THANKS A LOT!!!

EU flag

Is there a chance of adding the European Union flag? I know that it is not a country, but the EU flag is useful for currency popurses

Problem with implementation

Hello, I wanted to know if anyone has ever had this problem.

Could not find com.github.blongho:worldCountryData:v1.5.3.
Required by:
project :app
Search in build.gradle files

I saw someone with this problem, and it was because he didn't write JitPack in repositories. (Problem with implementation)

So, I think I have the same problem, since other libraries don't work for me either, do you know any solution?

Thanks and regards.

Argentina flag is too small?

Describe the bug
Argentina flag is too small? Compared to other flags it always appears smaller.

To Reproduce
Just use the argentina flag and compare it with others

Currencies not being loaded because of validation

There's a logic that checks whether the given currency is valid

private boolean isValid(final Currency currency) {
    return currency != null && currency.getSymbol() != null && currency.getName() != null
        && currency.getCode() != null;
  }

Yet, there are currencies which have no symbol defined, like Hong Kong Dollar

{
    "country": "HK",
    "name": "Hong Kong dollar",
    "code": "HKD"
 }

This effectively excludes such currencies from being added to currencyMap field.

private void loadCurrencies(Context context) {
    final String currencyArray = AssetsReader.readFromAssets(context,
        R.raw.com_blongho_country_data_currencies);
    Gson gson = new Gson();
    final Currency[] currencies = gson.fromJson(currencyArray, Currency[].class);
    for (final Currency currency : currencies) {
      if (isValid(currency)) {
        currencyMap.put(currency.getCountry().toLowerCase(), currency);
      }
    }
  }

Would it make sense to mark the symbol field as @Nullable and remove isValid() check?

Invalid data

The JSON data for some countries invalid

for example, the country code of Ethiopia is 251 but in the data, it is 231

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.