2015-04-23 69 views
0

這是我的第一個問題,我需要你的幫助,我的代碼中有一個致命錯誤。我試圖從doInBackground方法來獲取Google API的書籍數據來管理它,但try-catch塊給我null。 我在Android的newbi,我不知道如何解決這個問題?請幫我:)Android AsyncTask null錯誤

我的代碼:

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; 
    } 
} 
+4

發表您的logcat –

+0

是什麼'isbn'是越來越設置爲字符串? –

回答

0

我能得到它的工作。看來主要的問題是,你正在創建一個新的Book實例libro,然後在getBook()你回來了this.Book這仍然是null

我也將所有的網絡操作移至getBook()而不是在OtherParse的構造函數中。

您還在String對象上調用toString(),這是多餘的。

我只是做了一個測試用The Hitchikers Guide to the Galaxy,並顯示正確的結果:

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

這裏是工作代碼:

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

    } 
} 

編輯:檢查連接,見this answer

編輯2:解析JSON您的評論,做這樣的事情:

//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")); 
       } 
} 
+0

非常感謝您的快速回答。你的解釋很棒。 –

+0

你知道如何檢查連接是否正常嗎?也許像getResponseCode()== 200 –

+0

對不起,我不知道我必須標記的問題。感謝所有的東西 –