URLEncoder用多个单词搜索

时间:2016-11-03 08:40:49

标签: json

以下是图书馆应用。在当前状态下,应用程序只能搜索单个单词。像"哈利波特"没有结果。我被告知要使用URLEncoder,但我尝试过,甚至没有用。以下是我的java文件。'

MainActivity.java

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Books>>, SearchView.OnQueryTextListener {

    LoaderManager loaderManager;
    String mQuery;
    SearchView mSearchView;
    MenuItem mMenuSearchItem;

    private static final String LOG_TAG = MainActivity.class.getName();

    private static final String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?maxResults=40&q=";

    private String url = GOOGLE_REQUEST_URL + "android";

    private static final int BOOK_LOADER_ID = 1;

    private BookAdapter adapter;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

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

        adapter = new BookAdapter(this, new ArrayList<Books>());
        bookListView.setAdapter(adapter);

        loaderManager = getLoaderManager();
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);

        bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Books currentBook = adapter.getItem(position);
                Uri bookUri = Uri.parse(currentBook.getUrl());
                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
                startActivity(websiteIntent);
            }
        });
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if(isOnline()){
            url = GOOGLE_REQUEST_URL + query;
            loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
        }else{
            Toast.makeText(this, "No Internet Connection Found!", Toast.LENGTH_LONG).show();
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        mQuery = newText;
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        mMenuSearchItem = menu.findItem(R.id.menu_search);

        mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
        if (mSearchView != null) {
            mSearchView.setIconifiedByDefault(false);
            mSearchView.setOnQueryTextListener(this);

            mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean queryTextFocused) {
                    if (!queryTextFocused) {
                        if (TextUtils.isEmpty(mQuery))
                            adapter.clear();
                    }
                }
            });
        }
        return true;
    }

    @Override
    public Loader<List<Books>> onCreateLoader(int i, Bundle bundle) {
        return new BookLoader(this, url);
    }

    @Override
    public void onLoadFinished(Loader<List<Books>> loader, List<Books> books) {
        adapter.clear();
        if (books != null && !books.isEmpty()) {
            adapter.addAll(books);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<Books>> loader) {
        adapter.clear();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

BookUtils.java

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public final class BookUtils {

    private static final String LOG_TAG = BookUtils.class.getSimpleName();

    private BookUtils() {}

    public static List<Books> fetchBookData(String requestUrl) {
        URL url = createUrl(requestUrl);

        String jsonResponse = null;

        try {jsonResponse = makeHttpRequest(url);}
        catch (IOException e) {Log.e(LOG_TAG, "Problem making the HTTP request.", e);}

        List<Books> books = extractFeatureFromJson(jsonResponse);

        return books;
    }

    private static URL createUrl(String stringUrl) {
        URL url = null;

        try {url = new URL(stringUrl);}
        catch (MalformedURLException e) {Log.e(LOG_TAG, "Problem building the URL ", e);}

        return url;
    }

    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        if (url == null) {return jsonResponse;}

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);

            } else {Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());}
        }

        catch (IOException e) {Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);}

        finally {
            if (urlConnection != null) {urlConnection.disconnect();}
            if (inputStream != null) {inputStream.close();}
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    private static List<Books> extractFeatureFromJson(String bookJSON) {

        if (TextUtils.isEmpty(bookJSON)) {return null;}

        List<Books> books = new ArrayList<>();

        try {
            JSONObject jsonResponse = new JSONObject(bookJSON);
            JSONArray booksArray = jsonResponse.getJSONArray("items");

            for (int i = 0; i < booksArray.length(); i++) {
                JSONObject currentBook = booksArray.getJSONObject(i);
                JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
                JSONArray authorsArray = volumeInfo.getJSONArray("authors");
                String title = "", publisher = "", publishedDate = "", language = "", pageCount = "", printType = "", maturityRating = "", authors = "";

                if(volumeInfo.has("title")){
                    language = volumeInfo.getString("language");
                }

                for (int j = 0; j < authorsArray.length(); j++) {
                    if (volumeInfo.has("authors")){
                        authors = authorsArray.getString(j);
                    }
                }

                if(volumeInfo.has("publisher")){
                    publisher = volumeInfo.getString("publisher");
                }


                if(volumeInfo.has("publishedDate")){
                    publishedDate = volumeInfo.getString("publishedDate");
                }

                if(volumeInfo.has("language")){
                    language = volumeInfo.getString("language");
                }

                if(volumeInfo.has("pageCount")){
                    pageCount = volumeInfo.getString("pageCount");
                }

                if(volumeInfo.has("printType")){
                    printType = volumeInfo.getString("printType");
                }

                if(volumeInfo.has("maturityRating")){
                    maturityRating = volumeInfo.getString("maturityRating");
                }

                Books book = new Books(title, authors, publisher, publishedDate, language, pageCount, printType, maturityRating);
                books.add(book);
            }


        }
        catch (JSONException e) {Log.e("QueryUtils", "Problem parsing the book JSON results", e);}
        return books;
    }
}

