Ioanna Dln
Ioanna Dln

Reputation: 309

creating an xml file?

I am trying to create an xml file in android but I get empty files. I have read many articles about this issue but I did not manage to find a solution. My mimeType is text/xml and this is my code for selecting directory

 private void createFile(String mimeType, String fileName) {
            Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType(mimeType);
            intent.putExtra(Intent.EXTRA_TITLE, fileName);
            startActivityForResult(intent, WRITE_REQUEST_CODE);
}

and this is my code for passing data to my file.

public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {
        if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Uri uri = resultData.getData();
            String fileData = "the data I want to write to file";
            FileOutputStream fileOutputStream=null;
            try{
             fileOutputStream=(FileOutputStream) getContentResolver().openOutputStream(uri); }catch (Exception e){
                Log.e(LOG_TAG,e.getMessage());
            }
            XmlSerializer serializer= Xml.newSerializer();
            StringWriter writer=new StringWriter();
            try {
                serializer.setOutput(writer);
                serializer.startDocument("UTF-8",true);
                serializer.startTag("","myTag");
                serializer.text(fileData);
                serializer.endTag("","myTag");
                serializer.endDocument();
                String val= writer.toString();
                fileOutputStream.write(val.getBytes());
            } catch (Exception e) {
                Toast.makeText(this, "Error - Exception writing to " + uri.toString(), Toast.LENGTH_SHORT).show();
         }

the file is created but there is nothin in it. Can anyone help me?

Upvotes: 1

Views: 86

Answers (2)

Ioanna Dln
Ioanna Dln

Reputation: 309

I really don't unerstand why but it seems to be a mobile device issue. My code works fine on other mobile devices. Thanks

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006819

fileOutputStream=(FileOutputStream) getContentResolver().openOutputStream(uri); should be crashing with a ClassCastException. openOutputStream() returns an OutputStream, but it is not necessarily a FileOutputStream.

The stack trace for this exception should be showing up in LogCat.

Upvotes: 1

Related Questions