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

Posted

技术标签:

【中文标题】Android:调用 Activity 时应用程序关闭。意图,上下文,字符串[重复]【英文标题】:Android: The app is closed when an Activity is called. Intent, context, string [duplicate] 【发布时间】:2015-10-28 22:48:30 【问题描述】:

我的 Intent 有问题。我想在Page1.java 中进行一个名为ReadXMLFile.java 的类的String(即一个Context)。但是当 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://***.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 ComponentInfocom.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)

为什么应用在加载第 1 页时会关闭?我认为问题出在“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);
    

【问题讨论】:

您的错误代码是什么?在您的 Logcat 视图中,您可以获得错误代码和日志。 您在哪里启动活动?开始活动(意图) @Elenasys 当我单击 MainActivity 上的按钮时,我启动了 Activity。当我启动主活动时,这个 ReadXMLFile 工作(它是一个 DOMparser)并从 XML 文件中获取数据。当我在主活动上单击此按钮时,打开 Page1,我将在此新活动中显示从 ReadXMLFile 获取的数据 您要发布其他课程吗? 显示您的主要活动。围绕字符串“NomeDati1”编写代码。调用Page1的实际点。并且需要检查数据是否存在,或者文件路径是否正确。 【参考方案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循环,但是在这段代码中,只读取一次字符串并且不通过。这里的intent是局部变量,运行代码后会消失。

所以,我添加了 StringBuilder 来累积字符串,并返回累积的字符串。您可以修改“testo1”周围的代码以适应您的目的。

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://***.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();

        

    

并且,将数据置于意图之中。问题是,您没有发送名为“NomeDati1”的数据。

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

【讨论】:

好的,我把这段代码放在onCreate里面还是外面? 绝对,在里面。您不能将代码放在方法之外。 好的。我阅读了您的错误代码,您可能不会编辑我的答案,而是您的问题。您的下一步是:展示您的主要活动。调用Page1的实际点。并且需要检查数据是否存在,或者文件路径是否正确。 好吧,对不起.. 现在我编辑我的问题,添加 MainActivity 代码。我在点击按钮的事件上调用 Page1 谢谢,但是有一个问题:String data1 = ReadXMLFile.readXMLFile(this); “this”中的错误:readXMLFile 中的 readXMLFile (android.context.Context) 无法应用于 (anonymus android.View.onclicklistener)

以上是关于Android:调用 Activity 时应用程序关闭。意图,上下文,字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android service与activity绑定调用问题

在Android N多窗口模式下按下主页按钮时未调用Activity onStop()

如何在 Android 上的活动之间传递值?

android 应用调用另外一个应用的activity

从 asyncTask doInBackground 调用 Activity

Android 在程序运行时,有若干个activity,怎么在退出这个Activity是,释放掉它所占用的运行空间