在类之间传递数组的值

时间:2011-06-21 03:12:08

标签: java android multidimensional-array spinner

当我选择启动一个intent时,我正在使用一个微调器,并且启动的类获取并且XML feed并显示它。

我正在尝试根据用户选择的内容调用不同的XML文件。我不确定如何将值传递给我的XMLfunctions.java,一旦选中,其他类可以引用该数据吗?

这是我的Eclipse包Download

我的thourghts是一个多维数组,其中包含微调器的标题和硬币的XML URL:

   package com.patriotsar;


import android.app.Activity;

import android.content.Intent;
import android.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) {
            }

        });




     }
    }

然后我有一个监听器,当选择了另一个默认项目时调用意图ShowXMLPAR.class。 ShowXMLPAR类从XMLfunctions.java类调用一个函数,然后显示返回的数据。因此,我想,所选数组项中的第二个值需要传递给两个页面。

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));

}

}

对不起,我还在学习,但很高兴能够进入更先进的(对我来说)编程。任何帮助都是极好的。

截至目前,该应用程序可以运行,但无论如何都会调用相同的xml。

1 个答案:

答案 0 :(得分:1)

我没有很好地遵循您的描述,但是如果您想要通过Intents在Activities之间传递数据,那么请确保您传递的数据可以作为Extra包含,或者如果您更喜欢发送实际对象,那么确保你的对象实现了Parcelable接口。