Books.java

public class Books {
    private String mTitle;
    private String mAuthors;

    private String mPublisher;
    private String mPublishingDate;
    private String mLanguage;

    private String mCount;
    private String mPrintType;
    private String mMaturityRating;

    private String mURL;

    public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
        mTitle = title;
        mAuthors = authors;

        mPublisher = publisher;
        mPublishingDate = publishingDate;
        mLanguage = language;

        mCount = count;
        mPrintType = printType;
        mMaturityRating = maturityRating;
    }

    public String getTitle() {return mTitle;}
    public String getAuthors(){return mAuthors;}

    public String getPublisher(){return mPublisher;}
    public String getPublishedDate(){return mPublishingDate;}
    public String getLanguage(){return mLanguage;}

    public String getCount(){return mCount;}
    public String getPrintType(){return mPrintType;}
    public String getMaturityRating(){return mMaturityRating;}

    public String getUrl() {return mURL;}
}

BookLoader.java

import android.content.AsyncTaskLoader;
import android.content.Context;

import java.util.List;

public class BookLoader extends AsyncTaskLoader<List<Books>> {
    private static final String LOG_TAG = BookLoader.class.getName();

    private String mUrl;

    public BookLoader(Context context, String url) {
        super(context);
        mUrl = url;
    }

    @Override
    protected void onStartLoading() {forceLoad();}

    @Override
    public List<Books> loadInBackground() {
        if (mUrl == null) {return null;}

        List<Books> books = BookUtils.fetchBookData(mUrl);
        return books;
    }
}

BookAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


public class BookAdapter extends ArrayAdapter<Books> {

    public BookAdapter(Context context, List<Books> books) {
        super(context, 0, books);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);}

        Books currentBook = getItem(position);

        TextView title = (TextView) listItemView.findViewById(R.id.book_title);
        title.setText(currentBook.getTitle());

        TextView authors = (TextView) listItemView.findViewById(R.id.book_author);
        authors.setText(currentBook.getAuthors());

        TextView publisher = (TextView) listItemView.findViewById(R.id.book_publisher);
        publisher.setText(currentBook.getPublisher());

        TextView publishingDate = (TextView) listItemView.findViewById(R.id.book_publishing_date);
        publishingDate.setText(currentBook.getPublishedDate());

        TextView language = (TextView) listItemView.findViewById(R.id.book_language);
        language.setText(currentBook.getLanguage());

        TextView pageCount = (TextView) listItemView.findViewById(R.id.book_page_count);
        pageCount.setText(currentBook.getCount());

        TextView printType = (TextView) listItemView.findViewById(R.id.book_print_type);
        printType.setText(currentBook.getPrintType());

        TextView maturityRating = (TextView) listItemView.findViewById(R.id.book_maturity_rating);
        maturityRating.setText(currentBook.getMaturityRating());

        return listItemView;
    }
}

在我的onQueryTextSubmit方法中,我尝试将url = GOOGLE_REQUEST_URL + query;替换为:

Uri.Builder uriBuilder = Uri.parse(GOOGLE_REQUEST_URL).buildUpon().appendQueryParameter("q", query);
url = uriBuilder.toString();

但它没有用。

0 个答案:

没有答案