Synchronization problem

1

This code worked in a Java IDE, but now Android is not working.

This program needs to get an XML dataset from a website and then move to a spinner.

import android.app.Activity;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MainActivity extends Activity {

    private Spinner spinner, spinner2;
    private Button botaoProcurar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // addItemsOnSpinner2();
        addListenerOnSpinnerItemSelection();
        addListenerOnButton();
        new HttpTask().execute("http://services.explorecalifornia.org/rss/tours.php",null,"a");
        // Send HTTP request
        Toast.makeText(this, "Send", Toast.LENGTH_LONG).show();
        // Toast a message

    }


    private class HttpTask extends AsyncTask<String, Void, String> {

        protected String doInBackground(String... strURLs) {
            URL url = null;
            HttpURLConnection conn = null;

            try {
                InputStream stream = url.openStream();

                BufferedInputStream buf = new BufferedInputStream(stream);
                StringBuilder sb = new StringBuilder();

                while (true) {
                    int data = buf.read();

                    // pega a int e converte em char
                    if (data == -1) {
                        // chegou no final do arquivo
                        break;

                    } else
                        sb.append((char) data);
                }

                url = new URL(strURLs[0]);
                conn = (HttpURLConnection) url.openConnection();

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {  // 200
                    return "OK (" + responseCode + ")";
                } else {
                    return "Fail (" + responseCode + ")";
                }

            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "a";
        }

    }


        public void addItemsOnSpinner2() {

            spinner2 = (Spinner) findViewById(R.id.spinner2);
            List<String> list = new ArrayList<String>();
            list.add("list1");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner2.setAdapter(dataAdapter);

            try {
                URL url = new URL("http://services.explorecalifornia.org/rss/tours.php");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                //InputStream stream = url.openStream();
                // BufferedInputStream buf = new BufferedInputStream(stream);

                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                StringBuilder sb = new StringBuilder();

                while (true) {
                    int data = in.read();

                    // pega a int e converte em char
                    if (data == -1) {
                        // chegou no final do arquivo
                        break;

                    }
                    else System.out.println("alo");
                    //sb.append((char) data);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        public void addListenerOnSpinnerItemSelection() {
            spinner = (Spinner) findViewById(R.id.spinner);
            spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());

        }

        public void addListenerOnButton() {

            spinner = (Spinner) findViewById(R.id.spinner);
            spinner2 = (Spinner) findViewById(R.id.spinner2);
            botaoProcurar = (Button) findViewById(R.id.botaoProcurar);

            botaoProcurar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(MainActivity.this,
                            "OnClickListener : " +
                                    "\nSpinner : " + String.valueOf(spinner.getSelectedItem()) +
                                    "\nSpinner 2 :  " + String.valueOf(spinner2.getSelectedItem()),
                            Toast.LENGTH_SHORT
                    ).show();

                }
            });

        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.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();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

This code should take the data from the page and then convert it to String and play in Spinner, that is, if it takes for example the words: water, coffee and balloon, it will play all of them in the spinner.

The error you give is this:

Process: z.me.studiolayoutvrguia.app, PID: 1240
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
 Caused by: java.lang.NullPointerException
        at z.me.studiolayoutvrguia.app.MainActivity$HttpTask.doInBackground(MainActivity.java:69)
        at z.me.studiolayoutvrguia.app.MainActivity$HttpTask.doInBackground(MainActivity.java:62)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
    
asked by anonymous 01.07.2014 / 03:26

1 answer

1

Dude, you set the url to null and then tried to call openStream (). See:

URL url = null; // Aqui está nulo
HttpURLConnection conn = null;
try {
    InputStream stream = url.openStream(); // Aqui você chama o método de null
    BufferedInputStream buf = new BufferedInputStream(stream);

Result: java.lang.NullPointerException

Correct there, to see the result!

    
04.07.2014 / 14:17