Read XML in Android

Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form. XML is a popular format for sharing data on the internet. Websites that frequently update their content, such as news sites or blogs, often provide an XML feed so that external programs can keep abreast of content changes. Uploading and parsing XML data is a common task for network-connected apps. This lesson explains how to parse XML documents and use their data.

Choose Parser

We recommend XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface:

Either choice is fine. The example in this section usesExpatPullParser, via Xml.newPullParser().

Analyze

The first step in parsing a film

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<doc>
	<film title="Scarface">
		<runningTime>163 min.</runningTime>
		<country>USA</country>
		<director>Brian De Palma</director>
		<cast><name>Al</name>
			<surname>Pacino</surname><name> Steven</name>
			<surname>Bauer</surname><name>Michelle</name><surname>Pfeiffer</surname>
			<name>Mary Elizabeth</name>
			<surname>Mastrantonio</surname>
		</cast>
	</film>
	<film title="Hitman">
		<runningTime>96 min.</runningTime>
		<country>USA</country>
		<director>Aleksander Bach</director>
		<cast><name>Rupert</name>
			<surname>Friend</surname>
			<name>Zachary</name>
			<surname>Quinto</surname>
			<name>Hannah</name>
			<surname>Ware</surname>
			<name>Ciarán</name>
			<surname>Hinds</surname>
		</cast>
	</film>
	<film title="Out of Africa">
		<runningTime>160 min.</runningTime>
		<country>USA</country>
		<director>Sydney Pollack</director>
		<cast>
			<name>Robert</name>
			<surname>Redford</surname>
			<name>Meryl</name>
			<surname>Streep</surname>
			<name>Klaus Maria</name>
			<surname>Brandauer</surname>
			<name>Michael</name>
			<surname>Kitchen</surname>
		</cast>
	</film>
</doc>

The readFilm() method does the actual work of processing the feed. It looks for elements tagged “entry” as a starting point for recursively processing the feed. If a tag isn’t an entry tag, it skips it. Once the whole feed has been recursively processed, readFilm() returns a List containing the entries (including nested data members) it extracted from the feed. This List is then returned by the parser.

public void readFilm() {
        try {

            InputStream inputStream = new FileInputStream(mFileOutPut);
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(inputStream, null);
            parser.nextTag();
            List<Film> filmsList =  readDoc(parser);

            ListAdapter adapter = new ListAdapter(filmsList, this);
            mListView.setAdapter(adapter);

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<Film> readDoc(XmlPullParser parser) throws XmlPullParserException, IOException {

        List<Film> list = new ArrayList<Film>();
        parser.require(XmlPullParser.START_TAG, ns, "doc");

        while (parser.next() != XmlPullParser.END_TAG) {
            list.add(readFilms(parser));
        }
        return list;
    }

    // Parses the contents of an film. If it encounters a title, runningTime, country, or director, hands them off
// to their respective "read" methods for processing. Otherwise, skips the tag.
    private Film readFilms(XmlPullParser parser) throws XmlPullParserException, IOException {
        parser.require(XmlPullParser.START_TAG, ns, "film");
        String title = null;

        for(int x=0; x<parser.getAttributeCount(); x++) {
            if (parser.getAttributeName(x).equals("title")) {
                title = parser.getAttributeValue(x);
            }
        }

        String runningTime = null;
        String country = null;
        String director = null;
        List<Actor> cast = new ArrayList<Actor>();

        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            if (name.equals("runningTime")) {
                runningTime = readRunningTime(parser);
            } else if (name.equals("country")) {
                country = readCountry(parser);
            } else if (name.equals("director")) {
                director = readDirector(parser);
            } else if (name.equals("cast")) {
                cast = readCast(parser);
            } else {
                skip(parser);
            }
        }
        return new Film( title, runningTime, country, director, cast);
    }

    private String readRunningTime(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "runningTime");
        String runningTime = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "runningTime");
        return runningTime;
    }

    private String readCountry(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "country");
        String country = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "country");
        return country;
    }

    private String readDirector(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "director");
        String director = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "director");
        return director;
    }

    private List<Actor> readCast(XmlPullParser parser) throws IOException, XmlPullParserException {
        List<Actor> listActor= new ArrayList<Actor>();
        parser.require(XmlPullParser.START_TAG, ns, "cast");

        String nameActor = null;
        String surnameActor = null;

        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String nameParser = parser.getName();
            if (nameParser.equals("name")) {
                nameActor = readNameActor(parser);
            } else if(nameParser.equals("surname")) {
                surnameActor = readSurnameActor(parser);
                listActor.add(new Actor(nameActor, surnameActor));
            } else {
                skip(parser);
            }

        }
        return listActor;
    }

    private String readNameActor(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "name");
        String nameActor = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "name");
        return nameActor;
    }

    private String readSurnameActor(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "surname");
        String surnameActor = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "surname");
        return  surnameActor;
    }

    // For the tags title and runningTime, country, director their text values.
    private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";
        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }
    private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
                case XmlPullParser.END_TAG:
                    depth--;
                    break;
                case XmlPullParser.START_TAG:
                    depth++;
                    break;
            }
        }
    }

