2

I have a problem with Intent. I would like to carry on String of a class called ReadXMLFile.java (that is a Context) in Page1.java. But when Page1.java carry on, the Android emulator warns and close the app! This is the code of 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();

        }

    }


}

I would to switch string called testo1 in Page1. This is Page1.java code:

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

    }

In logcat appears:

 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)

Why the app is closed when it load Page1? I soppose that the problem is in "String dato1 = getIntent().getExtras().getString("NomeDati1");" but I don't understand the reason. The main activity work, but when go in Page1.java, the app is closed. Please, help me. Thanks

This is the code of 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);
    }
}
  • What is your error code? In your Logcat view, you can get the error code and log. – Stanley Ko Aug 06 '15 at 00:10
  • Where are you launching the Activity? startActivity(intent) – Jorgesys Aug 06 '15 at 00:22
  • @Elenasys I launch the Activity when I click on a button placed on the MainActivity. When I launch the main Activity this ReadXMLFile works (it is a DOMparser) and fetch data from a XML file. When I click on this button on the main activity, open Page1 and I would to show data fetched from ReadXMLFile in this new Activity –  Aug 06 '15 at 00:27
  • Do you want to post the other classes? –  Aug 06 '15 at 00:29
  • Show your main activity. Code around the string "NomeDati1". Actual point of calling Page1. And you need to check the data is exist, or fifle path is correct. – Stanley Ko Aug 06 '15 at 00:55
  • @StanleyKou I post the code of my MainActivity.. but I don't esplicited this string "NomeDati1" in main activity, but only in ReadXMLFile –  Aug 06 '15 at 01:17

1 Answers1

0

Ok, let's check the code step by step.

First, you need to split your code into smaller pieces.

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

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

and, run again. You can get actual error message.

Point 3: possible error point. This means, you didn't properly set data.

You need to test again, and let me show your result.


Edit

I modified your ReadXMLFile.java to return string. It seems that, this xml has multiple data and for-loop, but in this code, just read string once and do not pass. Intent here is local variable, so it will disappear after run the code.

So, I added StringBuilder to accumulate strings, and return the accumlated strings. You can modifiy code around "testo1" to fit your purpose.

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

        }

    }

And, put data to intent. The problem was, you did not sent data named "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);
        }
    });
}
Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
  • Ok, I put this code in onCreate or outside? –  Aug 06 '15 at 00:41
  • Absolutly, inside. You cannot put the code outside of method. – Stanley Ko Aug 06 '15 at 00:42
  • OK. I read your error code, and you may not edit my answer, but your question. Your next step is: Show your main activity. Actual point of calling Page1. And you need to check the data is exist, or fifle path is correct. – Stanley Ko Aug 06 '15 at 00:51
  • Ah ok, excuse me.. Now I edit my question, adding the MainActivity code. I calling Page1 on the click button's event –  Aug 06 '15 at 00:54
  • Thanks, but there are a problem: String data1 = ReadXMLFile.readXMLFile(this); Error in "this": readXMLFile (android.context.Context) in readXMLFile cannot be applied to (anonymus android.View.onclicklistener) –  Aug 06 '15 at 01:25
  • Ooops, String data1 = ReadXMLFile.readXMLFile( MainActivity.this); is right. I modified code. – Stanley Ko Aug 06 '15 at 01:37
  • Ok, and now, in Page1? I must change this row: String data1 = bundle.getString("NomeDati1"); // Point 3 ? –  Aug 06 '15 at 01:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/85257/discussion-between-giacomo-brunetta-and-stanley-kou). –  Aug 06 '15 at 01:43