开发者

Pass values of array inbetween classes

I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.

I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?

HERE is my Eclipse Package Download

My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:

   package com.patriotsar;


import android.app.Activity;

import android.content.Intent;
import androi开发者_如何学God.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;







public class patriosar extends Activity {

    private Button goButton;

    private String array_spinner[];



    String url = "http://www.patriotsar.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    Uri u = Uri.parse(url);
    Context context = this;
    Spinner areaspinner;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        array_spinner=new String[4];
        array_spinner[0]="George Washington","gw.xml";
        array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
        array_spinner[2]="THOMAS JEFFERSON","tj.xml";
        array_spinner[3]="PATRICK HENRY","ph.xml";

        goButton = (Button)findViewById(R.id.goButton);


        areaspinner = (Spinner) findViewById(R.id.areaspinner);

        ArrayAdapter<String> adapter = 
            new ArrayAdapter<String> (this, 
                    android.R.layout.simple_spinner_item,array_spinner);
        areaspinner.setAdapter(adapter);


        goButton.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v){
                try {
                      // Start the activity
                        i.setData(u);
                      startActivity(i);
                    } catch (ActivityNotFoundException e) {
                      // Raise on activity not found
                      Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
                    }
                  } 
        });


        areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                int item = areaspinner.getSelectedItemPosition();

                if(item != 0){
                       Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
                       startActivityForResult(myIntent, 0);
                    }
                else {
                   // finish();
                }



            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }

        });




     }
    }

I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.

ShowXMLPAR.java:

package com.patriotsar;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.patriotsar.XMLfunctions;


import android.app.ListActivity;
import android.content.Intent;


import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ShowXMLPAR extends ListActivity {


     private Button backButton;
     /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        backButton = (Button)findViewById(R.id.backButton);

        backButton.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View view){
                   Intent myIntent = new Intent(view.getContext(), patriosar.class);
                   startActivityForResult(myIntent, 0);

                }

         });


        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
            Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();  
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {                           
            HashMap<String, String> map = new HashMap<String, String>();    

            Element e = (Element)nodes.item(i);
            map.put("main_content", XMLfunctions.getValue(e, "content"));
            map.put("name", XMLfunctions.getValue(e, "name"));
            mylist.add(map);            
        }       
//       
        ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout, 
                        new String[] {"main_content", "name" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

       setListAdapter(adapter);



}
}

XMLfunctions.java:

package com.patriotsar;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public static String getXML(){  
            String line = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }

            return line;

    }

    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);        
        return XMLfunctions.getElementValue(n.item(0));

}

}

Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.

As of now the app works but calls the same xml no matter what.


I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