Search code examples
androidxmlandroid-layoutandroid-xmlandroid-xml-attribute

How do I get a tag inside android xml string resource


I want to get the tag inside the xml array like country , countryCode , iso2 , iso3.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country_data">
        <item>
            <country>Afghanistan</country>
            <countryCode>93</countryCode>
            <iso2>AF</iso2>
            <iso3>AFG</iso3>
        </item>
        <item>
            <country>Albania</country>
            <countryCode>355</countryCode>
            <iso2>AL</iso2>
            <iso3>ALB</iso3>
        </item>
        <item>
            <country>Algeria</country>
            <countryCode>213</countryCode>
            <iso2>DZ</iso2>
            <iso3>DZA</iso3>
        </item>
        <item>
            <country>American Samoa</country>
            <countryCode>1-684</countryCode>
            <iso2>AS</iso2>
            <iso3>ASM</iso3>
        </item>
        <item>
            <country>Andorra</country>
            <countryCode>376</countryCode>
            <iso2>AD</iso2>
            <iso3>AND</iso3>
        </item>
        <item>
            <country>Angola</country>
            <countryCode>244</countryCode>
            <iso2>AO</iso2>
            <iso3>AGO</iso3>
        </item>
    </string-array>
</resources>

I want to get the country, countryCode, iso2 and iso3, all independently, into different ArrayLists(ArrayList country, countryCode, iso2, iso3).


