mp.paschalis.BookSearch.java Source code

Java tutorial

Introduction

Here is the source code for mp.paschalis.BookSearch.java

Source

/*
 This file is part of SmartLib Project.
    
SmartLib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
SmartLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with SmartLib.  If not, see <http://www.gnu.org/licenses/>.
    
   Author: Paschalis Mpeis
    
   Affiliation:
   Data Management Systems Laboratory 
   Dept. of Computer Science 
   University of Cyprus 
   P.O. Box 20537 
   1678 Nicosia, CYPRUS 
   Web: http://dmsl.cs.ucy.ac.cy/
   Email: dmsl@cs.ucy.ac.cy
   Tel: +357-22-892755
   Fax: +357-22-892701
       
    
 */

package mp.paschalis;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

// import mp.paschalis.R;
import com.google.zxing.client.android.PreferencesActivity;

public class BookSearch extends SherlockActivity {

    private static final String TAG = BookSearch.class.getSimpleName();

    LinearLayout linearLayoutSearchLayout;

    EditText editTextSearchKeyword;

    Spinner spinnerColumnSelect;

    Button buttonSearch;

    ProgressBar progressBarSearchButton;

    ListView listViewBookResults;

    TextView textViewSearchResults;

    App app;

    ArrayList<Book> searchResultBooks;

    DataClassSearch dataClassSearch;

    Boolean isItemChecked = false;

    boolean openedEditBook = false;

    /**
     * Whether user is making search or just watching results
     */
    boolean isMakingSearch = true;

    ArrayAdapter<CharSequence> adapterSearchColumns;

    ArrayAdapter<Book> adapterBookResults;

    class DataClassSearch {

        String column;

        String keyword;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_search);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        app = (App) getApplication();

        linearLayoutSearchLayout = (LinearLayout) findViewById(R.id.linearLayoutSearchLayout);
        editTextSearchKeyword = (EditText) findViewById(R.id.editTextSearchKeyword);
        spinnerColumnSelect = (Spinner) findViewById(R.id.spinnerSearchSelectColumn);
        buttonSearch = (Button) findViewById(R.id.buttonSearchBookSearch);
        progressBarSearchButton = (ProgressBar) findViewById(R.id.progressBarSearchSearchButton);
        listViewBookResults = (ListView) findViewById(R.id.listViewBookResults);

        textViewSearchResults = (TextView) findViewById(R.id.textViewSearchSearchResults);

