Write XML in Android

When we write a XML in android, you can choose difference ways, in this case we recommend XMLSerializer, which is an efficient and maintainable way to parse XML on Android.

Implements an XML serializer supporting both DOM and SAX pretty serializing.

We put this simple line:

            xmlSerializer.setOutput(writer);
            xmlSerializer.startDocument("UTF-8", true);
            xmlSerializer.startTag(null, "doc");

            xmlSerializer.startTag(ns, country);
            xmlSerializer.text(filmObject.getCountry());
            xmlSerializer.endTag(ns, country);

            xmlSerializer.endTag(ns, "doc");
            xmlSerializer.endDocument();
            xmlSerializer.flush();

We made a example with films:

<?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>

In your activity you can put this lines with this films:

public void writeXml(List<Film> films) {


        try {
            FileOutputStream fileOutputStream = new FileOutputStream(mFileOutPut);
            XmlSerializer xmlSerializer = Xml.newSerializer();
            StringWriter writer = new StringWriter();

            xmlSerializer.setOutput(writer);
            xmlSerializer.startDocument("UTF-8", true);
            xmlSerializer.startTag(null, "doc");

            insertFilms(xmlSerializer, films);

            xmlSerializer.endTag(ns, "doc");
            xmlSerializer.endDocument();
            xmlSerializer.flush();
            String dataWrite = writer.toString();
            fileOutputStream.write(dataWrite.getBytes());
            fileOutputStream.close();

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

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

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

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

        }


    }

    public void insertFilms(XmlSerializer xmlSerializer, List<Film> films) throws IOException {
        final String film = "film";
        String title = "title";
        String runningTime = "runningTime";
        String country = "country";
        String director = "director";
        String cast = "cast";
        Film filmObject;
        for (int i=0; i<films.size(); i++) {
            filmObject = films.get(i);
            xmlSerializer.startTag(ns, film);
            xmlSerializer.attribute(ns, title, filmObject.getTitle());

            xmlSerializer.startTag(ns, runningTime);
            xmlSerializer.text(filmObject.getRunningTime());
            xmlSerializer.endTag(ns, runningTime);

            xmlSerializer.startTag(ns, country);
            xmlSerializer.text(filmObject.getCountry());
            xmlSerializer.endTag(ns, country);

            xmlSerializer.startTag(ns, director);
            xmlSerializer.text(filmObject.getDirector());
            xmlSerializer.endTag(ns, director);

            xmlSerializer.startTag(ns, cast);
            insertCast(xmlSerializer, filmObject.getCast());
            xmlSerializer.endTag(ns, cast);

            xmlSerializer.endTag(null, film);
        }

    }

    public void insertCast (XmlSerializer xmlSerializer, List<Actor> cast) throws IOException {
        String name = "name";
        String surname = "surname";
        Actor actor;
        for (int i=0; i<cast.size(); i++) {
            actor = cast.get(i);
            xmlSerializer.startTag(null, name);
            xmlSerializer.text(actor.getName());
            xmlSerializer.endTag(null, name);

            xmlSerializer.startTag(null, surname);
            xmlSerializer.text(actor.getSurname());
            xmlSerializer.endTag(null, surname);
        }

    }

Example in GitHub

How to read and write JSON from file with Gson

You can save JSON when you call web service. You must use the same methods which was used last item.

When you read this JSON, you must use Gson library.

http://howtodoinjava.com/wp-content/uploads/2014/06/google-gson.jpg
Download Gson Library.

public void returnJSONToYourModel() {
		final String json = Utils.readFromFile(MainActivity.this);
		final Gson gson = new Gson();
		final YourModel yourModel = gson.fromJson(json, YourModel.class);

	}

Download code.

How to read and write from file

JSON

It’s very esay to read and write from a file.

Download code

public static void writeToFile(String data, Activity activity) {
		try {
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					activity.openFileOutput("config.txt", Context.MODE_PRIVATE));
			outputStreamWriter.write(data);
			outputStreamWriter.close();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
		}
	}

	public static String readFromFile(Activity activity) {

		String ret = "";

		try {
			InputStream inputStream = activity.openFileInput("config.txt");

			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();
			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}
		 return ret;
	}