Solution

  • This is how I did it.

    I used XmlPullParserFactory to get the tags from an xml file in the assets folder.

    ..

    Events of XmlPullParser

    The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface. These are:

    START_TAG :An XML start tag was read.

    TEXT :Text content was read; the text content can be retrieved using the getText() method.

    END_TAG: An end tag was read.

    END_DOCUMENT:No more events are available.

    ..

    Android XMLPullParser XML Parsing

    The XMLPullParser will examine an XML file with a series of events, such as those listed above to parse the XML document.

    To read and parse the XML data using XMLPullParser in android, we need to create an instance of XMLPullParserFactory, XMLPullParser objects in android applications.

    Below is my code for reading and parsing the XML data using XMLPullParser in android applications with XMLPullParserFactory, XMLPullParser and series of events to get the required information from XML objects.

    The data is then passed into a BaseAdapter.

    package com.f.countryarraytest;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;
    import org.xmlpull.v1.XmlPullParserFactory;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class MainActivity extends AppCompatActivity {
    
        private ListView listView;
        public TextView tvCountryName, tvCountryCode, tvCountryIso2;
        private CustomAdapter customAdapter;
        private static final String tagCountryItem = "country";
        private static final String tagCountryName = "countryName";
        private static final String tagCountryCode = "countryCode";
        private static final String tagCountryIso2 = "countryIso2";
        private static final String tagCountryIso3 = "countryIso3";
        private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
        private ArrayList<HashMap<String, String>> countryListArray;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            listView        = findViewById(R.id.listView);
    
            tvCountryName   = findViewById(R.id.tvMainActivity_CountryName);
            tvCountryCode   = findViewById(R.id.tvMainActivity_CountryCode);
            tvCountryIso2   = findViewById(R.id.tvMainActivity_CountryIso2);
    
            countryName     = new ArrayList<>();
            countryCode     = new ArrayList<>();
            countryIso2     = new ArrayList<>();
            countryIso3     = new ArrayList<>();
    
            try{
                countryListArray = new ArrayList<>();
                HashMap<String,String> country = new HashMap<>();
    
                InputStream inputStream             = getAssets().open("countries.xml");
                XmlPullParserFactory parserFactory  = XmlPullParserFactory.newInstance();
                parserFactory.setNamespaceAware(true);
                XmlPullParser parser                = parserFactory.newPullParser();
    
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
                parser.setInput(inputStream,null);
    
                String tag = "" , text = "";
                int event = parser.getEventType();
    
                while (event!= XmlPullParser.END_DOCUMENT){
                    tag = parser.getName();
                    switch (event){
                        case XmlPullParser.START_TAG:
                            if(tag.equals(tagCountryItem))
                                country = new HashMap<>();
                            break;
                        case XmlPullParser.TEXT:
                            text=parser.getText();
                            break;
                        case XmlPullParser.END_TAG:
    
                            if (tag.equalsIgnoreCase(tagCountryName)){
                                country.put(tagCountryName,text);
    
                            } else if (tag.equalsIgnoreCase(tagCountryCode)){
                                country.put(tagCountryCode,text);
    
                            } else if (tag.equalsIgnoreCase(tagCountryIso2)){
                                country.put(tagCountryIso2,text);
    
                            } else if (tag.equalsIgnoreCase(tagCountryIso3)){
                                country.put(tagCountryIso3,text);
    
                            } else if (tag.equalsIgnoreCase(tagCountryItem)){
    
                                if(country != null){
                                    countryListArray.add(country);
                                }
                            }
    
                            /*switch (tag){
                                case tagCountryName: country.put(tagCountryName,text);
                                    break;
    
                                case tagCountryCode: country.put(tagCountryCode,text);
                                    break;
    
                                case tagCountryIso2: country.put(tagCountryIso2,text);
                                    break;
    
                                case tagCountryIso3: country.put(tagCountryIso3,text);
                                    break;
    
                                case tagCountryItem:
                                    if(country != null){
                                        countryListArray.add(country);}
                                    break;
                            }*/
    
                            break;
                    }
                    event = parser.next();
                }
    
                //Get ArrayList With County Data HashMap
                getHashMapData();
    
                customAdapter   = new CustomAdapter(this, countryName, countryCode, countryIso2, countryIso3);
                listView.setAdapter(customAdapter);
            }
            catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
    
    
        }
    
        private void getHashMapData(){
    
            countryName.clear();
            countryCode.clear();
            countryIso2.clear();
            countryIso3.clear();
    
            try {
    
                if (countryListArray.size() > 0) {
    
                    for (int i = 0; i < countryListArray.size(); i++) {
    
                        HashMap<String, String> hashmap = countryListArray.get(i);
    
                        countryName.add(hashmap.get(tagCountryName));
                        countryCode.add(hashmap.get(tagCountryCode));
                        countryIso2.add(hashmap.get(tagCountryIso2));
                        countryIso3.add(hashmap.get(tagCountryIso3));
                    }
                }
            } catch (Exception e){}
        }
    
    }
    

    Here is the code for my BaseAdapter.

    package com.f.countryarraytest;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class CustomAdapter extends BaseAdapter {
    
        private Context context;
        private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
        private LayoutInflater layoutInflater;
        private TextView tvSelectedCountryName, tvSelectedCountryCode, tvSelectedCountryIso2;
    
        public CustomAdapter(MainActivity mainActivity, ArrayList<String> countryName, ArrayList<String> countryCode, ArrayList<String> countryIso2, ArrayList<String> countryIso3){
    
            this.context        = mainActivity.getApplicationContext();
            this.countryName    = countryName;
            this.countryCode    = countryCode;
            this.countryIso2    = countryIso2;
            this.countryIso3    = countryIso3;
            this.layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            this.tvSelectedCountryName  = mainActivity.tvCountryName;
            this.tvSelectedCountryCode  = mainActivity.tvCountryCode;
            this.tvSelectedCountryIso2  = mainActivity.tvCountryIso2;
        }
    
        @Override
        public int getCount() {
            return countryName.size();
        }
    
    
        @Override
        public Object getItem(int position) {
            return position;
        }
    
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            if(convertView == null)
            {
                convertView = layoutInflater.inflate(R.layout.custom_listview_country_picker, null);
            }
    
            LinearLayout llItem;
            final TextView tvCountryName, tvCountryCode, tvCountryIso2;
    
            llItem          = convertView.findViewById(R.id.llCountryPicker);
            tvCountryName   = convertView.findViewById(R.id.tvCountryName);
            tvCountryCode   = convertView.findViewById(R.id.tvCountryCode);
            tvCountryIso2   = convertView.findViewById(R.id.tvCountryIso2);
    
            //Set Values
            tvCountryName.setText(countryName.get(position));
            tvCountryCode.setText(String.valueOf(countryCode.get(position)));
            tvCountryIso2.setText(countryIso2.get(position));
    
            llItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    tvSelectedCountryName.setText(tvCountryName.getText().toString().trim());
                    tvSelectedCountryCode.setText(tvCountryCode.getText().toString().trim());
                    tvSelectedCountryIso2.setText(tvCountryIso2.getText().toString().trim());
                }
            });
    
            return convertView;
        }
    }
    

    Here is the xml layout for the list item.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="horizontal">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:id="@+id/llCountryPicker"
        android:gravity="center_vertical"
        android:layout_height="wrap_content">
    
        <!--Country Flag-->
        <ImageView
            android:layout_width="28dp"
            android:padding="2dp"
            android:contentDescription="countryFlag"
            android:src="@android:drawable/ic_menu_gallery"
            android:id="@+id/ivCountryPicker_CountryFlag"
            android:layout_marginStart="10dp"
            android:layout_height="28dp"
            />
    
        <!-- Country Code And Name -->
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_marginTop="5dp"
            android:layout_height="wrap_content">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
                <TextView
                    android:id="@+id/tvCountryIso2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="10dp"
                    android:singleLine="true"
                    android:textColorHint="#000"
                    android:layout_marginEnd="10dp"
                    android:hint="Iso2"
                    android:textColor="#000000"
                    android:textSize="14dp"
                    />
                <TextView
                    android:id="@+id/tvCountryName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:singleLine="true"
                    android:textColorHint="#000"
                    android:layout_marginEnd="10dp"
                    android:hint="country Name"
                    android:textColor="#000000"
                    android:textSize="14dp"
                    />
            </LinearLayout>
            <TextView
                android:id="@+id/tvCountryCode"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:singleLine="true"
                android:minEms="3"
                android:textColorHint="#000"
                android:maxEms="5"
                android:layout_marginEnd="10dp"
                android:hint="000"
                android:textColor="#000000"
                android:textSize="14dp"
                />
        </LinearLayout>
    </LinearLayout>