Friday, 3 June 2011

How to read local xml file from my asset folder or in res/raw folder?

Here is my main file of java to read xml and parse it.

public class Readxml extends ListActivity {
    ArrayList<String> items=new ArrayList<String>();
    TextView selection;
    String myvalues;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        selection=(TextView)findViewById(R.id.selection);
        Button btn=(Button)findViewById(R.id.btnget);
       
       
       try
       {
           InputStream is=getResources().openRawResource(R.raw.my_xml_sample);
          //here is i specified my xml file name
           DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
           Document doc=builder.parse(is, null);
           NodeList words=doc.getElementsByTagName("Data");
           //NodeList words=doc.getElementsByTagNameNS(arg0, arg1);
          // NodeList mywords=doc.getElementsByTagNameNS("Data" , "Data" );
         
           for(int i=0;i<words.getLength();i++){
              items.add(((Element)words.item(i)).getTextContent());
            // myvalues=((Element)words.item(i)).getNodeValue();
              Log.v("log_tag", "my values is"+ myvalues);
           }
           is.close();
       }
       catch(Throwable t){
          
           Toast.makeText(this, "Exception :"+ t.toString(), 2000).show();
          
          
       }
      
       setListAdapter(new ArrayAdapter<String>(this,
               android.R.layout.simple_list_item_1,
               items));
       btn.setOnClickListener(new OnClickListener() {
       
        @Override
        public void onClick(View arg0) {
            String[] mylist =new String[items.size()];
            for(int i=0,j=0;i<items.size();i=i+18,j++){
                Log.v("log_tag", "the values of item is"+items.get(i));
                mylist[j]=items.get(i);
           
                Log.v("log_tag", "her is my column"+mylist[j]);
           
            }
           
        }
    });
      
       
    }
   
    public void onListItemClick(ListView parent, View v, int position,
            long id) {
            selection.setText(items.get(position).toString());
            }
}

1 comment:

  1. Document doc=builder.parse(is, null);

    What is the "is,null". when i have put the code into my work it says create local variable, but you haven't used it any where.

    ReplyDelete