0

This is my first question and I need your help, there is a Fatal Error in my code. I´m trying to get a book data from google API using the doInBackground method to manage it but the try-catch block is giving me null. I'm newbi in Android and I don't know how to solve this problem... please help me out :)

My code:

    public class FrmSaludo extends Activity {
    private String isbn;
    private Book libro;
    private TextView txtSaludo;
    private Book resultado;

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

        // Localizar los controles
        txtSaludo = (TextView) findViewById(R.id.TxtSaludo);

        // Recuperamos la información pasada en el intent
        Bundle bundle = this.getIntent().getExtras();
        this.isbn = bundle.getString("ISBN");

        Buscar();


        /*
         * OtherParse otherparse= new OtherParse(isbn);
         * txtSaludo.setText("Hola " + otherparse.getResult());
         */
    }

    private class SearchIsbnTask extends AsyncTask<String, Integer, Boolean> {


        @Override
        protected Boolean doInBackground(String... params) {
            /*
             * ParseJson parse= new ParseJson(params[0]); libro = parse.Parse();
             */
            try{
            OtherParse otherParse = new OtherParse(params[0]);
            resultado = otherParse.getBook();
            Log.v("TEST", "book ="+resultado.toString());
            }catch (Exception e){

                Log.e("BACKGROUND", "Error ejecutando hilo" + e.getMessage());

            }
            return true;

        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Log.v("TEST", "volviendo a hilo principal");

            if (result) {
                txtSaludo.setText("Hola " + resultado.getTitle().toString());
            }

        }

    }

    public void Buscar() {

        // Carga del XML mediante la tarea asíncrona
        SearchIsbnTask tarea = new SearchIsbnTask();

        tarea.execute(isbn);
    }
}


    public class OtherParse {

    private String url;
    private JSONObject jsonObject;
    private String author;
    private Book book;
    public OtherParse(String isbn) {
        HttpClient client = new DefaultHttpClient();
        String ruta = "https://www.googleapis.com/books/v1/volumes?q=isbn:";

        this.url = ruta.concat(isbn);
        HttpGet get = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        System.out.println("Buscando");
        try {
            responseBody = client.execute(get, responseHandler);
        } catch (Exception ex) {
            Log.v("RESPONSEBODY", "Exception: " + ex.getMessage());
        }
         this.jsonObject = null;

        try {
            this.jsonObject = new JSONObject(responseBody);
            System.out.println("JSONRESPONSE =" + this.jsonObject);

        } catch (Exception e) {
            Log.v("TEST", "Exception: " + e.getMessage());
        }
        Book libro = new Book();
        JSONArray jArray;
        try {
            jArray = jsonObject.getJSONArray("items");

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject volumeInfo = jArray.getJSONObject(i).getJSONObject(
                        "volumeInfo");
                libro.setTitle(volumeInfo.getString("title"));

                JSONArray authors = volumeInfo.getJSONArray("authors");
                for (int j = 0; j < authors.length(); j++) {
                    this.author = authors.getString(i);
                }
                libro.setAuthors(author);
            }
            System.out.println("TITULO=" + libro.getTitle().toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    JSONObject getResult(){
        return this.jsonObject;

    }
    Book getBook(){
        return this.book;
    }
}
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
aries_93
  • 5
  • 2

1 Answers1

0

I was able to get it working. It seems that the main problem was that you were creating a new Book instance libro, and then in getBook() you were returning this.Book which was still null.

I also moved all of your network operations to getBook() instead of in the constructor of OtherParse.

You were also calling toString() on String objects, which is redundant.

I just did a test with The Hitchikers Guide to the Galaxy, and it displayed the correct results:

 author =Douglas Adams
 TITULO=The Hitchhiker's Guide to the Galaxy

Here is the working code:

public class FrmSaludo extends Activity {
    private String isbn;
    private OtherParse.Book libro;
    public TextView txtSaludo;
    private OtherParse.Book resultado;

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

        // Localizar los controles
        txtSaludo = (TextView) findViewById(R.id.TxtSaludo);

        // Recuperamos la información pasada en el intent
        //Bundle bundle = this.getIntent().getExtras();
        //this.isbn = bundle.getString("ISBN");
        this.isbn = "0345391802";

        Buscar();


        /*
         * OtherParse otherparse= new OtherParse(isbn);
         * txtSaludo.setText("Hola " + otherparse.getResult());
         */
    }

    private class SearchIsbnTask extends AsyncTask<String, Integer, Boolean> {


        @Override
        protected Boolean doInBackground(String... params) {
            /*
             * ParseJson parse= new ParseJson(params[0]); libro = parse.Parse();
             */
            try{
                OtherParse otherParse = new OtherParse(params[0]);
                resultado = otherParse.getBook();
                Log.v("TEST", "book ="+resultado.toString());
            }catch (Exception e){

                Log.e("BACKGROUND", "Error ejecutando hilo" + e);

            }
            return true;

        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Log.v("TEST", "volviendo a hilo principal");

            if (result) {
                txtSaludo.setText("Hola " + resultado.getTitle() + " author: " + resultado.getAuthors());
            }

        }

    }

    public void Buscar() {

        // Carga del XML mediante la tarea asíncrona
        SearchIsbnTask tarea = new SearchIsbnTask();

        tarea.execute(isbn);
    }
}


   class OtherParse {

    private String url;
    private JSONObject jsonObject;
    private String author;
    private Book book;
    public OtherParse(String isbn) {

        book = new Book(); //initialize book here

        String ruta = "https://www.googleapis.com/books/v1/volumes?q=isbn:";

        this.url = ruta.concat(isbn);

    }

    JSONObject getResult(){
        return this.jsonObject;

    }
    Book getBook(){
        //do all of the network operations in getBook instead of the constructor
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        System.out.println("Buscando");
        try {
            responseBody = client.execute(get, responseHandler);
        } catch (Exception ex) {
            Log.v("RESPONSEBODY", "Exception: " + ex.getMessage());
        }
        this.jsonObject = null;

        try {
            this.jsonObject = new JSONObject(responseBody);
            System.out.println("JSONRESPONSE =" + this.jsonObject);

        } catch (Exception e) {
            Log.v("TEST", "Exception: " + e.getMessage());
        }
        //Book libro = new Book(); //no need to create a new book here

        JSONArray jArray;
        try {
            jArray = jsonObject.getJSONArray("items");

            System.out.println("JSONARRAY length =" + jArray.length());

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject volumeInfo = jArray.getJSONObject(i).getJSONObject(
                        "volumeInfo");
                book.setTitle(volumeInfo.getString("title"));

                JSONArray authors = volumeInfo.getJSONArray("authors");
                for (int j = 0; j < authors.length(); j++) {
                    this.author = authors.getString(i);
                }
                book.setAuthors(author);

                System.out.println("author =" + author);
            }
            System.out.println("TITULO=" + book.getTitle());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return this.book;
    }

    public class Book{
        String title;
        String authors;

        public void setAuthors(String a){
            authors = a;
        }

        public void setTitle(String t){
            title = t;
        }

        public String getTitle(){
           return title;
        }

        public String getAuthors(){
            return authors;
        }

    }
}

Edit: to check for connectivity, see this answer.

Edit 2: To parse the JSON in your comment, do something like this:

//first get industryIdentifiers array
for (int i = 0; i < jIdentifiersArray.length(); i++) {
                JSONObject identifier = jIdentifiersArray.getJSONObject(i);
                String type = identifier.getString("type");
                if (type.equals("ISBN_10")){
                   book.setISBN10(identifier.getString("identifier"));
                }
                else if (type.equals("ISBN_13")){
                   book.setISBN13(identifier.getString("identifier"));
                }
}
Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • Thank you so much for your quick answer. Your explanation is awesome. – aries_93 Apr 24 '15 at 13:58
  • do you know how to check if the connection is ok? maybe something like getResponseCode() == 200 – aries_93 Apr 24 '15 at 13:59
  • sorry i didn't know i have to mark the question.thanks for everything – aries_93 Apr 24 '15 at 14:36
  • Any idea about how to parse the part ?? I want to get the isbn 10 and 13 I tried with JsonArray but i cant get it working "industryIdentifiers": [ { "type": "ISBN_10", "identifier": "8499082971" }, { "type": "ISBN_13", "identifier": "9788499082974" } ], – aries_93 Apr 25 '15 at 18:56
  • @aries_93 I just updated the answer, have a look at the bottom. Although in the future, one question at a time! :) – Daniel Nugent Apr 25 '15 at 19:16