        // Create adapter for the Spinner
        adapterSearchColumns = ArrayAdapter.createFromResource(this, R.array.ArraySearchColumns,
                android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterSearchColumns.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner

        spinnerColumnSelect.setAdapter(adapterSearchColumns);

        isItemChecked = false;

        // When button is pressed
        buttonSearch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                dataClassSearch = new DataClassSearch();
                dataClassSearch.column = getResources().getStringArray(
                        R.array.ArraySearchColumnValues)[spinnerColumnSelect.getSelectedItemPosition()];
                dataClassSearch.keyword = editTextSearchKeyword.getText().toString();

                // Re-init results
                searchResultBooks = new ArrayList<Book>();

                new AsyncTaskBookSearch().execute(dataClassSearch);
            }
        });

        // When results is chosen
        listViewBookResults.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                app.selectedBook = (Book) (listViewBookResults.getItemAtPosition(pos));

                listViewBookResults.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                listViewBookResults.setItemChecked(pos, true);

                isItemChecked = true;

                // REcreate the menu
                invalidateOptionsMenu();

                // linearLayoutSelectedBooks.setVisibility(View.VISIBLE);
                //
                // textViewMyBookSelected.setText(selectedBook.title);

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (openedEditBook) {

            adapterBookResults.clear();
            if (dataClassSearch != null) {
                new AsyncTaskBookSearch().execute(dataClassSearch);
            }

            openedEditBook = false;// restore this value
        }

        isItemChecked = false;

        app.selectedBook = null;

        // Recreate the menu
        invalidateOptionsMenu();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            linearLayoutSearchLayout.setVisibility(View.VISIBLE);
            isMakingSearch = true;
            invalidateOptionsMenu();

            editTextSearchKeyword.setFocusable(true);
            editTextSearchKeyword.requestFocus();

            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(Menu.NONE, App.MENU_MY_BOOKS_BOOK_SELECTED, Menu.FIRST, R.string.editBook).setVisible(false)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        menu.add(Menu.NONE, App.MENU_SEARCH_SEARCH_BOOKS, Menu.FIRST, R.string.search)
                .setIcon(R.drawable.ic_menu_search_holo_light).setVisible(false)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        menu.add(Menu.NONE, App.MENU_GLOBAL_SETTINGS, Menu.NONE, R.string.menu_settings)
                .setIcon(R.drawable.ic_menu_settings_holo_light).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

        menu.add(Menu.NONE, App.MENU_LIBRARY_SETTINGS, Menu.NONE, app.library.name)
                .setIcon(R.drawable.ic_menu_account_list).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case App.MENU_LIBRARY_SETTINGS: {
            Intent myIntent = new Intent(BookSearch.this, LibPreferences.class);
            BookSearch.this.startActivity(myIntent);

        }
            return true;
        case App.MENU_GLOBAL_SETTINGS: {
            Intent myIntent = new Intent(BookSearch.this, PreferencesActivity.class);
            BookSearch.this.startActivity(myIntent);

        }
            return true;

        case App.MENU_SEARCH_SEARCH_BOOKS: {
            linearLayoutSearchLayout.setVisibility(View.VISIBLE);
            isMakingSearch = true;
            invalidateOptionsMenu();

        }
            return true;

        case App.MENU_MY_BOOKS_BOOK_SELECTED: {
            // If user owns that book, open edit book
            if (app.selectedBook.status != App.BOOK_STATE_USER_DONT_OWNS) {
                // Workaround - Change the status of book, to users
                // specific status
                for (Book.DataClassUser u : app.selectedBook.owners) {
                    // Find real status for that book
                    if (u.username.equalsIgnoreCase(app.user.username)) {
                        app.selectedBook.status = u.status;
                        break;
                    }
                }

                Intent intent = new Intent(BookSearch.this, EditBookActivity.class);

                intent.putExtra(App.ExtrasForEditBookActivityFromBookSearch, true);

                openedEditBook = true;

                startActivity(intent);
            } else {
                Boolean isAvail = false;

                // Find all users who lent this book
                for (Book.DataClassUser u : app.selectedBook.owners) {
                    if (u.status == App.BOOK_STATE_USER_AVAILABLE) {
                        isAvail = true;
                    }
                }

                Intent intent = new Intent(BookSearch.this, WatchBookActivity.class);

                intent.putExtra(App.ExtrasForWatchBookActivityFromBookSearch, isAvail);

                startActivity(intent);
            }

        }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        if (isMakingSearch) {
            menu.findItem(App.MENU_SEARCH_SEARCH_BOOKS).setVisible(false);
        } else {
            menu.findItem(App.MENU_SEARCH_SEARCH_BOOKS).setVisible(true);
        }

        // If library is selected, show register option
        if (isItemChecked) {

            if (app.selectedBook.status != App.BOOK_STATE_USER_DONT_OWNS) {
                menu.findItem(App.MENU_MY_BOOKS_BOOK_SELECTED).setVisible(true)
                        .setTitle(getString(R.string.edit) + ": " + app.selectedBook.title);
            } else {

                menu.findItem(App.MENU_MY_BOOKS_BOOK_SELECTED).setVisible(true)
                        .setTitle(getString(R.string.view) + ": " + app.selectedBook.title);

            }

        } else {
            menu.findItem(App.MENU_MY_BOOKS_BOOK_SELECTED).setVisible(false);

        }

        return true;
    }

    /**
     * Get Search Results
     *
     * @author paschalis
     */
    private class AsyncTaskBookSearch extends AsyncTask<DataClassSearch, Integer, JSONArray> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Disable Search Pane
            linearLayoutSearchLayout.setEnabled(false);
            buttonSearch.setVisibility(View.GONE);
            progressBarSearchButton.setVisibility(View.VISIBLE);

        }

        @Override
        protected JSONArray doInBackground(DataClassSearch... data) {

            JSONArray result = null;

            // int returnResult = App.GENERAL_NO_INTERNET;

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // Say that we are mobile (Android Device)
            parameters.add(new BasicNameValuePair("device", App.DEVICE_ANDROID));

            // Set Username
            parameters.add(new BasicNameValuePair("username", app.getUsername()));

            // If user also selected a column
            if (data[0].column != "") {
                parameters.add(new BasicNameValuePair("column", data[0].column));
            }

            parameters.add(new BasicNameValuePair("keyword", data[0].keyword));

            // Execute PHP Script
            String resultStr = App.executePHPScript(app.getLibrary_getSearch_URL(), parameters);

            // Parse Result (JSON Obj)
            if (resultStr != null) {
                try {
                    // Create JSON Obj based on the result!
                    result = new JSONArray(resultStr);

                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing data " + e.toString());

                }

            }

            return result;

        }

        @Override
        protected void onPostExecute(JSONArray result) {

            linearLayoutSearchLayout.setEnabled(true);
            buttonSearch.setVisibility(View.VISIBLE);
            progressBarSearchButton.setVisibility(View.GONE);

            int returnFromJson = App.GENERAL_NO_INTERNET;

            try {
                returnFromJson = result.getJSONObject(0).getInt("result");

            } catch (Exception e1) {

                returnFromJson = App.BOOKS_OF_USER_NO_BOOKS;
            }

            switch (returnFromJson) {
            case App.GENERAL_SUCCESSFULL:
                // Hide search pane & show results
                linearLayoutSearchLayout.setVisibility(View.GONE);
                textViewSearchResults.setVisibility(View.VISIBLE);

                // Is viewing results now!
                isMakingSearch = false;
                invalidateOptionsMenu();

                // Save all books to array

                try {

                    textViewSearchResults.setText(
                            getString(R.string.results) + " (" + result.getJSONObject(0).getInt("booksNum") + ")");

                } catch (Exception e) {

                }

                for (int i = 1; i < result.length(); i++) {

                    try {

                        JSONObject row;

                        Book book = new Book();

                        row = result.getJSONObject(i);

                        String isbn = row.getString("isbn");
                        String username = row.getString("username");
                        int bookStatus = row.getInt("status");

                        Book bookExistance = bookExists(isbn);

                        // Get the use and its book status info
                        Book.DataClassUser dataClassUser = new Book.DataClassUser(username, bookStatus);

                        // Check if book already exists
                        if (bookExistance != null) {

                            // Add only new owner
                            bookExistance.owners.add(dataClassUser);

                            // User Owns that book
                            if (dataClassUser.username.equalsIgnoreCase(app.user.username)) {

                                bookExistance.status = bookStatus;
                            }

                        }
                        // Add book + his first onwer
                        else {

                            String title = row.getString("title");
                            String authors = row.getString("authors");
                            int publishedYear = row.getInt("publishedYear");
                            int pageCount = row.getInt("pageCount");

                            String dateOfInsert = row.getString("dateOfInsert");
                            String imgURL = row.getString("imgURL");
                            String lang = row.getString("lang");

                            book.isbn = isbn;
                            book.title = title;
                            book.authors = authors;
                            book.publishedYear = publishedYear;
                            book.pageCount = pageCount;
                            book.dateOfInsert = dateOfInsert;
                            book.imgURL = imgURL;
                            book.lang = lang;

                            // Add book first owner
                            book.owners.add(dataClassUser);

                            // Is user's book
                            if (dataClassUser.username.equalsIgnoreCase(app.user.username)) {
                                book.status = bookStatus;
                            } else {
                                book.status = App.BOOK_STATE_USER_DONT_OWNS;
                            }

                            // Insert book to array
                            searchResultBooks.add(book);

                        }

                    } catch (JSONException e) {
                    }

                }

                adapterBookResults = new AdapterBookInfo(BookSearch.this.getApplicationContext(),
                        R.layout.book_item, searchResultBooks, true);

                // Show list
                listViewBookResults.setAdapter(adapterBookResults);

                break;
            case App.GENERAL_NO_INTERNET:
                // TODO refresh button, and call again asynctask from
                // refresh button
                break;

            case App.BOOKS_OF_USER_NO_BOOKS:

                Toast.makeText(BookSearch.this, R.string.msgNoResultsFound, Toast.LENGTH_LONG).show();
                break;

            case App.GENERAL_WEIRD_ERROR:
                Toast.makeText(BookSearch.this, R.string.msgWeirdError, Toast.LENGTH_LONG).show();
                break;
            case App.GENERAL_DATABASE_ERROR:
                Toast.makeText(BookSearch.this, R.string.msgDatabaseError, Toast.LENGTH_LONG).show();
                break;
            default:
                break;
            }

        }
    }

    /**
     * @param pISBN to check if book exists
     * @return true if book exists, otherwise false
     */
    Book bookExists(String pISBN) {
        for (Book b : searchResultBooks) {
            if (b.isbn.equals(pISBN))
                return b;
        }
        return null;
    }

}