Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在类之间传递数组的值_Java_Android_Multidimensional Array_Spinner - Fatal编程技术网

Java 在类之间传递数组的值

Java 在类之间传递数组的值,java,android,multidimensional-array,spinner,Java,Android,Multidimensional Array,Spinner,当选中该选项启动一个意图时,我正在使用微调器,所启动的类将获取和显示XML提要 我试图根据用户选择的内容调用不同的XML文件。我不确定如何将该值传递给我的XMLfunctions.java,一旦选择,其他类是否可以引用该数据 这是我的Eclipse包 我的想法是有一个多维数组,其中包含微调器的标题和共同的XML url: package com.patriotsar; import android.app.Activity; import android.content.Intent

当选中该选项启动一个意图时,我正在使用微调器,所启动的类将获取和显示XML提要

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

这是我的Eclipse包

我的想法是有一个多维数组,其中包含微调器的标题和共同的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) {
            }

        });




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

}
package com.patriotsar;
导入java.io.IOException;
导入java.io.StringReader;
导入java.io.UnsupportedEncodingException;
导入java.net.MalformedURLException;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.parsers.parserConfiguration异常;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
导入org.xml.sax.InputSource;
导入org.xml.sax.SAXException;
公共类函数{
公共最终静态文档XMLfromString(字符串xml){
单据单据=空;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
试一试{
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=新的InputSource();
is.setCharacterStream(新的StringReader(xml));
doc=db.parse(is);
}捕获(ParserConfiguration异常e){
System.out.println(“XML解析错误:+e.getMessage());
返回null;
}捕获(SAXE异常){
System.out.println(“错误的XML文件结构:+e.getMessage());
返回null;
}捕获(IOE异常){
System.out.println(“I/O验证:+e.getMessage());
返回null;
}
退货单;
}
/**返回元素值
*@param elem元素(它是XML标记)
*@返回元素值,否则为空字符串
*/
公共最终静态字符串getElementValue(节点元素){
节点儿童;
if(elem!=null){
if(elem.hasChildNodes()){
for(kid=elem.getFirstChild();kid!=null;kid=kid.getNextSibling()){
if(kid.getNodeType()==Node.TEXT\u节点){
return kid.getNodeValue();
}
}
}
}
返回“”;
}
公共静态字符串getXML(){
字符串行=null;
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet httpPost=新的HttpGet(“http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
line=EntityUtils.toString(httpEntity);
}捕获(不支持的编码异常e){
line=“无法连接到服务器”;
}捕获(格式错误){
line=“无法连接到服务器”;
}捕获(IOE异常){
line=“无法连接到服务器”;
}
回流线;
}
公共静态整数结果(文档文档){
节点结果=doc.getDocumentElement();
int res=-1;
试一试{
res=Integer.valueOf(results.getAttributes().getNamedItem(“count”).getNodeValue());
}捕获(例外e){
res=-1;
}
返回res;
}
公共静态字符串getValue(元素项,字符串str){
NodeList n=item.getElementsByTagName(str);
返回XMLfunctions.getElementValue(n.item(0));
}
}

抱歉,我仍在学习,但我很高兴能进入更高级的(对我来说)编程。任何帮助都会很棒


到目前为止,该应用程序仍能正常工作,但无论如何都会调用相同的xml。

我不太理解您的描述,但如果您希望通过Intents在活动之间传递数据,请确保传递的数据可以作为额外的,或者,如果您希望发送实际对象,请确保您的对象实现可包裹界面。

对不起,不清楚,我发布了所有代码以帮助您更清楚地了解。我将使用“附加”设施调查“附加”。。。可以将其视为一个名称-值对容器,它允许您提供字符串名称,以及您可以认为是值的任何其他数据类型。。。在活动或服务之间。您可以根据需要包含任意数量的这些名称值项。。。我认为唯一的限制是名称必须是唯一的(这并不奇怪)。您还可以为值包含对象,只要该对象实现了Parcelable接口(这非常容易添加到您自己的类中);bundle.putString(“选择”,项);myIntent.putExtras(bundle);但是“putString()不起作用,是因为项是数组值吗?bundle.putInt(“selection”,item);看起来可以起作用。谢谢您的帮助。
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));

}