Skip to content Skip to sidebar Skip to footer

Adding A Node To Same Xml File On Sd Card Under Its Root Tag In Android

Hello friends I have this code in which I am writing an xml file to my sd card: public class SingleItemView extends Activity { File newxmlfile = new File(Environment.getExtern

Solution 1:

The issue with your code is that You're not appending new data properly.

As described in this answer in case if file exists You need to find last line of it (in this case it's </root>) and provide new data before it, so it will appear in the same xml document, but not new one.

The code is below (I've moved file modification part to separate function and removed all stuff which is not related to your problem):

publicclassMyActivityextendsActivity {

    privatestaticfinalStringTAG="MyActivity";

    Filenewxmlfile=newFile(Environment.getExternalStorageDirectory() + "/testfinal.xml");
    int number;
    String numberOfItems;
    ImageView addToCartButton;
    finalContextcontext=this;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Log.e(TAG, "File is " + Environment.getExternalStorageDirectory() + "/testfinal.xml");

        if (!newxmlfile.exists()){
            try{
                newxmlfile.createNewFile();
            }catch(IOException e){
                Log.e("IOException", "exception in createNewFile() method");
            }
        }

        //xml
        addToCartButton = (ImageView)findViewById(R.id.imageView1);
        addToCartButton.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // get prompts.xml viewLayoutInflaterli= LayoutInflater.from(context);
                ViewpromptsView= li.inflate(R.layout.promptdialog, null);

                AlertDialog.BuilderalertDialogBuilder=newAlertDialog.Builder(
                        context);

                if (promptsView == null) {
                    return;
                }

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                finalEditTextuserInput= (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                newDialogInterface.OnClickListener() {
                                    @OverridepublicvoidonClick(DialogInterface dialog, int id) {
                                        if (userInput == null || userInput.getText() == null) {
                                            return;
                                        }

                                        numberOfItems = userInput.getText().toString();
                                        number = Integer.parseInt(numberOfItems);
                                        StringutCostString="200";//txtutcost.getText().toString();floatcost= Float.parseFloat(utCostString);
                                        floattotalCost= Float.parseFloat(utCostString) * number;
                                        Stringtc= Float.toString(totalCost);
                                        StringcodeText="codeText";//txtmodno.getText().toString();//Loop for writing xmltry {
                                            updateFile(codeText, utCostString, tc);

                                            Contextcontext= getApplicationContext();
                                            CharSequencetext="Save!";
                                            intduration= Toast.LENGTH_SHORT;
                                            Toasttoast= Toast.makeText(context, text, duration);
                                            toast.show();
                                        } catch (Exception e) {
                                            Log.e("Exception", "error occurred while creating xml file");
                                        }
                                        //end of xml lopp
                                    }
                                })
                        .setNegativeButton("Cancel",
                                newDialogInterface.OnClickListener() {
                                    publicvoidonClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialogAlertDialogalertDialog= alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
        });
    }

    /**
     * Appends new data to the file
     *
     * @param codeText
     * @param utCostString
     * @param tc
     */privatevoidupdateFile(final String codeText, final String utCostString, final String tc)throws IOException {
        RandomAccessFilerandomAccessFile=null;
        StringclosingLine=null;
        booleanfileExists=true;

        if (newxmlfile.length() == 0) {
            fileExists = false;

            try {
                randomAccessFile = newRandomAccessFile(newxmlfile, "rw");
            } catch(FileNotFoundException e) {
                Log.e("FileNotFoundException", "can't create FileOutputStream");
            }
        } else {
            try {
                randomAccessFile = newRandomAccessFile(newxmlfile, "rw");
                randomAccessFile.seek(0);

                String lastLine;
                longlastLineOffset=0;
                intlastLineLength=0;

                lastLine = randomAccessFile.readLine();

                while (lastLine != null) {
                    // +1 is for end line symbol
                    lastLineLength = lastLine.length();
                    lastLineOffset = randomAccessFile.getFilePointer();

                    closingLine = lastLine;
                    lastLine = randomAccessFile.readLine();
                }

                lastLineOffset -= lastLineLength;
                // got to string before last
                randomAccessFile.seek(lastLineOffset);
            } catch(FileNotFoundException e) {
                Log.e("FileNotFoundException", "can't create FileOutputStream");
            } catch (IOException e) {
                Log.e("IOException", "Failed to find last line");
            }
        }

        // Now random access file is positioned properly, we can append new xml data//we create a XmlSerializer in order to write xml dataXmlSerializerserializer= Xml.newSerializer();

        if (randomAccessFile == null) {
            return;
        }

        try {
            finalStringWriterwriter=newStringWriter();

            serializer.setOutput(writer);

            if (!fileExists) {
                serializer.startDocument(null, true);
                serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
                serializer.startTag(null, "root");
            } else {
                serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
            }

            serializer.startTag(null, "code");
            serializer.text(codeText);
            serializer.endTag(null, "code");

            serializer.startTag(null, "price");
            serializer.text(utCostString);
            serializer.endTag(null, "price");

            serializer.startTag(null, "quantity");
            serializer.text(numberOfItems);
            serializer.endTag(null, "quantity");

            serializer.startTag(null, "totalcost");
            serializer.text(tc);
            serializer.endTag(null, "totalcost");

            if (!fileExists) {
                serializer.endTag(null, "root");
            }

            serializer.flush();

            if (closingLine != null) {
                serializer.endDocument();
                writer.append("\n");
                writer.append(closingLine);
            }

            // Add \n just for better output in console
            randomAccessFile.writeBytes(writer.toString());
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            randomAccessFile.close();
        }
    }
}

Post a Comment for "Adding A Node To Same Xml File On Sd Card Under Its Root Tag In Android"