Android:调用Activity时应用程序将关闭。意图,上下文,字符串

时间:2015-08-06 00:00:42

标签: android string android-intent android-context

我对Intent有疑问。我想在Page1.java中继承一个名为ReadXMLFile.java(即Context)的类的String。但是当Page1.java继续运行时,Android模拟器会发出警告并关闭应用程序! 这是ReadXMLFile.java的代码:

/**
 * Created by Giacomo B on 30/07/2015.
 */
package com.example.giacomob.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;

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

import java.io.InputStream;

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

public class ReadXMLFile {

     public static void readXMLFile(Context context) {


        try {
          //  Log.i("MyActivity", "casa");

            AssetManager assetManager = context.getAssets();
            InputStream is = assetManager.open("infofermata.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(is);

           // String filePath = "assets/infofermata.xml";
            //File fXmlFile = new File(filePath);
            //DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            //Document doc = dBuilder.parse(fXmlFile);

            //optional, but recommended
            //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nList = doc.getElementsByTagName("fermata");

            System.out.println("----------------------------");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                System.out.println("\nCurrent Element :" + nNode.getNodeName());
               // Log.i("MyActivity", "casa");

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                   // System.out.println("Staff id : " + eElement.getAttribute("id"));

                   // String stringidfermata = "Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent()"";

                   // Log.i("MyActivity", "\"Id Fermata : \" + eElement.getElementsByTagName(\"idfermata\").item(0).getTextContent()");
                    System.out.println("Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent());
                    String testo1 = eElement.getElementsByTagName("idfermata").item(0).getTextContent();
                    Intent nuovaPagina = new Intent(context, Page1.class);
                    nuovaPagina.putExtra("NomeDati1", testo1);
                    // I would to switch string called testo1 in Page1
                    System.out.println(testo1); //provo per vedere se stampa quello che ho messo nella variabile "testo1"
                    System.out.println("Naziome : " + eElement.getElementsByTagName("nazione").item(0).getTextContent());
                    System.out.println("Paese : " + eElement.getElementsByTagName("paese").item(0).getTextContent());
                    System.out.println("Via : " + eElement.getElementsByTagName("via").item(0).getTextContent());


                }

                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }


}

我想在Page1中切换名为testo1的字符串。 这是Page1.java代码:

package com.example.giacomob.myapplication;
import android.app.Activity;
import android.os.Bundle;

/**
 * Created by Giacomo B on 05/08/2015.
 */
public class Page1 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page1);
    }
    //Bundle datipassati = getIntent().getExtras();
   // String dato1 = datipassati.getString("NomeDati1");

    String dato1 = getIntent().getExtras().getString("NomeDati1");

    }

在logcat中出现:

 Process: com.example.giacomob.myapplication, PID: 3503
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.giacomob.myapplication/com.example.giacomob.myapplication.Page1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
            at com.example.giacomob.myapplication.Page1.onCreate(Page1.java:15)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

为什么应用程序在加载Page1时会关闭?我认为问题出在“String dato1 = getIntent()。getExtras()。getString(”NomeDati1“);”但我不明白原因。主要活动工作,但当进入Page1.java时,应用程序将关闭。请帮我。感谢

这是MainActivity.java的代码:

package com.example.giacomob.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ReadXMLFile.readXMLFile(this);
        Button b_load=(Button)findViewById(R.id.button_send);
        b_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent openPage1 = new Intent(MainActivity.this, Page1.class);
                startActivity(openPage1);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

好的,让我们一步一步检查代码。

首先,您需要将代码拆分为更小的部分。

//String dato1 = getIntent().getExtras().getString("NomeDati1");

Intent intent = getIntent(); // Point 1
Bundle bundle = intent.getExtras(); // Point 2
String dato1 = bundle.getString("NomeDati1"); // Point 3

并再次运行。您可以获得实际的错误消息。

第3点:可能的错误点。这意味着,您没有正确设置数据。

你需要再次测试,让我展示你的结果。

修改

我修改了你的ReadXMLFile.java以返回字符串。 看来,这个xml有多个数据和for循环,但在这段代码中,只需读取一次字符串而不传递。这里的意图是局部变量,因此在运行代码后它将消失。

因此,我添加了StringBuilder来累积字符串,并返回累积的字符串。你可以修改代码&#34; testo1&#34;适合你的目的。

<强> ReadXMLFile.java

        /**
     * Created by Giacomo B on 30/07/2015.
     */
    package com.hanamicron.example.hanabee_sdk_servicesample;

    import android.content.Context;
    import android.content.Intent;
    import android.content.res.AssetManager;

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

    import java.io.InputStream;

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

    public class ReadXMLFile {

        public static String readXMLFile(Context context) {

            StringBuilder sb = new StringBuilder();

            try {
                // Log.i("MyActivity", "casa");

                AssetManager assetManager = context.getAssets();
                InputStream is = assetManager.open("infofermata.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(is);

                // String filePath = "assets/infofermata.xml";
                // File fXmlFile = new File(filePath);
                // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                // Document doc = dBuilder.parse(fXmlFile);

                // optional, but recommended
                // read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                doc.getDocumentElement().normalize();

                System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

                NodeList nList = doc.getElementsByTagName("fermata");

                System.out.println("----------------------------");

                for (int temp = 0; temp < nList.getLength(); temp++) {

                    Node nNode = nList.item(temp);

                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    // Log.i("MyActivity", "casa");

                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element eElement = (Element) nNode;

                        // System.out.println("Staff id : " + eElement.getAttribute("id"));

                        // String stringidfermata = "Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent()"";

                        // Log.i("MyActivity", "\"Id Fermata : \" + eElement.getElementsByTagName(\"idfermata\").item(0).getTextContent()");
                        System.out.println("Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent());
                        String testo1 = eElement.getElementsByTagName("idfermata").item(0).getTextContent();
                        System.out.println(testo1); // provo per vedere se stampa quello che ho messo nella variabile "testo1"

                        sb.append(testo1);

                        //Intent nuovaPagina = new Intent(context, Page1.class);
                        //nuovaPagina.putExtra("NomeDati1", testo1);
                        // I would to switch string called testo1 in Page1

                        System.out.println("Naziome : " + eElement.getElementsByTagName("nazione").item(0).getTextContent());
                        System.out.println("Paese : " + eElement.getElementsByTagName("paese").item(0).getTextContent());
                        System.out.println("Via : " + eElement.getElementsByTagName("via").item(0).getTextContent());


                        String testo2 = eElement.getElementsByTagName("nazione").item(0).getTextContent();
                        String testo3 = eElement.getElementsByTagName("paese").item(0).getTextContent();
                        String testo4 = eElement.getElementsByTagName("via").item(0).getTextContent();

                        sb.append(testo2);
                        sb.append(testo3);
                        sb.append(testo4);


                    }

                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();

            }


            return sb.toString();

        }

    }

然后,将数据置于意图之中。问题是,你没有发送名为&#34; NomeDati1&#34;的数据。

<强> MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //ReadXMLFile.readXMLFile(this);
    Button b_load=(Button)findViewById(R.id.button_send);
    b_load.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            String data1 = ReadXMLFile.readXMLFile(MainActivity.this); // read data from xml
            Intent openPage1 = new Intent(MainActivity.this, Page1.class);

            openPage1.putExtra("NomeDati1", data1); // put data to intent

            startActivity(openPage1);
        }
    });
}