[英]Android AsyncTask null error
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
. 我正在尝试使用
doInBackground
方法来从Google API获取图书数据,但是try-catch块给了我null
。 I'm newbi in Android and I don't know how to solve this problem... please help me out :) 我是Android的新手,不知道如何解决此问题...请帮帮我:)
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;
}
}
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
. 似乎主要的问题是您正在创建一个新的
Book
实例libro
,然后在getBook()
中返回this.Book
仍然为null
。
I also moved all of your network operations to getBook()
instead of in the constructor of OtherParse
. 我还将所有网络操作都移到了
getBook()
而不是在OtherParse
的构造函数中。
You were also calling toString()
on String objects, which is redundant. 您还在String对象上调用
toString()
,这是多余的。
I just did a test with The Hitchikers Guide to the Galaxy
, and it displayed the correct results: 我刚刚用《
The Hitchikers Guide to the Galaxy
了测试,它显示了正确的结果:
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: 编辑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"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.