вот XML-код поля названия:
Код: Выделить всё
Код: Выделить всё
public class AddBookActivity extends AppCompatActivity {
private ActivityAddBookBinding binding;
private ArrayAdapter bookTitleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityAddBookBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setupBookTitleAutoComplete();
bookTitleAdapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, bookTitles);
AutoCompleteTextView titleAutoCompleteTextView = (AutoCompleteTextView) binding.titleTil.getEditText();
titleAutoCompleteTextView.setAdapter(bookTitleAdapter);
titleAutoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 2) {
Log.d("AddBookActivity", "Text changed, starting fetchBooks");
fetchBooks(s.toString(), binding.languageEt.getText().toString());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
titleAutoCompleteTextView.setOnItemClickListener((adapterView, view, position, id) -> {
String selectedTitle = (String) adapterView.getItemAtPosition(position);
Log.d("AddBookActivity", "Item selected: " + selectedTitle);
fetchBookDetails(selectedTitle, binding.languageEt.getText().toString());
});
}
private void fetchBooks(String query, String language) {
new Thread(() -> {
try {
String apiKey = "mykey";
String baseUrl = "https://www.googleapis.com/books/v1/volumes";
String langRestrict = LANGUAGE_CODES[getLanguageIndex(language)];
String urlStr = baseUrl + "?q=" + URLEncoder.encode(query, "UTF-8") + "&langRestrict=" + langRestrict + "&maxResults=10" + "&key=" + apiKey;
Log.d("AddBookActivity", "Fetching books with URL: " + urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlStr).openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Log.d("AddBookActivity", "Response received: " + response.toString());
runOnUiThread(() -> updateBookSuggestions(response.toString()));
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("AddBookActivity", "Error fetching books", e);
}
}).start();
}
private void fetchBookDetails(String title, String language) {
new Thread(() -> {
try {
String apiKey = "my key";
String baseUrl = "https://www.googleapis.com/books/v1/volumes";
String langRestrict = LANGUAGE_CODES[getLanguageIndex(language)];
String query = title + "+intitle:" + title;
String urlStr = baseUrl + "?q=" + URLEncoder.encode(query, "UTF-8") + "&langRestrict=" + langRestrict + "&maxResults=1" + "&key=" + apiKey;
Log.d("AddBookActivity", "Fetching book details with URL: " + urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlStr).openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Log.d("AddBookActivity", "Detailed response received: " + response.toString());
runOnUiThread(() -> updateBookDetails(response.toString()));
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("AddBookActivity", "Error fetching book details", e);
}
}).start();
}
private void updateBookSuggestions(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray items = jsonObject.getJSONArray("items");
bookTitles.clear();
for (int i = 0; i < Math.min(items.length(), 10); i++) {
JSONObject book = items.getJSONObject(i);
JSONObject volumeInfo = book.getJSONObject("volumeInfo");
bookTitles.add(volumeInfo.getString("title"));
}
bookTitleAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("AddBookActivity", "Failed to parse book data", e);
}
}
private void updateBookSuggestions(String json) {
Log.d("AddBookActivity", "Updating book suggestions with JSON: " + json);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray items = jsonObject.getJSONArray("items");
bookTitles.clear();
if (items.length() == 0) {
Log.d("AddBookActivity", "No items found in JSON response");
} else {
for (int i = 0; i < items.length(); i++) {
JSONObject book = items.getJSONObject(i);
JSONObject volumeInfo = book.getJSONObject("volumeInfo");
String title = volumeInfo.getString("title");
bookTitles.add(title);
Log.d("AddBookActivity", "Added book title: " + title);
}
Log.d("AddBookActivity", "Total books added: " + bookTitles.size());
}
runOnUiThread(() -> {
bookTitleAdapter.notifyDataSetChanged();
AutoCompleteTextView titleAutoCompleteTextView = (AutoCompleteTextView) binding.titleTil.getEditText();
titleAutoCompleteTextView.requestFocus();
if (titleAutoCompleteTextView.getText().length() >= titleAutoCompleteTextView.getThreshold()) {
titleAutoCompleteTextView.showDropDown();
}
});
} catch (Exception e) {
Log.e("AddBookActivity", "Failed to parse book data", e);
}
}
private void loadImageIntoView(String imageUrl) {
Glide.with(this).load(imageUrl).into(binding.coverImageView);
}
private void setupBookTitleAutoComplete() {
bookTitleAdapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, bookTitles);
AutoCompleteTextView titleAutoCompleteTextView = (AutoCompleteTextView) binding.titleTil.getEditText();
titleAutoCompleteTextView.setAdapter(bookTitleAdapter);
titleAutoCompleteTextView.setAccessibilityDelegate(new View.AccessibilityDelegate() {
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(host, info);
info.setText("Enter book title. Suggestions will appear as you type.");
}
});
titleAutoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 2) {
fetchBooks(s.toString(), binding.languageEt.getText().toString());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
Код: Выделить всё
D/AddBookActivity: Response received: { "kind": "books#volumes", "totalItems": 283, "items": [ { "kind": "books#volume", "id": "t_ZYYXZq4RgC", "etag": "O9goLPs+zIw", "selfLink": "https://www.googleapis.com/books/v1/volumes/t_ZYYXZq4RgC", "volumeInfo": { "title": "Mistborn", "subtitle": "The Final Empire", "authors": [ "Brandon Sanderson" ], "publisher": "Macmillan", "publishedDate": "2010-04-01", "description": "Now with over 10 million copies sold, The Mistborn Series has the thrills of a heist story, the twistiness of political intrigue, and the epic scale of a landmark fantasy saga. For a thousand years the ash fell and no flowers bloomed. For a thousand years the Skaa slaved in misery and lived in fear. For a thousand years the Lord Ruler, the \"Sliver of Infinity,\" reigned with absolute power and ultimate terror, divinely invincible. Then, when hope was so long lost that not even its memory remained, a terribly scarred, heart-broken half-Skaa rediscovered it in the depths of the Lord Ruler's most hellish prison. Kelsier \"snapped\" and found in himself the powers of a Mistborn. A brilliant thief and natural leader, he turned his talents to the ultimate caper, with the Lord Ruler himself as the mark. Kelsier recruited the underworld's elite, the smartest and most trustworthy allomancers, each of whom shares one of his many powers, and all of whom relish a high-stakes challenge. Only then does he reveal his ultimate dream, not just the greatest heist in history, but the downfall of the divine despot. But even with the best criminal crew ever assembled, Kel's plan looks more like the ultimate long shot, until luck brings a ragged girl named Vin into his life. Like him, she's a half-Skaa orphan, but she's lived a much harsher life. Vin has learned to expect betrayal from everyone she meets, and gotten it. She will have to learn to trust, if Kel is to help her master powers of which she never dreamed. This saga dares to ask a simple question: What if the hero of prophecy fails? Other Tor books by Brandon Sanderson The Cosmere The Stormlight Archive The Way of Kings Words of Radiance Edgedancer (Novella) Oathbringer The Mistborn trilogy Mistborn: The Final Empire The Well of Ascension The Hero of Ages Mistborn: The Wax and Wayne series Alloy of Law Shadows of Self Bands of Mourning Collection Arcanum Unbounded Other Cosmere novels Elantris Warbreaker The Alcatraz vs. the Evil Librarians series Alcatraz vs. the Evil Librarians The Scrivener's Bones The Knights of Crystallia The Shattered Lens The Dark Talent The Rithmatist series The Rithmatist Other books by Brandon Sanderson The Reckoners Steelheart Firefight Calamity At the Publisher's request, this title is being sold without Digital Rights Management Software (DRM) applied.", "industryIdentifiers": [ { "type": "ISBN_13", "identifier": "9781429914567" }, { "type": "ISBN_10", "identifier": "1429914564" } ], "readingModes": { "text": true, "image": false }, "pageCount": 686, "printType": "BOOK", "categories": [ "Fiction" ], "averageRating": 4.5, "ratingsCount": 78, "maturityRating": "NOT_MATURE", "allowAnonLogging": true, "contentVersion": "14.44.38.0.preview.2", "panelizationSummary": { "containsEpubBubbles": false, "containsImageBubbles": false }, "imageLinks": { "smallThumbnail": "http://books.google.com/books/content?id=t_ZYYXZq4RgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api", "thumbnail": "http://books.google.com/books/content?id=t_ZYYXZq4RgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api" }, "language": "en", "previewLink": "http://books.google.be/books?id=t_ZYYXZq4RgC&pg=PA637&dq=mistbor&hl=&cd=1&source=gbs_api", "infoLink": "https://play.google.
D/AddBookActivity: Updating book suggestions with JSON: { "kind": "books#volumes", "totalItems": 283, "items": [ { "kind": "books#volume", "id": "t_ZYYXZq4RgC", "etag": "O9goLPs+zIw", "selfLink": "https://www.googleapis.com/books/v1/volumes/t_ZYYXZq4RgC", "volumeInfo": { "title": "Mistborn", "subtitle": "The Final Empire", "authors": [ "Brandon Sanderson" ], "publisher": "Macmillan", "publishedDate": "2010-04-01", "description": "Now with over 10 million copies sold, The Mistborn Series has the thrills of a heist story, the twistiness of political intrigue, and the epic scale of a landmark fantasy saga. For a thousand years the ash fell and no flowers bloomed. For a thousand years the Skaa slaved in misery and lived in fear. For a thousand years the Lord Ruler, the \"Sliver of Infinity,\" reigned with absolute power and ultimate terror, divinely invincible. Then, when hope was so long lost that not even its memory remained, a terribly scarred, heart-broken half-Skaa rediscovered it in the depths of the Lord Ruler's most hellish prison. Kelsier \"snapped\" and found in himself the powers of a Mistborn. A brilliant thief and natural leader, he turned his talents to the ultimate caper, with the Lord Ruler himself as the mark. Kelsier recruited the underworld's elite, the smartest and most trustworthy allomancers, each of whom shares one of his many powers, and all of whom relish a high-stakes challenge. Only then does he reveal his ultimate dream, not just the greatest heist in history, but the downfall of the divine despot. But even with the best criminal crew ever assembled, Kel's plan looks more like the ultimate long shot, until luck brings a ragged girl named Vin into his life. Like him, she's a half-Skaa orphan, but she's lived a much harsher life. Vin has learned to expect betrayal from everyone she meets, and gotten it. She will have to learn to trust, if Kel is to help her master powers of which she never dreamed. This saga dares to ask a simple question: What if the hero of prophecy fails? Other Tor books by Brandon Sanderson The Cosmere The Stormlight Archive The Way of Kings Words of Radiance Edgedancer (Novella) Oathbringer The Mistborn trilogy Mistborn: The Final Empire The Well of Ascension The Hero of Ages Mistborn: The Wax and Wayne series Alloy of Law Shadows of Self Bands of Mourning Collection Arcanum Unbounded Other Cosmere novels Elantris Warbreaker The Alcatraz vs. the Evil Librarians series Alcatraz vs. the Evil Librarians The Scrivener's Bones The Knights of Crystallia The Shattered Lens The Dark Talent The Rithmatist series The Rithmatist Other books by Brandon Sanderson The Reckoners Steelheart Firefight Calamity At the Publisher's request, this title is being sold without Digital Rights Management Software (DRM) applied.", "industryIdentifiers": [ { "type": "ISBN_13", "identifier": "9781429914567" }, { "type": "ISBN_10", "identifier": "1429914564" } ], "readingModes": { "text": true, "image": false }, "pageCount": 686, "printType": "BOOK", "categories": [ "Fiction" ], "averageRating": 4.5, "ratingsCount": 78, "maturityRating": "NOT_MATURE", "allowAnonLogging": true, "contentVersion": "14.44.38.0.preview.2", "panelizationSummary": { "containsEpubBubbles": false, "containsImageBubbles": false }, "imageLinks": { "smallThumbnail": "http://books.google.com/books/content?id=t_ZYYXZq4RgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api", "thumbnail": "http://books.google.com/books/content?id=t_ZYYXZq4RgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api" }, "language": "en", "previewLink": "http://books.google.be/books?id=t_ZYYXZq4RgC&pg=PA637&dq=mistbor&hl=&cd=1&source=gbs_api", "infoLink": "ht
D/AddBookActivity: Added book title: Mistborn
D/AddBookActivity: Added book title: The Hero of Ages
D/AddBookActivity: Added book title: A Royal Embarrassment
D/AddBookActivity: Added book title: Warbreaker
D/AddBookActivity: Added book title: Continue Online The Complete Series
D/AddBookActivity: Added book title: Mistborn Trilogy Boxed Set
D/AddBookActivity: Added book title: The Bands of Mourning
D/AddBookActivity: Added book title: Mistborn: Secret History
D/AddBookActivity: Added book title: Study Guide - Misborn
D/AddBookActivity: Added book title: Oathbringer
D/AddBookActivity: Total books added: 10
Подробнее здесь: https://stackoverflow.com/questions/784 ... ing-an-api
Мобильная версия