Android AsyncTask 空错误
Android AsyncTask null error
这是我的第一个问题,我需要你的帮助,我的代码中有一个致命错误。我试图使用 doInBackground
方法从 google API 获取书籍数据来管理它,但是 try-catch 块给了我 null
。
我是 Android 的新手,我不知道如何解决这个问题...请帮帮我 :)
我的代码:
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;
}
}
我能够让它工作。似乎主要问题是您创建了一个新的 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"));
}
}
这是我的第一个问题,我需要你的帮助,我的代码中有一个致命错误。我试图使用 doInBackground
方法从 google API 获取书籍数据来管理它,但是 try-catch 块给了我 null
。
我是 Android 的新手,我不知道如何解决这个问题...请帮帮我 :)
我的代码:
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;
}
}
我能够让它工作。似乎主要问题是您创建了一个新的 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"));
}
}