Android Студия Поиск книг Google API - PullRequest
0 голосов
/ 27 марта 2020

OK. Это приложение Android (Java) выполняет поиск в Google App API и отображает книги в виде списка. Он использует специальный адаптер и загрузчик Asyn c. У меня есть скелет работающего приложения, но только один поиск. После этого все просто остается на экране, и новый поиск не происходит или, кажется, не происходит.

Я работал с MainActivity при создании, но затем переместил его в кнопку и EditText.

Я думаю, что проблема в основном здесь, в этом файле.

Если бы кто-то мог помочь, было бы здорово! Посмотрите на последний раздел под нажатием кнопки goQuery. Спасибо.

publi c класс MainActivity расширяет AppCompatActivity реализует LoaderCallbacks> {private stati c final String LOG_TAG = MainActivity.class.getName (); private String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=10"; / ** * Постоянное значение для идентификатора загрузчика книг. Мы можем выбрать любое целое число. * Это действительно вступает в игру, только если вы используете несколько загрузчиков. * / private stati c final int BOOK_LOADER_ID = 1;

/** Adapter for the list of books */
private BookWormAdapter mAdapter;

/** TextView that is displayed when the list is empty */
private TextView mEmptyStateTextView;

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


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

    mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
    bookwormListView.setEmptyView(mEmptyStateTextView);

    // Create a new adapter that takes an empty list of books as input
    mAdapter = new BookWormAdapter(this, new ArrayList<Book>());

    // Set the adapter on the {@link ListView}
    // so the list can be populated in the user interface
    bookwormListView.setAdapter(mAdapter);
    /// End Button search

    // Set an item click listener on the ListView, which sends an intent to a web browser
    // to open a website with more information about the selected book.
    bookwormListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Find the current book that was clicked on
            Book currentBook = mAdapter.getItem(position);

            // Convert the String URL into a URI object (to pass into the Intent constructor)
            Uri bookwormUri = Uri.parse(currentBook.getPreviewLink());

            // Create a new intent to view the book URI
            Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookwormUri);

            // Send the intent to launch a new activity
            startActivity(websiteIntent);
        }
    });

    View loadingIndicator = findViewById(R.id.loading_indicator);
    loadingIndicator.setVisibility(View.GONE);
}


@Override
public Loader<List<Book>> onCreateLoader(int i, Bundle bundle) {
    // Create a new loader for the given URL
    //Log.i(LOG_TAG, "onCreateLoader: TEST Created Loader!");
    return new BookWormLoader(this, GOOGLE_REQUEST_URL);
}



@Override
public void onLoadFinished(Loader<List<Book>> loader, List<Book> bookworms) {
    // Hide loading indicator because the data has been loaded
    View loadingIndicator = findViewById(R.id.loading_indicator);
    loadingIndicator.setVisibility(View.GONE);
    //  Log.i(LOG_TAG, "onLoadFinished: On Load finished!");
    // Set empty state text to display "No books found."
    mEmptyStateTextView.setText(R.string.no_books);

    // Clear the adapter of previous book data
    mAdapter.clear();

    // If there is a valid list of {@link Book}s, then add them to the adapter's
    // data set. This will trigger the ListView to update.
    if (bookworms != null && !bookworms.isEmpty()) {
        mAdapter.addAll(bookworms);
        //mAdapter.notifyDataSetChanged();
    }
}

@Override
public void onLoaderReset(Loader<List<Book>> loader) {
    // Loader reset, so we can clear out our existing data.
    mAdapter.clear();
    //  Log.i(LOG_TAG, "onLoaderReset: TEST On Loader Reset!");
}
public void goQuery(View view){
    EditText mySearchTextView = findViewById(R.id.searchEdit);

    `enter code here`if (mySearchTextView.getText().length() < 1) return;

    //mAdapter.clear();
  // mAdapter.notifyDataSetChanged();


    View loadingIndicator = findViewById(R.id.loading_indicator);
    loadingIndicator.setVisibility(View.VISIBLE);

    GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q="+mySearchTextView.getText()+"&maxResults=20";

    // Get a reference to the ConnectivityManager to check state of network connectivity
    ConnectivityManager connMgr = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);

    // Get details on the currently active default data network
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    // If there is a network connection, fetch data
    if (networkInfo != null && networkInfo.isConnected()) {
        // Get a reference to the LoaderManager, in order to interact with loaders.
        android.app.LoaderManager loaderManager = getLoaderManager();

// Инициализировать загрузчик. Передайте константу int ID, определенную выше, и передайте null для // пакета. Передайте это действие для параметра LoaderCallbacks (который действителен //, потому что это действие реализует интерфейс LoaderCallbacks). loaderManager.initLoader (BOOK_LOADER_ID, null, this); } else {// В противном случае отображаем ошибку

1 Ответ

0 голосов
/ 27 марта 2020

Я добавил это к кнопке, и теперь оно работает. Не знаете, действительно ли это кошерный?

loaderManager.destroyLoader (BOOK_LOADER_ID); mAdapter.clear (); mAdapter.notifyDataSetChanged () enter code here;

...