Example in GitHub

TabLayout with Android Design Support Library

TabLayout with Android Design Support Library

Switching between different views in your app via tabs is not a new concept to material design and they are equally at home as a top level navigation pattern or for organizing different groupings of content within your app.

The Design library’s TabLayout implements both fixed tabs, where the view’s width is divided equally between all of the tabs, as well as scrollable tabs, where the tabs are not a uniform size and can scroll horizontally. Tabs can be added programmatically:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setElevation(0);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);


        viewPager.setAdapter(new TabsAdapter(getSupportFragmentManager(), this));
        tabLayout.setupWithViewPager(viewPager);
    }

We have to put our Adapter

public class TabsAdapter extends FragmentPagerAdapter {

    public static final int TOTAL_TABS = 3;
    public Context mContext;

    public TabsAdapter(FragmentManager fm, Context context) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new FirstFragment().newInstance();
            case 1:
                return new SecondFragment().newInstance();
            case 2:
            default:
                return new ThirdFragment().newInstance();
        }
    }

    @Override
    public int getCount() {
        return TOTAL_TABS;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return mContext.getString(R.string.fragment_first_title);
            case 1:
                return mContext.getString(R.string.fragment_second_title);
            case 2:
            default:
                return mContext.getString(R.string.fragment_third_title);
        }
    }

}

However, if you are using a ViewPager for horizontal paging between tabs, you can create tabs directly from yourPagerAdapter’s getPageTitle() and then connect the two together using setupWithViewPager(). This ensures that tab selection events update the ViewPager and page changes update the selected tab.

Also we can see the xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.thedeveloperworldisyours.tabbarr.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll"
        app:tabSelectedTextColor="@android:color/white"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

We can see the code in GitHub

Launch an application

Launch an application from another application

public void startNewActivity(Context context, String packageName) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent == null) {
        // Bring user to the market or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + packageName));
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Edit Pdf

Edit

We can edit a PDF, we have to create a new copy from original.

Generate pdf

private static String sInPutfile = "Android/data/Example.pdf";
    private static String sOutPutFile = "Android/data/ExampleCopy.pdf";

Then we have to PdfReader and PdfStamper, you can check the library iText.

private void editPDF(String string) {

        try {

            FileInputStream is = new FileInputStream(mPdfFile);
            PdfReader pdfReader = new PdfReader(is);
            PdfStamper pdfStamper = new PdfStamper(pdfReader,
                    new FileOutputStream(mPdfFileOutPut));

            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

                //create content from pdfStamper
                PdfContentByte content = pdfStamper.getUnderContent(i);

                // Text over the existing page
                BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                        BaseFont.WINANSI, BaseFont.EMBEDDED);

                content.beginText();
                //set the font
                content.setFontAndSize(bf, 18);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, string, 430, 15, 0);
                content.endText();

            }

            pdfStamper.close();

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

        } catch (DocumentException e) {
            e.printStackTrace();

        }

    }

And we can edit the PDF generated other PDF in android.

Example in Github

Generate PDF

Generate

In this example we use iText library, we can download in this link.

Generate pdf

Then we add the library in libs file and we include this conde in your activity.

private void generateAndwritePDF() {

        // create a new document
        Document document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(mPdfFile));
            document.open();
            document.add(new Paragraph("Title"));
            document.close();

            mProgressDialog.cancel();

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

And we can generate pdf in android.

Example in Github