0

I'm trying to write an app that reads from a local xml file, and need some help. I've read a few articles on here as well as google and youtube to read/write xml files, but most of them are for files online. I'm looking to read/write xml locally in Android. So far, I figure, the steps I need are as follows.

  1. Read XML file.
  2. convert elements into String Array.
  3. populate list with String Array.

I can't seem to get the first 2 to work. I'm not looking for code, or an easy way of doing it. I truely want to figure this out, but need some guidance from all of you guru's on here. I really can't find a way to read the xml file. From what I've found here, I need to put the xml file in the res/raw folder, then from there, i'm not too sure what to do. How do I read that into the array? Once I do get this thing up and running, i'll do what I can to post the code and hopefully help others who are having similar issues. Thanks again!

Android Student
  • 153
  • 2
  • 12
  • this can help you http://stackoverflow.com/questions/2728064/parsing-local-xml-file-using-sax-in-android – HADEV Jul 21 '12 at 01:02

2 Answers2

2

In your main class

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleList extends Activity {  //SimpleList is the name of this class

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final ListView lv=(ListView)findViewById(R.id.listView1);       

        //final ArrayList<String> myNewList = new ArrayList<String>();

        ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.simple_array,android.R.layout.simple_list_item_1);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub      
                String item=lv.getItemAtPosition(arg2).toString();
                String itemordered;
                itemordered = item + " added to list";
                Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Create a String Array in strings.xml

<resources>

    <string name="app_name">SimpleList</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">SimpleList</string>

    <string-array name="simple_array">
        <item>Bacon Double Cheese Burger</item>
        <item>Bacon Cheeses Burger</item>
        <item>Cheese Burger</item>
        <item>Hamburger</item>
        <item>Grilled Chicken Sandwich</item>
        <item>Crispy Chicken Sandwich</item>
        <item>Chicken Strips</item>
        <item>Hot Dog</item>
        <item>Chocolate Chip Cookie Dough Polar Swirl</item>
        <item>Vanilla Shake</item>
        <item>Chocolate Shake</item>
        <item>Strawberry Shake</item>
    </string-array>


</resources>    

Create a Layout for your ListView in main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#FFCC00"
        android:dividerHeight="2dp" >
    </ListView>

</LinearLayout> 
Sobo
  • 487
  • 8
  • 21
1

I finally got it to work the way I want, here is what I was trying to accomplish. To all that provided answers, Thank you very much! I took pieces of each of your patterns, and customized it to what I need. I am by no means an android/java/xml expert, but here is what I got and its working the way I want yay!

public class MainActivity extends Activity {

Spinner spinner;
List<String> ingredient = new ArrayList<String>();
List<String> effect1 = new ArrayList<String>();
List<String> effect2 = new ArrayList<String>();
List<String> effect3 = new ArrayList<String>();
List<String> effect4 = new ArrayList<String>();

XmlResourceParser myXml;
int eventType;
String nodeValue;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    loadXml(); // Reads XML and loads it into Lists, One list for each element
    convertListToSpinner(); // Takes Lists and merges data with Spinners (Currently Unimplemented)


}


private void convertListToSpinner() {
    // TODO Auto-generated method stub

}


private void loadXml() {
    // TODO Auto-generated method stub
    myXml = getBaseContext().getResources().getXml(R.xml.xmlfilename);
    try {
        myXml.next();

    eventType = myXml.getEventType(); // Get current xml Event

    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    while(eventType != XmlPullParser.END_DOCUMENT){
        if(eventType == XmlPullParser.START_DOCUMENT){
            // checks can be placed here to make sure file is read
        }
        else if(eventType == XmlPullParser.START_TAG){
            nodeValue = myXml.getName();

            try{
            if(nodeValue.equalsIgnoreCase("Ingredient")){ //Finds Ingredient tag
            myXml.next(); //Since the ingredient tag does not hold the text, we go to next element area
            ingredient.add(myXml.getText().trim()); // Set the text of the Ingredient tag to list
            }

            //Since the effect tags are followed by ending tags, we can just do nextText() to get tag text
            if(nodeValue.equalsIgnoreCase("Effect1")){
                effect1.add(myXml.nextText().trim()); // Set the text of the Effect1 tag to list
            }
            if(nodeValue.equalsIgnoreCase("Effect2")){
                effect2.add(myXml.nextText().trim()); // ditto
            }
            if(nodeValue.equalsIgnoreCase("Effect3")){
                effect3.add(myXml.nextText().trim()); // ditto
            }
            if(nodeValue.equalsIgnoreCase("Effect4")){
                effect4.add(myXml.nextText().trim()); // ditto
            }
            }catch(Exception e){
                e.getMessage();
            }


        }
        try {
            eventType = myXml.next();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    for(int i = 0; ingredient.size() > i; i++){
        System.out.println(ingredient.get(i));

    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}




}

And the XML file is in the current format.

<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        name="item"
        type="string">
        <Ingredient>
         Intrests
            <effect1>
            Android
            </effect1>
            <effect2>
            Programming
            </effect2>
            <effect3>
            Type O Negative
            </effect3>
            <effect4>
            Sirenia
            </effect4>
        </Ingredient>
        <Ingredient>
        Virtues
            <effect1>
        Power
            </effect1>
            <effect2>
        Money
            </effect2>
            <effect3>
        Knowledge
            </effect3>
            <effect4>
        Kindness
            </effect4>
        </Ingredient>
    </item>
</resources>

I hope this helps others who are having similar problems. Again, thanks to Sobo and HADEV for contributing!!

I'm sure there is a much better way of doing what is being done, but I'm just happy I got this to work :)

Android Student
  • 153
  • 2
  • 12