Ошибка синтаксического анализа JSON с Android Я получаю нулевое значение вместо правильных данных

Предполагается, что это приложение будет анализировать некоторые данные JSON (пока жестко заданные) из API Google Книг и передавать ArrayList of Books адаптеру, который отобразит их в ListView. У меня проблема в том, что анализ JSON возвращает ноль вместо проанализированных данных. Я не знаю, где именно проблема, но я подозреваю, что это должно быть либо в классе HTTPManager, либо в классе BookJSONParser. Я включу весь код на всякий случай. Я ценю любую помощь Спасибо!

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

ProgressBar pBar;
List<MyTask> tasks;

ArrayList<Book> bookList;

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

    pBar = (ProgressBar) findViewById(R.id.progressBar);
    pBar.setVisibility(View.INVISIBLE);

    Button sButton = (Button) findViewById(R.id.s_button);
    sButton.setOnClickListener(this);

    tasks = new ArrayList<>();

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.s_button: {
            if (isOnline()) {
                new MyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills

            } else {
                Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
            }
            break;
        }
    }
}

protected boolean isOnline() {

    ConnectivityManager connectManager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = connectManager.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}

protected void updateDisplay(ArrayList<Book> showBooklist) {
    bookList = showBooklist;

    if (bookList != null) {
        BookAdapter adapter = new BookAdapter(this, bookList);

        ListView listView = (ListView) findViewById(R.id.list);

        listView.setAdapter(adapter);
    } else {
        Toast.makeText(this, "No content", Toast.LENGTH_LONG).show();
    }

}

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return HttpManager.getData(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        bookList = BookJSONParser.parseFeed(result);
        updateDisplay(bookList);
    }

}

}

public class HttpManager {

public static String getData(String myUrl) throws IOException {

    InputStream inputStream = null;

    int len = 10000;

    try {
        URL url = new URL(myUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        // Starts the query
        connection.connect();

        inputStream = connection.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(inputStream, len);
        return contentAsString;

        // Makes sure that the InputStream inputStream closed after the app inputStream
        // finished using it.
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

        }
    }
}

// Reads an InputStream and converts it to a String.
public static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}
}

public class BookJSONParser {

public static ArrayList<Book> parseFeed(String content) {

    ArrayList<Book> bookList = new ArrayList<>();

    try {
        JSONArray jsonArray = new JSONArray(content);

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject object = jsonArray.getJSONObject(i);

            String name = object.getString("title").toString();

            Book book = new Book(name);
            bookList.add(book);

        }
        return bookList;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

}
}

public class BookAdapter extends ArrayAdapter<Book> {

public BookAdapter(Context context, ArrayList<Book> bookList) {
    super(context, 0, bookList);

}

@Override
public View getView(int position, View convertedView, ViewGroup parent) {

    View listItemView = convertedView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }

    Book currentBook = getItem(position);

    TextView locationName = (TextView) listItemView.findViewById(R.id.book_title);

    locationName.setText(currentBook.getTittle());

    return listItemView;

}
}

public class Book {

private String mTittle;

/**
 * This is the constructor.
 * @param title is the book title being passed in.
 */
public Book(String title) {
    mTittle = title;

}

public String getTittle() {
    return mTittle;
}

public void setTittle(String tittle) {
    mTittle = tittle;
}

}

0 ответов

Другие вопросы по тегам