当前位置: 首页 > 知识库问答 >
问题:

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

步胜
2023-03-14

我对 Intent 有疑问。我想在Page1.java中继续一个名为ReadXMLFile.java(即上下文)的类的字符串。但是,当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个答案

董昕
2023-03-14

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

首先,你需要把你的代码分成更小的部分。

//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来累加字符串,并返回累加的字符串。您可以修改“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://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();

        }

    }

而且,将数据变为目的。问题是,您没有发送名为“NomeDati1”的数据。

主要活动.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);
        }
    });
}
 类似资料:
  • 问题内容: 关于这两个上下文的内容,已经有很多文章了。但是我仍然不太正确。 到目前为止,据我了解:每个实例都是其类的一个实例,这意味着某些程序员建议您尽可能频繁地使用它,以免“泄漏”任何内存。这是因为另一个this(获取Activity实例上下文)指向的Activity是每次用户倾斜手机或离开应用程序等时都将销毁的一个。显然,垃圾收集器(GC)无法捕获,因此使用了过多的内存。 .. 但是任何人都可

  • 我可以通过firebase FCM打开活动,但这只适用于android

  • 当用户按下注册按钮并将值传递给HomeActivity.java时,我试图从数据库(在LoginActivity.java上创建)传递变量。在我使用意图附加和捆绑之前,代码工作正常(除了传递变量)。但是当我把新代码,应用程序崩溃后,立即我按下注册按钮 我试图寻找另一个可能的重复问题,但没有一个问题与我的问题相同。他们中的大多数人忘了把活动放在android清单上,但我把LoginActivity放

  • 是上面的代码少了点什么,还是有什么其他的方式可以在所有android版本上工作? 请建议。多谢了。

  • 我做了一个jsf应用程序。这个应用程序有一个包含开始、停止按钮的菜单。当按下开始时,应用程序开始从网站获取数据,并更新其数据库。应用程序还有更新过程的进度条。但是,这个过程需要很长时间才能完成。我希望当我关闭浏览器时,它应该继续更新数据库。此外,当我再次打开它时,我应该得到以前的状态。然而,这并没有发生。当我关闭浏览器时,应用程序也关闭了。我该怎么办? 谢谢。