From: drizea Date: Wed, 15 Aug 2012 10:35:59 +0000 (+0300) Subject: code indent removed tab and replaced with spaces X-Git-Url: https://old-git.evergreen-ils.org/?a=commitdiff_plain;h=83e5923a1a695530e5255554d41e5ab03d7cbb91;p=working%2FEvergreen.git code indent removed tab and replaced with spaces --- diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AccountAccess.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AccountAccess.java index 895233a36e..d1533813f4 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AccountAccess.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AccountAccess.java @@ -1,4 +1,3 @@ - package org.evergreen.android.accountAccess; import java.security.MessageDigest; @@ -27,1073 +26,1213 @@ import android.net.ConnectivityManager; import android.util.Log; /** - * The Class AuthenticateUser. - * Singleton class + * The Class AuthenticateUser. Singleton class */ public class AccountAccess { - //Used for authentication purpose - - /** The SERVICE. */ - public static String SERVICE_AUTH = "open-ils.auth"; - - /** The METHOD Auth init. */ - public static String METHOD_AUTH_INIT = "open-ils.auth.authenticate.init"; - - /** The METHOD Auth complete. */ - public static String METHOD_AUTH_COMPLETE = "open-ils.auth.authenticate.complete"; - - /** The METHOD Auth session retrieve. */ - public static String METHOD_AUTH_SESSION_RETRV = "open-ils.auth.session.retrieve"; - - // Used for the Checked out Items Tab - - /** The SERVIC e_ actor. */ - public static String SERVICE_ACTOR = "open-ils.actor"; - - /** The SERVIC e_ circ. */ - public static String SERVICE_CIRC = "open-ils.circ"; - - public static String SERVICE_SEARCH = "open-ils.search"; - - public static String SERVICE_SERIAL = "open-ils.serial"; - - public static String SERVICE_FIELDER = "open-ils.fielder"; - - /** The METHOD_FETCH_CHECKED_OUT_SUM - * description : for a given user returns a a structure of circulation objects sorted by - * out, overdue, lost, claims_returned, long_overdue; A list of ID's returned for each type : "out":[id1,id2,...] - * @param : authtoken , UserID - * @returns: { "out":[id's],"claims_returned":[],"long_overdue":[],"overdue":[],"lost":[]} - */ - public static String METHOD_FETCH_CHECKED_OUT_SUM = "open-ils.actor.user.checked_out"; - - /** The METHOD_FETCH_NON_CAT_CIRCS - * description : for a given user, returns an id-list of non-cataloged circulations that are considered open for now. - * A circ is open if circ time + circ duration (based on type) is > than now - * @param : authtoken, UserID - * @returns: Array of non-catalogen circ IDs, event or error - */ - public static String METHOD_FETCH_NON_CAT_CIRCS = "open-ils.circ.open_non_cataloged_circulation.user"; - - /** The METHOD_FETCH_CIRC_BY_ID - * description : Retrieves a circ object by ID. - * @param : authtoken, circ_id - * @returns : "circ" class. Fields of interest : renewal_remaining, due_date - */ - public static String METHOD_FETCH_CIRC_BY_ID = "open-ils.circ.retrieve"; - - /** The METHOD_FETCH_MODS_FROM_COPY - * description : used to return info - * @param : target_copy - * @returns : mvr class OSRF Object. Fields of interest : title, author - */ - public static String METHOD_FETCH_MODS_FROM_COPY = "open-ils.search.biblio.mods_from_copy"; - - /** The METHOD_FETCH_COPY - * description : used to return info for a PRE_CATALOGED object - * @param : target_copy - * @returns : acp class OSRF Object. Fields of interest : dummy_title, dummy_author - */ - public static String METHOD_FETCH_COPY = "open-ils.search.asset.copy.retrieve"; - /** - * The METHOD_RENEW_CIRC - * description : used to renew a circulation object - * @param : HashMap ex :{ {"patron":id,"copyid":copy_id,"opac_renewal":1} } - * @returnes : acn, acp, circ, mus, mbts - */ - public static String METHOD_RENEW_CIRC = "open-ils.circ.renew"; - - // Used for Holds Tab - - /** The METHOD_FETCH_HOLDS - * @param : authtoken, userID - * @returns: List of "ahr" OSPFObject . Fields of interest : pickup_lib - */ - public static String METHOD_FETCH_HOLDS = "open-ils.circ.holds.retrieve"; - - /** The METHOD_FETCH_ORG_SETTINGS - * description : retrieves a setting from the organization unit - * @param : org_id, String with setting property to return - * @returns : returns the requested value of the setting - */ - public static String METHOD_FETCH_ORG_SETTINGS = "open-ils.actor.ou_setting.ancestor_default"; - - /** The METHOD_FETCH_MRMODS - * - */ - // if holdtype == M return mvr OSRFObject - public static String METHOD_FETCH_MRMODS = "open-ils.search.biblio.metarecord.mods_slim.retrieve"; - // if holdtype == T return mvr OSRFObject - public static String METHOD_FETCH_RMODS = "open-ils.search.biblio.record.mods_slim.retrieve"; - //if hold type V - public static String METHOD_FETCH_VOLUME = "open-ils.search.asset.call_number.retrieve"; - //if hold type I - public static String METHOD_FETCH_ISSUANCE = "open-ils.serial.issuance.pub_fleshed.batch.retrieve"; - - public static String METHOD_FETCH_HOLD_STATUS = "open-ils.circ.hold.queue_stats.retrieve"; - - /** The METHOD_UPDATE_HOLD - * description : Updates the specified hold. If session user != hold user then session user - * must have UPDATE_HOLD permissions - * @param : authtoken, ahr object - * @returns : hold_is on success, event or error on failure - */ - public static String METHOD_UPDATE_HOLD = "open-ils.circ.hold.update"; - - /** The METHOD_CANCEL_HOLD - * description : Cancels the specified hold. session user != hold user - * must have CANCEL_HOLD permissions. - * @param : authtoken, hold_ids, one after another : 1,21,33,.... - * @returns : 1 on success, event or error on failure - */ - public static String METHOD_CANCEL_HOLD = "open-ils.circ.hold.cancel"; - - /** The METHOD_VERIFY_HOLD_POSSIBLE - * description : - * @param : authtoken , hashmap {"titleid":38,"mrid":35,"volume_id":null,"issuanceid":null, - * "copy_id":null,"hold_type":"T","holdable_formats":null,"patronid":2,"depth":0,"pickup_lib":"8","partid":null} - * parameters : (desc in OpenILS::Application::Circ::holds perldoc) - * patron_id ID of hold recipient - * depth (hold range depth, default 0) - * pickup_lib destination for hold, fallback value for selection_ou - * selection_ou - * issuanceid - * partid - * titleid - * volume_id - * copy_id - * mrid - * hold_type - * - * @returns : hashmap with "success" : 1 field or - */ - public static String METHOD_VERIFY_HOLD_POSSIBLE = "open-ils.circ.title_hold.is_possible"; - - /** The METHOD_CREATE_HOLD - * description : - * @param : authtoken, ahr OSRFObject - * @returns : hash with messages : "success" : 1 field or - */ - public static String METHOD_CREATE_HOLD = "open-ils.circ.holds.create"; - - //Used for Fines - - /** The METHODS_FETCH_FINES_SUMMARY - * description : - * @param : authToken, UserID - * @returns: "mous" OSRFObject. fields: balance_owed, total_owed, total_paid - */ - public static String METHOD_FETCH_FINES_SUMMARY = "open-ils.actor.user.fines.summary"; - - /** The METHOD_FETCH_TRANSACTIONS - * description: For a given user retrieves a list of fleshed transactions. List of objects, each object is a hash - * containing : transaction, circ, record - * @param : authToken, userID - * @returns : array of objects, must investigate - */ - public static String METHOD_FETCH_TRANSACTIONS = "open-ils.actor.user.transactions.have_charge.fleshed"; - - /** The METHOD_FETCH_MONEY_BILLING - * description : - * @param : authToken, transaction_id; - */ - public static String METHOD_FETCH_MONEY_BILLING = "open-ils.circ.money.billing.retrieve.all"; - - - //Used for book bags - /** The METHOD_FLESH_CONTAINERS - * description : Retrieves all un-fleshed buckets by class assigned to a given user - * VIEW_CONTAINER permissions is requestID != owner ID - * @param : authtoken, UserID, "biblio", "bookbag" - * @returns : array of "cbreb" OSRFObjects - */ - public static String METHOD_FLESH_CONTAINERS = "open-ils.actor.container.retrieve_by_class.authoritative"; - - - /** The METHOD_FLESH_PUBLIC_CONTAINER - * description : array of contaoners correspondig to a id - * @param : authtoken , "biblio" , boobkbag ID - * @returns : array of "crebi" OSRF objects (content of bookbag, id's of elements to get more info) - */ - public static String METHOD_FLESH_PUBLIC_CONTAINER = "open-ils.actor.container.flesh"; - - - public static String METHOD_CONTAINER_DELETE = "open-ils.actor.container.item.delete"; - - public static String METHOD_CONTAINER_CREATE = "open-ils.actor.container.create"; - - public static String METHOD_CONTAINER_ITEM_CREATE = "open-ils.actor.container.item.create"; - - public static String METHOD_CONTAINER_FULL_DELETE = "open-ils.actor.container.full_delete"; - - public ArrayList bookBags = null; - - /** The conn. */ - public HttpConnection conn; - - /** The http address. */ - private String httpAddress = "http://ulysses.calvin.edu"; - - /** The TAG. */ - public String TAG = "AuthenticareUser"; - - /** The auth token. - * Sent with every request that needs authentication - * */ - public String authToken = null; - - private ConnectivityManager cm; - - /** The auth time. */ - private Integer authTime = null; - - private Integer userID = null; - //for demo purpose - /** The user name. */ - public static String userName = "daniel"; - - /** The password. */ - public static String password = "demo123"; - - private static AccountAccess accountAccess = null; - /** - * Instantiates a new authenticate user. - * - * @param httpAddress the http address - */ - private AccountAccess(String httpAddress, ConnectivityManager cm) { - - this.httpAddress = httpAddress; - this.cm = cm; - - try { - // configure the connection - - System.out.println("Connection with " + httpAddress); - conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); - - } catch (Exception e) { - System.err.println("Exception in establishing connection " - + e.getMessage()); - } - - } - - public boolean isAuthenticated(){ - - if(authToken != null) - return true; - - return false; - } - - public static AccountAccess getAccountAccess(String httpAddress, ConnectivityManager cm){ - - if(accountAccess == null){ - accountAccess = new AccountAccess(httpAddress,cm); - } - System.out.println(" Addresses " + httpAddress + " " + accountAccess.httpAddress); - if(!httpAddress.equals(accountAccess.httpAddress)) - accountAccess.updateHttpAddress(httpAddress); - - return accountAccess; - } - - // the object must be initialized before - public static AccountAccess getAccountAccess(){ - - if(accountAccess != null){ - return accountAccess; - } - - return null; - } - /* - * Change the Http conn to a new library address - */ - public void updateHttpAddress(String httpAddress){ - System.out.println("update http address of account access to " + httpAddress); - try { - // configure the connection - this.httpAddress = httpAddress; - System.out.println("Connection with " + httpAddress); - conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); - - } catch (Exception e) { - System.err.println("Exception in establishing connection " - + e.getMessage()); - } - } - /** - * Md5. - * - * @param s the s - * @return the string - */ - private String md5(String s) { - try { - // Create MD5 Hash - MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); - digest.update(s.getBytes()); - byte messageDigest[] = digest.digest(); - - // Create Hex String - StringBuffer hexString = new StringBuffer(); - for (int i=0; i complexParam = new HashMap(); - //TODO parameter for user login - complexParam.put("type", "opac"); - - complexParam.put("username", userName); - complexParam.put("password", hash); - - System.out.println("Password " + password); - System.out.println("Compelx param " + complexParam); - - Object resp = Utils.doRequest(conn, SERVICE_AUTH, METHOD_AUTH_COMPLETE, cm, new Object[]{complexParam}); - if(resp == null) - return false; - - String queryResult = ((Map) resp).get("textcode"); - - System.out.println("Result " + queryResult); - - if(queryResult.equals("SUCCESS")){ - Object payload = ((Map) resp).get("payload"); - accountAccess.authToken = ((Map)payload).get("authtoken"); - try{ - System.out.println(authToken); - accountAccess.authTime = ((Map)payload).get("authtime"); - - }catch(Exception e){ - System.err.println("Error in parsing authtime " + e.getMessage()); - } - - //get user ID - try{ - accountAccess.getAccountSummary(); - }catch(Exception e){ - Log.d(TAG, "Error in retrieving account info, this is normal if it is before IDL load"); - } - - return true; - } - - return false; - - } - - - //------------------------Checked Out Items Section -------------------------// - - public ArrayList getItemsCheckedOut() throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - - ArrayList circRecords = new ArrayList(); - /* - ArrayList long_overdue = new ArrayList(); - ArrayList claims_returned = new ArrayList(); - ArrayList lost = new ArrayList(); - ArrayList out = new ArrayList(); - ArrayList overdue = new ArrayList(); - */ - - //fetch ids - List long_overdue_id; - List overdue_id; - List claims_returned_id; - List lost_id; - List out_id; - - - Object resp = Utils.doRequest(conn, SERVICE_ACTOR, METHOD_FETCH_CHECKED_OUT_SUM, authToken, cm, new Object[]{authToken, userID}); - - long_overdue_id = (List)((Map)resp).get("long_overdue"); - claims_returned_id = (List)((Map)resp).get("claims_returned"); - lost_id = (List)((Map)resp).get("lost"); - out_id = (List)((Map)resp).get("out"); - overdue_id = (List)((Map)resp).get("overdue"); - - //get all the record circ info - if(out_id != null) - for(int i=0;i complexParam = new HashMap(); - complexParam.put("patron", this.userID); - complexParam.put("copyid", target_copy); - complexParam.put("opac_renewal", 1); - - Object a_lot = (Object) Utils.doRequest(conn, SERVICE_CIRC, METHOD_RENEW_CIRC, authToken, cm, new Object[]{authToken,complexParam}); - - Map resp = (Map)a_lot; - - if(resp.get("textcode") != null){ - if(resp.get("textcode").equals("MAX_RENEWALS_REACHED")) - throw new MaxRenewalsException(); - throw new ServerErrorMessage(resp.get("desc").toString()); - } - - - } - - //------------------------Holds Section --------------------------------------// - - public Object fetchOrgSettings(Integer org_id, String setting)throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - OSRFObject response = (OSRFObject) Utils.doRequest(conn, SERVICE_ACTOR, METHOD_FETCH_ORG_SETTINGS, cm, new Object[]{org_id,setting}); - return response; - - } - - - - public List getHolds() throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - - ArrayList holds = new ArrayList(); - - //fields of interest : expire_time - List listHoldsAhr = null; - - Object resp = Utils.doRequest(conn, SERVICE_CIRC, METHOD_FETCH_HOLDS, authToken, cm, new Object[]{authToken,userID}); - - listHoldsAhr = (List) resp; - - for(int i=0;i)holdInfo.get("types_of_resource")).get(0).toString(); - }catch(Exception e){System.err.println("Can't get types of resurce type" + e.getMessage());}; - } - else{ - //multiple objects per hold ???? - holdInfo = holdFetchObjects(holdArhObject, hold); - - } - return holdInfo; - } - - private OSRFObject holdFetchObjects(OSRFObject hold, HoldRecord holdObj) throws NoNetworkAccessException, NoAccessToServer{ - - String type = (String)hold.get("hold_type"); - - System.out.println("Hold Type " + type); - if(type.equals("C")){ - - /* steps - * asset.copy'->'asset.call_number'->'biblio.record_entry' - * or, in IDL ids, acp->acn->bre - */ - - //fetch_copy - OSRFObject copyObject = fetchAssetCopy(hold.getInt("target")); - //fetch_volume from copyObject.call_number field - Integer call_number = copyObject.getInt("call_number"); - - if(call_number != null){ - - OSRFObject volume = (OSRFObject) Utils.doRequest(conn,SERVICE_SEARCH, METHOD_FETCH_VOLUME, cm, new Object[]{copyObject.getInt("call_number")}); - //in volume object : record - Integer record = volume.getInt("record"); - - //part label - holdObj.part_label = volume.getString("label"); - - System.out.println("Record " + record); - OSRFObject holdInfo = (OSRFObject)Utils.doRequest(conn,SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, new Object[]{record}); - - holdObj.title = holdInfo.getString("title"); - holdObj.author = holdInfo.getString("author"); - holdObj.recordInfo = new RecordInfo((OSRFObject)holdInfo); - try{ - holdObj.types_of_resource= ((List)holdInfo.get("types_of_resource")).get(0).toString(); - }catch(Exception e){System.err.println("Can't get types of resurce type" + e.getMessage());}; - } - - - - return copyObject; - } - else - if(type.equals("V")){ - //must test - - //fetch_volume - OSRFObject volume = (OSRFObject) Utils.doRequest(conn,SERVICE_SEARCH, METHOD_FETCH_VOLUME, cm, new Object[]{hold.getInt("target")}); - //in volume object : record - - //in volume object : record - Integer record = volume.getInt("record"); - - //part label - holdObj.part_label = volume.getString("label"); - - System.out.println("Record " + record); - OSRFObject holdInfo = (OSRFObject)Utils.doRequest(conn,SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, new Object[]{record}); - - holdObj.title = holdInfo.getString("title"); - holdObj.author = holdInfo.getString("author"); - holdObj.recordInfo = new RecordInfo((OSRFObject)holdInfo); - try{ - holdObj.types_of_resource= ((List)holdInfo.get("types_of_resource")).get(0).toString(); - }catch(Exception e){System.err.println("Can't get types of resurce type" + e.getMessage());}; - } - else - if(type.equals("I")){ - OSRFObject issuance = (OSRFObject) Utils.doRequest(conn,SERVICE_SERIAL, METHOD_FETCH_ISSUANCE, cm, new Object[]{hold.getInt("target")}); - //TODO - - } - else - if(type.equals("P")){ - HashMap param = new HashMap(); - - param.put("cache", 1); - - ArrayList fieldsList = new ArrayList(); - fieldsList.add("label"); - fieldsList.add("record"); - - param.put("fields", fieldsList); - HashMap queryParam = new HashMap(); - //PART_ID use "target field in hold" - queryParam.put("id", hold.getInt("target")); - param.put("query",queryParam); - - //returns [{record:id, label=part label}] - - List part = (List)Utils.doRequest(conn,SERVICE_FIELDER,"open-ils.fielder.bmp.atomic", cm, new Object[]{param}); - - Map partObj =(Map)part.get(0); - - Integer recordID = (Integer)partObj.get("record"); - String part_label = (String)partObj.get("label"); - - OSRFObject holdInfo = (OSRFObject)Utils.doRequest(conn,SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, new Object[]{recordID}); - - holdObj.part_label = part_label; - holdObj.title = holdInfo.getString("title"); - holdObj.author = holdInfo.getString("author"); - holdObj.recordInfo = new RecordInfo((OSRFObject)holdInfo); - try{ - holdObj.types_of_resource= ((List)holdInfo.get("types_of_resource")).get(0).toString(); - }catch(Exception e){System.err.println("Can't get types of resurce type" + e.getMessage());}; - } - - return null; - } - - - public Object fetchHoldStatus(OSRFObject hold, HoldRecord holdObj) throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - Integer hold_id = hold.getInt("id"); - // MAP : potential_copies, status, total_holds, queue_position, estimated_wait - Object hold_status = Utils.doRequest(conn,SERVICE_CIRC, METHOD_FETCH_HOLD_STATUS, authToken, cm, new Object[]{authToken,hold_id}); - - //get status - holdObj.status = ((Map)hold_status).get("status"); - return hold_status; - } - - - public boolean cancelHold(OSRFObject hold) throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - Integer hold_id = hold.getInt("id"); - - Object response = Utils.doRequest(conn,SERVICE_CIRC, METHOD_CANCEL_HOLD, authToken, cm, new Object[]{authToken,hold_id}); - - //delete successful - if(response.toString().equals("1")) - return true; - - return false; - - } - - public Object updateHold(OSRFObject ahr,Integer pickup_lib, boolean email_notify, boolean phone_notify, String phone, boolean suspendHold, String expire_time,String thaw_date) - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - //TODO verify that object is correct passed to the server - - ahr.put("pickup_lib", pickup_lib); //pick-up lib - ahr.put("phone_notify", phone); - ahr.put("email_notify", email_notify); - ahr.put("expire_time",expire_time); - //frozen set, what this means ? - ahr.put("frozen", suspendHold); - //only if it is frozen - ahr.put("thaw_date",thaw_date); - - Object response = Utils.doRequest(conn,SERVICE_CIRC, METHOD_UPDATE_HOLD, authToken, cm, new Object[]{authToken,ahr}); - - return response; - } - - public String[] createHold(Integer recordID, Integer pickup_lib, boolean email_notify, boolean phone_notify, String phone, boolean suspendHold, String expire_time,String thaw_date) - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - OSRFObject ahr = new OSRFObject("ahr"); - ahr.put("target", recordID); - ahr.put("usr", userID); - ahr.put("requestor", userID); - - //TODO - //only gold type 'T' for now - ahr.put("hold_type", "T"); - ahr.put("pickup_lib", pickup_lib); //pick-up lib - ahr.put("phone_notify", phone); - ahr.put("email_notify", email_notify); - ahr.put("expire_time",expire_time); - //frozen set, what this means ? - ahr.put("frozen", suspendHold); - //only if it is frozen - ahr.put("thaw_date",thaw_date); - - //extra parameters (not mandatory for hold creation) - - - Object response = Utils.doRequest(conn,SERVICE_CIRC, METHOD_CREATE_HOLD, authToken, cm, new Object[]{authToken,ahr}); - - String[] resp = new String[3]; - //if we can get hold ID then we return true - try{ - - Integer id = Integer.parseInt(response.toString()); - if(id >-1) - resp[0] = "true"; - - - }catch(Exception e){ - - List respErrorMessage = (List) response; - - Object map = respErrorMessage.get(0); - resp[0]="false"; - - resp[1] = ((Map)map).get("textcode"); - resp[2] = ((Map)map).get("desc"); - }; - - System.out.println("Result " + resp[1] + " " + resp[2]); - - //else we return false - return resp; - } - // ?? return boolean - public Object isHoldPossible(Integer pickup_lib,Integer recordID) - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - - HashMap mapAsk = getHoldPreCreateInfo(recordID, pickup_lib); - mapAsk.put("pickup_lib", pickup_lib); - mapAsk.put("hold_type", null); - mapAsk.put("patronid", userID); - mapAsk.put("volume_id", null); - mapAsk.put("issuanceid", null); - mapAsk.put("copy_id", null); - mapAsk.put("depth", 0); - mapAsk.put("part_id", null); - mapAsk.put("holdable_formats", null); - //{"titleid":63,"mrid":60,"volume_id":null,"issuanceid":null,"copy_id":null,"hold_type":"T","holdable_formats":null, - //"patronid":2,"depth":0,"pickup_lib":"8","partid":null} - - - Object response = Utils.doRequest(conn,SERVICE_CIRC, METHOD_VERIFY_HOLD_POSSIBLE, authToken, cm, new Object[]{authToken,mapAsk}); - - return response; - } - //return - public HashMap getHoldPreCreateInfo(Integer recordID, Integer pickup_lib) - throws NoNetworkAccessException, NoAccessToServer{ - - - HashMap param = new HashMap(); - - param.put("pickup_lib",pickup_lib); - param.put("record", recordID); - - Map response = (Map)Utils.doRequest(conn, SERVICE_SEARCH, "open-ils.search.metabib.record_to_descriptors", cm, new Object[]{param}); - - Object obj = response.get("metarecord"); - System.out.println(obj); - Integer metarecordID = Integer.parseInt(obj.toString()); - - HashMap map = new HashMap(); - map.put("titleid", recordID); - map.put("mrid", metarecordID); - - return map; - /* Methods to get necessary info on hold - open-ils.search.metabib.record_to_descriptors - - open-ils.search.biblio.record_hold_parts - */ - } - - - //----------------------------Fines Summary------------------------------------// - - public float[] getFinesSummary() - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - //mous object - OSRFObject finesSummary = (OSRFObject) Utils.doRequest(conn,SERVICE_ACTOR, METHOD_FETCH_FINES_SUMMARY, authToken, cm, new Object[]{authToken,userID}); - - float fines[] = new float[3]; - try{ - fines[0] = Float.parseFloat(finesSummary.getString("total_owed")); - fines[1] = Float.parseFloat(finesSummary.getString("total_paid")); - fines[2] = Float.parseFloat(finesSummary.getString("balance_owed")); - }catch(Exception e){ - System.err.println("Exception in parsing fines " + e.getMessage()); - } - - return fines; - } - - public ArrayList getTransactions() - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - ArrayList finesRecords = new ArrayList(); - - Object transactions = Utils.doRequest(conn,SERVICE_ACTOR, METHOD_FETCH_TRANSACTIONS, authToken, cm, new Object[]{authToken,userID}); - - - //get Array - - List> list = (List>)transactions; - - for(int i=0;i item = list.get(i); - - FinesRecord record = new FinesRecord(item.get("circ"),item.get("record"),item.get("transaction")); - finesRecords.add(record); - } - - return finesRecords; - } - - //---------------------------------------Book bags-----------------------------------// - - public ArrayList getBookbags() - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - Object response = Utils.doRequest(conn,SERVICE_ACTOR, METHOD_FLESH_CONTAINERS, authToken, cm, new Object[]{authToken,userID,"biblio","bookbag"}); - - List bookbags = (List)response; - - ArrayList bookBagObj = new ArrayList(); - //in order to refresh bookbags - this.bookBags = bookBagObj; - - if(bookbags == null) - return bookBagObj; - - for(int i=0;i map =(Map) Utils.doRequest(conn,SERVICE_ACTOR, METHOD_FLESH_PUBLIC_CONTAINER, authToken, cm, new Object[]{authToken,"biblio",bookbagID}); - - List items =(List) map.get("items"); - - for(int i=0;i than now + * + * @param : authtoken, UserID + * @returns: Array of non-catalogen circ IDs, event or error + */ + public static String METHOD_FETCH_NON_CAT_CIRCS = "open-ils.circ.open_non_cataloged_circulation.user"; + + /** + * The METHOD_FETCH_CIRC_BY_ID description : Retrieves a circ object by ID. + * + * @param : authtoken, circ_id + * @returns : "circ" class. Fields of interest : renewal_remaining, due_date + */ + public static String METHOD_FETCH_CIRC_BY_ID = "open-ils.circ.retrieve"; + + /** + * The METHOD_FETCH_MODS_FROM_COPY description : used to return info + * + * @param : target_copy + * @returns : mvr class OSRF Object. Fields of interest : title, author + */ + public static String METHOD_FETCH_MODS_FROM_COPY = "open-ils.search.biblio.mods_from_copy"; + + /** + * The METHOD_FETCH_COPY description : used to return info for a + * PRE_CATALOGED object + * + * @param : target_copy + * @returns : acp class OSRF Object. Fields of interest : dummy_title, + * dummy_author + */ + public static String METHOD_FETCH_COPY = "open-ils.search.asset.copy.retrieve"; + /** + * The METHOD_RENEW_CIRC description : used to renew a circulation object + * + * @param : HashMap ex :{ {"patron":id,"copyid":copy_id,"opac_renewal":1} } + * @returnes : acn, acp, circ, mus, mbts + */ + public static String METHOD_RENEW_CIRC = "open-ils.circ.renew"; + + // Used for Holds Tab + + /** + * The METHOD_FETCH_HOLDS + * + * @param : authtoken, userID + * @returns: List of "ahr" OSPFObject . Fields of interest : pickup_lib + */ + public static String METHOD_FETCH_HOLDS = "open-ils.circ.holds.retrieve"; + + /** + * The METHOD_FETCH_ORG_SETTINGS description : retrieves a setting from the + * organization unit + * + * @param : org_id, String with setting property to return + * @returns : returns the requested value of the setting + */ + public static String METHOD_FETCH_ORG_SETTINGS = "open-ils.actor.ou_setting.ancestor_default"; + + /** + * The METHOD_FETCH_MRMODS + * + */ + // if holdtype == M return mvr OSRFObject + public static String METHOD_FETCH_MRMODS = "open-ils.search.biblio.metarecord.mods_slim.retrieve"; + // if holdtype == T return mvr OSRFObject + public static String METHOD_FETCH_RMODS = "open-ils.search.biblio.record.mods_slim.retrieve"; + // if hold type V + public static String METHOD_FETCH_VOLUME = "open-ils.search.asset.call_number.retrieve"; + // if hold type I + public static String METHOD_FETCH_ISSUANCE = "open-ils.serial.issuance.pub_fleshed.batch.retrieve"; + + public static String METHOD_FETCH_HOLD_STATUS = "open-ils.circ.hold.queue_stats.retrieve"; + + /** + * The METHOD_UPDATE_HOLD description : Updates the specified hold. If + * session user != hold user then session user must have UPDATE_HOLD + * permissions + * + * @param : authtoken, ahr object + * @returns : hold_is on success, event or error on failure + */ + public static String METHOD_UPDATE_HOLD = "open-ils.circ.hold.update"; + + /** + * The METHOD_CANCEL_HOLD description : Cancels the specified hold. session + * user != hold user must have CANCEL_HOLD permissions. + * + * @param : authtoken, hold_ids, one after another : 1,21,33,.... + * @returns : 1 on success, event or error on failure + */ + public static String METHOD_CANCEL_HOLD = "open-ils.circ.hold.cancel"; + + /** + * The METHOD_VERIFY_HOLD_POSSIBLE description : + * + * @param : authtoken , hashmap + * {"titleid":38,"mrid":35,"volume_id":null,"issuanceid":null, + * "copy_id" + * :null,"hold_type":"T","holdable_formats":null,"patronid":2 + * ,"depth":0,"pickup_lib":"8","partid":null} parameters : (desc in + * OpenILS::Application::Circ::holds perldoc) patron_id ID of hold + * recipient depth (hold range depth, default 0) pickup_lib + * destination for hold, fallback value for selection_ou selection_ou + * issuanceid partid titleid volume_id copy_id mrid hold_type + * + * @returns : hashmap with "success" : 1 field or + */ + public static String METHOD_VERIFY_HOLD_POSSIBLE = "open-ils.circ.title_hold.is_possible"; + + /** + * The METHOD_CREATE_HOLD description : + * + * @param : authtoken, ahr OSRFObject + * @returns : hash with messages : "success" : 1 field or + */ + public static String METHOD_CREATE_HOLD = "open-ils.circ.holds.create"; + + // Used for Fines + + /** + * The METHODS_FETCH_FINES_SUMMARY description : + * + * @param : authToken, UserID + * @returns: "mous" OSRFObject. fields: balance_owed, total_owed, total_paid + */ + public static String METHOD_FETCH_FINES_SUMMARY = "open-ils.actor.user.fines.summary"; + + /** + * The METHOD_FETCH_TRANSACTIONS description: For a given user retrieves a + * list of fleshed transactions. List of objects, each object is a hash + * containing : transaction, circ, record + * + * @param : authToken, userID + * @returns : array of objects, must investigate + */ + public static String METHOD_FETCH_TRANSACTIONS = "open-ils.actor.user.transactions.have_charge.fleshed"; + + /** + * The METHOD_FETCH_MONEY_BILLING description : + * + * @param : authToken, transaction_id; + */ + public static String METHOD_FETCH_MONEY_BILLING = "open-ils.circ.money.billing.retrieve.all"; + + // Used for book bags + /** + * The METHOD_FLESH_CONTAINERS description : Retrieves all un-fleshed + * buckets by class assigned to a given user VIEW_CONTAINER permissions is + * requestID != owner ID + * + * @param : authtoken, UserID, "biblio", "bookbag" + * @returns : array of "cbreb" OSRFObjects + */ + public static String METHOD_FLESH_CONTAINERS = "open-ils.actor.container.retrieve_by_class.authoritative"; + + /** + * The METHOD_FLESH_PUBLIC_CONTAINER description : array of contaoners + * correspondig to a id + * + * @param : authtoken , "biblio" , boobkbag ID + * @returns : array of "crebi" OSRF objects (content of bookbag, id's of + * elements to get more info) + */ + public static String METHOD_FLESH_PUBLIC_CONTAINER = "open-ils.actor.container.flesh"; + + public static String METHOD_CONTAINER_DELETE = "open-ils.actor.container.item.delete"; + + public static String METHOD_CONTAINER_CREATE = "open-ils.actor.container.create"; + + public static String METHOD_CONTAINER_ITEM_CREATE = "open-ils.actor.container.item.create"; + + public static String METHOD_CONTAINER_FULL_DELETE = "open-ils.actor.container.full_delete"; + + public ArrayList bookBags = null; + + /** The conn. */ + public HttpConnection conn; + + /** The http address. */ + private String httpAddress = "http://ulysses.calvin.edu"; + + /** The TAG. */ + public String TAG = "AuthenticareUser"; + + /** + * The auth token. Sent with every request that needs authentication + * */ + public String authToken = null; + + private ConnectivityManager cm; + + /** The auth time. */ + private Integer authTime = null; + + private Integer userID = null; + // for demo purpose + /** The user name. */ + public static String userName = "daniel"; + + /** The password. */ + public static String password = "demo123"; + + private static AccountAccess accountAccess = null; + + /** + * Instantiates a new authenticate user. + * + * @param httpAddress + * the http address + */ + private AccountAccess(String httpAddress, ConnectivityManager cm) { + + this.httpAddress = httpAddress; + this.cm = cm; + + try { + // configure the connection + + System.out.println("Connection with " + httpAddress); + conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); + + } catch (Exception e) { + System.err.println("Exception in establishing connection " + + e.getMessage()); + } + + } + + public boolean isAuthenticated() { + + if (authToken != null) + return true; + + return false; + } + + public static AccountAccess getAccountAccess(String httpAddress, + ConnectivityManager cm) { + + if (accountAccess == null) { + accountAccess = new AccountAccess(httpAddress, cm); + } + System.out.println(" Addresses " + httpAddress + " " + + accountAccess.httpAddress); + if (!httpAddress.equals(accountAccess.httpAddress)) + accountAccess.updateHttpAddress(httpAddress); + + return accountAccess; + } + + // the object must be initialized before + public static AccountAccess getAccountAccess() { + + if (accountAccess != null) { + return accountAccess; + } + + return null; + } + + /* + * Change the Http conn to a new library address + */ + public void updateHttpAddress(String httpAddress) { + System.out.println("update http address of account access to " + + httpAddress); + try { + // configure the connection + this.httpAddress = httpAddress; + System.out.println("Connection with " + httpAddress); + conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); + + } catch (Exception e) { + System.err.println("Exception in establishing connection " + + e.getMessage()); + } + } + + /** + * Md5. + * + * @param s + * the s + * @return the string + */ + private String md5(String s) { + try { + // Create MD5 Hash + MessageDigest digest = java.security.MessageDigest + .getInstance("MD5"); + digest.update(s.getBytes()); + byte messageDigest[] = digest.digest(); + + // Create Hex String + StringBuffer hexString = new StringBuffer(); + for (int i = 0; i < messageDigest.length; i++) { + String hex = Integer.toHexString(0xFF & messageDigest[i]); + if (hex.length() == 1) { + // could use a for loop, but we're only dealing with a + // single byte + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + return ""; + } + + public static void setAccountInfo(String username, String password) { + + AccountAccess.userName = username; + AccountAccess.password = password; + + } + + /** + * Authenticate. + */ + public boolean authenticate() throws NoNetworkAccessException, + NoAccessToServer { + + String seed = authenticateInit(); + + return authenticateComplete(seed); + } + + /** + * Gets the account summary. + * + * @return the account summary + */ + public OSRFObject getAccountSummary() { + + Method method = new Method(METHOD_AUTH_SESSION_RETRV); + + method.addParam(authToken); + + // sync request + HttpRequest req = new GatewayRequest(conn, SERVICE_AUTH, method).send(); + Object resp; + + while ((resp = req.recv()) != null) { + System.out.println("Sync Response: " + resp); + OSRFObject au = (OSRFObject) resp; + userID = au.getInt("id"); + System.out.println("User Id " + userID); + + return au; + } + return null; + } + + /** + * Authenticate init. + * + * @return seed for phase 2 of login + */ + private String authenticateInit() throws NoAccessToServer, + NoNetworkAccessException { + + String seed = null; + + System.out.println("Send request to " + httpAddress); + Object resp = (Object) Utils.doRequest(conn, SERVICE_AUTH, + METHOD_AUTH_INIT, cm, new Object[] { userName }); + if (resp != null) + seed = resp.toString(); + + System.out.println("Seed " + seed); + + return seed; + } + + /** + * Authenticate complete. Phase 2 of login process Application send's + * username and hash to confirm login + * + * @param seed + * the seed + * @returns bollean if auth was ok + */ + private boolean authenticateComplete(String seed) throws NoAccessToServer, + NoNetworkAccessException { + + // calculate hash to pass to server for authentication process phase 2 + // seed = "b18a9063e0c6f49dfe7a854cc6ab5775"; + String hash = md5(seed + md5(password)); + System.out.println("Hash " + hash); + + HashMap complexParam = new HashMap(); + // TODO parameter for user login + complexParam.put("type", "opac"); + + complexParam.put("username", userName); + complexParam.put("password", hash); + + System.out.println("Password " + password); + System.out.println("Compelx param " + complexParam); + + Object resp = Utils.doRequest(conn, SERVICE_AUTH, METHOD_AUTH_COMPLETE, + cm, new Object[] { complexParam }); + if (resp == null) + return false; + + String queryResult = ((Map) resp).get("textcode"); + + System.out.println("Result " + queryResult); + + if (queryResult.equals("SUCCESS")) { + Object payload = ((Map) resp).get("payload"); + accountAccess.authToken = ((Map) payload) + .get("authtoken"); + try { + System.out.println(authToken); + accountAccess.authTime = ((Map) payload) + .get("authtime"); + + } catch (Exception e) { + System.err.println("Error in parsing authtime " + + e.getMessage()); + } + + // get user ID + try { + accountAccess.getAccountSummary(); + } catch (Exception e) { + Log.d(TAG, + "Error in retrieving account info, this is normal if it is before IDL load"); + } + + return true; + } + + return false; + + } + + // ------------------------Checked Out Items Section + // -------------------------// + + public ArrayList getItemsCheckedOut() + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + ArrayList circRecords = new ArrayList(); + /* + * ArrayList long_overdue = new ArrayList(); + * ArrayList claims_returned = new ArrayList(); + * ArrayList lost = new ArrayList(); + * ArrayList out = new ArrayList(); + * ArrayList overdue = new ArrayList(); + */ + + // fetch ids + List long_overdue_id; + List overdue_id; + List claims_returned_id; + List lost_id; + List out_id; + + Object resp = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_FETCH_CHECKED_OUT_SUM, authToken, cm, new Object[] { + authToken, userID }); + + long_overdue_id = (List) ((Map) resp) + .get("long_overdue"); + claims_returned_id = (List) ((Map) resp) + .get("claims_returned"); + lost_id = (List) ((Map) resp).get("lost"); + out_id = (List) ((Map) resp).get("out"); + overdue_id = (List) ((Map) resp).get("overdue"); + + // get all the record circ info + if (out_id != null) + for (int i = 0; i < out_id.size(); i++) { + // get circ + OSRFObject circ = retrieveCircRecord(out_id.get(i)); + CircRecord circRecord = new CircRecord(circ, CircRecord.OUT, + Integer.parseInt(out_id.get(i))); + // get info + fetchInfoForCheckedOutItem(circ.getInt("target_copy"), + circRecord); + circRecords.add(circRecord); + + // System.out.println(out.get(i).get("target_copy")); + // fetchInfoForCheckedOutItem(out.get(i).get("target_copy")+""); + } + + if (overdue_id != null) + for (int i = 0; i < overdue_id.size(); i++) { + // get circ + OSRFObject circ = retrieveCircRecord(overdue_id.get(i)); + CircRecord circRecord = new CircRecord(circ, + CircRecord.OVERDUE, Integer.parseInt(overdue_id.get(i))); + // fetch info + fetchInfoForCheckedOutItem(circ.getInt("target_copy"), + circRecord); + circRecords.add(circRecord); + + } + // TODO are we using this too? In the opac they are not used + /* + * for(int i=0;i complexParam = new HashMap(); + complexParam.put("patron", this.userID); + complexParam.put("copyid", target_copy); + complexParam.put("opac_renewal", 1); + + Object a_lot = (Object) Utils.doRequest(conn, SERVICE_CIRC, + METHOD_RENEW_CIRC, authToken, cm, new Object[] { authToken, + complexParam }); + + Map resp = (Map) a_lot; + + if (resp.get("textcode") != null) { + if (resp.get("textcode").equals("MAX_RENEWALS_REACHED")) + throw new MaxRenewalsException(); + throw new ServerErrorMessage(resp.get("desc").toString()); + } + + } + + // ------------------------Holds Section + // --------------------------------------// + + public Object fetchOrgSettings(Integer org_id, String setting) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + OSRFObject response = (OSRFObject) Utils + .doRequest(conn, SERVICE_ACTOR, METHOD_FETCH_ORG_SETTINGS, cm, + new Object[] { org_id, setting }); + return response; + + } + + public List getHolds() throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + ArrayList holds = new ArrayList(); + + // fields of interest : expire_time + List listHoldsAhr = null; + + Object resp = Utils.doRequest(conn, SERVICE_CIRC, METHOD_FETCH_HOLDS, + authToken, cm, new Object[] { authToken, userID }); + + listHoldsAhr = (List) resp; + + for (int i = 0; i < listHoldsAhr.size(); i++) { + // create hold item + HoldRecord hold = new HoldRecord(listHoldsAhr.get(i)); + // get title + fetchHoldTitleInfo(listHoldsAhr.get(i), hold); + + // get status + fetchHoldStatus(listHoldsAhr.get(i), hold); + + holds.add(hold); + } + return holds; + } + + /* + * hold target type : M - metarecord T - record V - volume I - issuance C - + * copy P - pat + */ + + private Object fetchHoldTitleInfo(OSRFObject holdArhObject, HoldRecord hold) + throws NoNetworkAccessException, NoAccessToServer { + + String holdType = (String) holdArhObject.get("hold_type"); + + String method = null; + + Object response; + OSRFObject holdInfo = null; + if (holdType.equals("T") || holdType.equals("M")) { + + if (holdType.equals("M")) + method = METHOD_FETCH_MRMODS; + if (holdType.equals("T")) + method = METHOD_FETCH_RMODS; + System.out.println(); + holdInfo = (OSRFObject) Utils.doRequest(conn, SERVICE_SEARCH, + method, cm, new Object[] { holdArhObject.get("target") }); + + // System.out.println("Hold here " + holdInfo); + hold.title = ((OSRFObject) holdInfo).getString("title"); + hold.author = ((OSRFObject) holdInfo).getString("author"); + hold.recordInfo = new RecordInfo((OSRFObject) holdInfo); + try { + hold.types_of_resource = ((List) holdInfo + .get("types_of_resource")).get(0).toString(); + } catch (Exception e) { + System.err.println("Can't get types of resurce type" + + e.getMessage()); + } + ; + } else { + // multiple objects per hold ???? + holdInfo = holdFetchObjects(holdArhObject, hold); + + } + return holdInfo; + } + + private OSRFObject holdFetchObjects(OSRFObject hold, HoldRecord holdObj) + throws NoNetworkAccessException, NoAccessToServer { + + String type = (String) hold.get("hold_type"); + + System.out.println("Hold Type " + type); + if (type.equals("C")) { + + /* + * steps asset.copy'->'asset.call_number'->'biblio.record_entry' or, + * in IDL ids, acp->acn->bre + */ + + // fetch_copy + OSRFObject copyObject = fetchAssetCopy(hold.getInt("target")); + // fetch_volume from copyObject.call_number field + Integer call_number = copyObject.getInt("call_number"); + + if (call_number != null) { + + OSRFObject volume = (OSRFObject) Utils.doRequest(conn, + SERVICE_SEARCH, METHOD_FETCH_VOLUME, cm, + new Object[] { copyObject.getInt("call_number") }); + // in volume object : record + Integer record = volume.getInt("record"); + + // part label + holdObj.part_label = volume.getString("label"); + + System.out.println("Record " + record); + OSRFObject holdInfo = (OSRFObject) Utils.doRequest(conn, + SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, + new Object[] { record }); + + holdObj.title = holdInfo.getString("title"); + holdObj.author = holdInfo.getString("author"); + holdObj.recordInfo = new RecordInfo((OSRFObject) holdInfo); + try { + holdObj.types_of_resource = ((List) holdInfo + .get("types_of_resource")).get(0).toString(); + } catch (Exception e) { + System.err.println("Can't get types of resurce type" + + e.getMessage()); + } + ; + } + + return copyObject; + } else if (type.equals("V")) { + // must test + + // fetch_volume + OSRFObject volume = (OSRFObject) Utils.doRequest(conn, + SERVICE_SEARCH, METHOD_FETCH_VOLUME, cm, + new Object[] { hold.getInt("target") }); + // in volume object : record + + // in volume object : record + Integer record = volume.getInt("record"); + + // part label + holdObj.part_label = volume.getString("label"); + + System.out.println("Record " + record); + OSRFObject holdInfo = (OSRFObject) Utils.doRequest(conn, + SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, + new Object[] { record }); + + holdObj.title = holdInfo.getString("title"); + holdObj.author = holdInfo.getString("author"); + holdObj.recordInfo = new RecordInfo((OSRFObject) holdInfo); + try { + holdObj.types_of_resource = ((List) holdInfo + .get("types_of_resource")).get(0).toString(); + } catch (Exception e) { + System.err.println("Can't get types of resurce type" + + e.getMessage()); + } + ; + } else if (type.equals("I")) { + OSRFObject issuance = (OSRFObject) Utils.doRequest(conn, + SERVICE_SERIAL, METHOD_FETCH_ISSUANCE, cm, + new Object[] { hold.getInt("target") }); + // TODO + + } else if (type.equals("P")) { + HashMap param = new HashMap(); + + param.put("cache", 1); + + ArrayList fieldsList = new ArrayList(); + fieldsList.add("label"); + fieldsList.add("record"); + + param.put("fields", fieldsList); + HashMap queryParam = new HashMap(); + // PART_ID use "target field in hold" + queryParam.put("id", hold.getInt("target")); + param.put("query", queryParam); + + // returns [{record:id, label=part label}] + + List part = (List) Utils.doRequest(conn, + SERVICE_FIELDER, "open-ils.fielder.bmp.atomic", cm, + new Object[] { param }); + + Map partObj = (Map) part.get(0); + + Integer recordID = (Integer) partObj.get("record"); + String part_label = (String) partObj.get("label"); + + OSRFObject holdInfo = (OSRFObject) Utils.doRequest(conn, + SERVICE_SEARCH, METHOD_FETCH_RMODS, cm, + new Object[] { recordID }); + + holdObj.part_label = part_label; + holdObj.title = holdInfo.getString("title"); + holdObj.author = holdInfo.getString("author"); + holdObj.recordInfo = new RecordInfo((OSRFObject) holdInfo); + try { + holdObj.types_of_resource = ((List) holdInfo + .get("types_of_resource")).get(0).toString(); + } catch (Exception e) { + System.err.println("Can't get types of resurce type" + + e.getMessage()); + } + ; + } + + return null; + } + + public Object fetchHoldStatus(OSRFObject hold, HoldRecord holdObj) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + Integer hold_id = hold.getInt("id"); + // MAP : potential_copies, status, total_holds, queue_position, + // estimated_wait + Object hold_status = Utils.doRequest(conn, SERVICE_CIRC, + METHOD_FETCH_HOLD_STATUS, authToken, cm, new Object[] { + authToken, hold_id }); + + // get status + holdObj.status = ((Map) hold_status).get("status"); + return hold_status; + } + + public boolean cancelHold(OSRFObject hold) throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + Integer hold_id = hold.getInt("id"); + + Object response = Utils.doRequest(conn, SERVICE_CIRC, + METHOD_CANCEL_HOLD, authToken, cm, new Object[] { authToken, + hold_id }); + + // delete successful + if (response.toString().equals("1")) + return true; + + return false; + + } + + public Object updateHold(OSRFObject ahr, Integer pickup_lib, + boolean email_notify, boolean phone_notify, String phone, + boolean suspendHold, String expire_time, String thaw_date) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + // TODO verify that object is correct passed to the server + + ahr.put("pickup_lib", pickup_lib); // pick-up lib + ahr.put("phone_notify", phone); + ahr.put("email_notify", email_notify); + ahr.put("expire_time", expire_time); + // frozen set, what this means ? + ahr.put("frozen", suspendHold); + // only if it is frozen + ahr.put("thaw_date", thaw_date); + + Object response = Utils.doRequest(conn, SERVICE_CIRC, + METHOD_UPDATE_HOLD, authToken, cm, new Object[] { authToken, + ahr }); + + return response; + } + + public String[] createHold(Integer recordID, Integer pickup_lib, + boolean email_notify, boolean phone_notify, String phone, + boolean suspendHold, String expire_time, String thaw_date) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + OSRFObject ahr = new OSRFObject("ahr"); + ahr.put("target", recordID); + ahr.put("usr", userID); + ahr.put("requestor", userID); + + // TODO + // only gold type 'T' for now + ahr.put("hold_type", "T"); + ahr.put("pickup_lib", pickup_lib); // pick-up lib + ahr.put("phone_notify", phone); + ahr.put("email_notify", email_notify); + ahr.put("expire_time", expire_time); + // frozen set, what this means ? + ahr.put("frozen", suspendHold); + // only if it is frozen + ahr.put("thaw_date", thaw_date); + + // extra parameters (not mandatory for hold creation) + + Object response = Utils.doRequest(conn, SERVICE_CIRC, + METHOD_CREATE_HOLD, authToken, cm, new Object[] { authToken, + ahr }); + + String[] resp = new String[3]; + // if we can get hold ID then we return true + try { + + Integer id = Integer.parseInt(response.toString()); + if (id > -1) + resp[0] = "true"; + + } catch (Exception e) { + + List respErrorMessage = (List) response; + + Object map = respErrorMessage.get(0); + resp[0] = "false"; + + resp[1] = ((Map) map).get("textcode"); + resp[2] = ((Map) map).get("desc"); + } + ; + + System.out.println("Result " + resp[1] + " " + resp[2]); + + // else we return false + return resp; + } + + // ?? return boolean + public Object isHoldPossible(Integer pickup_lib, Integer recordID) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + HashMap mapAsk = getHoldPreCreateInfo(recordID, + pickup_lib); + mapAsk.put("pickup_lib", pickup_lib); + mapAsk.put("hold_type", null); + mapAsk.put("patronid", userID); + mapAsk.put("volume_id", null); + mapAsk.put("issuanceid", null); + mapAsk.put("copy_id", null); + mapAsk.put("depth", 0); + mapAsk.put("part_id", null); + mapAsk.put("holdable_formats", null); + // {"titleid":63,"mrid":60,"volume_id":null,"issuanceid":null,"copy_id":null,"hold_type":"T","holdable_formats":null, + // "patronid":2,"depth":0,"pickup_lib":"8","partid":null} + + Object response = Utils.doRequest(conn, SERVICE_CIRC, + METHOD_VERIFY_HOLD_POSSIBLE, authToken, cm, new Object[] { + authToken, mapAsk }); + + return response; + } + + // return + public HashMap getHoldPreCreateInfo(Integer recordID, + Integer pickup_lib) throws NoNetworkAccessException, + NoAccessToServer { + + HashMap param = new HashMap(); + + param.put("pickup_lib", pickup_lib); + param.put("record", recordID); + + Map response = (Map) Utils.doRequest(conn, + SERVICE_SEARCH, + "open-ils.search.metabib.record_to_descriptors", cm, + new Object[] { param }); + + Object obj = response.get("metarecord"); + System.out.println(obj); + Integer metarecordID = Integer.parseInt(obj.toString()); + + HashMap map = new HashMap(); + map.put("titleid", recordID); + map.put("mrid", metarecordID); + + return map; + /* + * Methods to get necessary info on hold + * open-ils.search.metabib.record_to_descriptors + * + * open-ils.search.biblio.record_hold_parts + */ + } + + // ----------------------------Fines + // Summary------------------------------------// + + public float[] getFinesSummary() throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + // mous object + OSRFObject finesSummary = (OSRFObject) Utils.doRequest(conn, + SERVICE_ACTOR, METHOD_FETCH_FINES_SUMMARY, authToken, cm, + new Object[] { authToken, userID }); + + float fines[] = new float[3]; + try { + fines[0] = Float.parseFloat(finesSummary.getString("total_owed")); + fines[1] = Float.parseFloat(finesSummary.getString("total_paid")); + fines[2] = Float.parseFloat(finesSummary.getString("balance_owed")); + } catch (Exception e) { + System.err.println("Exception in parsing fines " + e.getMessage()); + } + + return fines; + } + + public ArrayList getTransactions() + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + ArrayList finesRecords = new ArrayList(); + + Object transactions = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_FETCH_TRANSACTIONS, authToken, cm, new Object[] { + authToken, userID }); + + // get Array + + List> list = (List>) transactions; + + for (int i = 0; i < list.size(); i++) { + + Map item = list.get(i); + + FinesRecord record = new FinesRecord(item.get("circ"), + item.get("record"), item.get("transaction")); + finesRecords.add(record); + } + + return finesRecords; + } + + // ---------------------------------------Book + // bags-----------------------------------// + + public ArrayList getBookbags() throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + Object response = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_FLESH_CONTAINERS, authToken, cm, new Object[] { + authToken, userID, "biblio", "bookbag" }); + + List bookbags = (List) response; + + ArrayList bookBagObj = new ArrayList(); + // in order to refresh bookbags + this.bookBags = bookBagObj; + + if (bookbags == null) + return bookBagObj; + + for (int i = 0; i < bookbags.size(); i++) { + + BookBag bag = new BookBag(bookbags.get(i)); + getBookbagContent(bag, bookbags.get(i).getInt("id")); + + bookBagObj.add(bag); + } + return bookBagObj; + } + + private Object getBookbagContent(BookBag bag, Integer bookbagID) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + Map map = (Map) Utils.doRequest(conn, + SERVICE_ACTOR, METHOD_FLESH_PUBLIC_CONTAINER, authToken, cm, + new Object[] { authToken, "biblio", bookbagID }); + + List items = (List) map.get("items"); + + for (int i = 0; i < items.size(); i++) { + + BookBagItem bookBagItem = new BookBagItem(items.get(i)); + + bag.items.add(bookBagItem); + } + + return items; + } + + public void removeBookbagItem(Integer id) throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + removeContainer("biblio", id); + + } + + public void createBookbag(String name) throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + OSRFObject cbreb = new OSRFObject("cbreb"); + cbreb.put("btype", "bookbag"); + cbreb.put("name", name); + cbreb.put("pub", false); + cbreb.put("owner", userID); + + createContainer("biblio", cbreb); + } + + public void deleteBookBag(Integer id) throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + Object response = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_CONTAINER_FULL_DELETE, authToken, cm, new Object[] { + authToken, "biblio", id }); + } + + public void addRecordToBookBag(Integer record_id, Integer bookbag_id) + throws SessionNotFoundException, NoAccessToServer, + NoNetworkAccessException { + + OSRFObject cbrebi = new OSRFObject("cbrebi"); + cbrebi.put("bucket", bookbag_id); + cbrebi.put("target_biblio_record_entry", record_id); + cbrebi.put("id", null); + + Object response = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_CONTAINER_ITEM_CREATE, authToken, cm, new Object[] { + authToken, "biblio", cbrebi }); + } + + private void removeContainer(String container, Integer id) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + Object response = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_CONTAINER_DELETE, authToken, cm, new Object[] { + authToken, container, id }); + } + + private void createContainer(String container, Object parameter) + throws SessionNotFoundException, NoNetworkAccessException, + NoAccessToServer { + + Object response = Utils.doRequest(conn, SERVICE_ACTOR, + METHOD_CONTAINER_CREATE, authToken, cm, new Object[] { + authToken, container, parameter }); + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AuthenticateUser.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AuthenticateUser.java index 8ec8804e4f..60e5d77153 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AuthenticateUser.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/AuthenticateUser.java @@ -1,4 +1,3 @@ - package org.evergreen.android.accountAccess; import java.security.MessageDigest; @@ -16,173 +15,174 @@ import org.opensrf.net.http.HttpRequest; */ public class AuthenticateUser { - /** The SERVICE. */ - public static String SERVICE = "open-ils.auth"; - - /** The METHO d_ multicas s_ search. */ - public static String METHOD_AUTH_INIT = "open-ils.auth.authenticate.init"; - - /** The METHO d_ sli m_ retrive. */ - public static String METHOD_AUTH_COMPLETE = "open-ils.auth.authenticate.complete"; - - /** The conn. */ - public HttpConnection conn; - - /** The http address. */ - public String httpAddress = "http://ulysses.calvin.edu"; - - /** The TAG. */ - public String TAG = "AuthenticareUser"; - - /** The auth token. - * Sent with every request that needs authentication - * */ - private String authToken = null; - - //for demo purpose - /** The user name. */ - private String userName = "staff"; - - /** The password. */ - private String password = "demo123"; - - /** - * Instantiates a new authenticate user. - * - * @param httpAddress the http address - */ - public AuthenticateUser(String httpAddress) { - - this.httpAddress = httpAddress; - - try { - // configure the connection - - System.out.println("Connection with " + httpAddress); - conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); - - } catch (Exception e) { - System.err.println("Exception in establishing connection " - + e.getMessage()); - } - - // OSRFRegistry.registerObject("mvr", WireProtocol.ARRAY, new String[] - // {"title","author","doc_id","doc_type","pubdate","isbn","publisher","tcn","subject","type_of_resources","call_numbers","edition","online_loc","synopsis","physical_description","toc","copy_count","series","serials","foreign_copy_maps"}); - - } - - /** - * Md5. - * - * @param s the s - * @return the string - */ - public String md5(String s) { - try { - // Create MD5 Hash - MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); - digest.update(s.getBytes()); - byte messageDigest[] = digest.digest(); - - // Create Hex String - StringBuffer hexString = new StringBuffer(); - for (int i=0; i complexParam = new HashMap(); - - - complexParam.put("username", userName); - complexParam.put("password", hash+"'"); - - - method.addParam(complexParam); - System.out.println("Compelx param " + complexParam); - - // sync test - HttpRequest req = new GatewayRequest(conn, SERVICE, method).send(); - Object resp; - - - while ((resp = req.recv()) != null) { - System.out.println("Sync Response: " + resp); - - String queryResult = ((Map) resp).get("desc"); - - System.out.println("Result " + queryResult); - - if(queryResult.equals("Success")){ - authToken = ((Map) resp).get("authtoken"); - } - } - - - } + /** The SERVICE. */ + public static String SERVICE = "open-ils.auth"; + + /** The METHO d_ multicas s_ search. */ + public static String METHOD_AUTH_INIT = "open-ils.auth.authenticate.init"; + + /** The METHO d_ sli m_ retrive. */ + public static String METHOD_AUTH_COMPLETE = "open-ils.auth.authenticate.complete"; + + /** The conn. */ + public HttpConnection conn; + + /** The http address. */ + public String httpAddress = "http://ulysses.calvin.edu"; + + /** The TAG. */ + public String TAG = "AuthenticareUser"; + + /** + * The auth token. Sent with every request that needs authentication + * */ + private String authToken = null; + + // for demo purpose + /** The user name. */ + private String userName = "staff"; + + /** The password. */ + private String password = "demo123"; + + /** + * Instantiates a new authenticate user. + * + * @param httpAddress + * the http address + */ + public AuthenticateUser(String httpAddress) { + + this.httpAddress = httpAddress; + + try { + // configure the connection + + System.out.println("Connection with " + httpAddress); + conn = new HttpConnection(httpAddress + "/osrf-gateway-v1"); + + } catch (Exception e) { + System.err.println("Exception in establishing connection " + + e.getMessage()); + } + + // OSRFRegistry.registerObject("mvr", WireProtocol.ARRAY, new String[] + // {"title","author","doc_id","doc_type","pubdate","isbn","publisher","tcn","subject","type_of_resources","call_numbers","edition","online_loc","synopsis","physical_description","toc","copy_count","series","serials","foreign_copy_maps"}); + + } + + /** + * Md5. + * + * @param s + * the s + * @return the string + */ + public String md5(String s) { + try { + // Create MD5 Hash + MessageDigest digest = java.security.MessageDigest + .getInstance("MD5"); + digest.update(s.getBytes()); + byte messageDigest[] = digest.digest(); + + // Create Hex String + StringBuffer hexString = new StringBuffer(); + for (int i = 0; i < messageDigest.length; i++) { + String hex = Integer.toHexString(0xFF & messageDigest[i]); + if (hex.length() == 1) { + // could use a for loop, but we're only dealing with a + // single byte + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + return ""; + } + + /** + * Authenticate. + */ + public void authenticate() { + + String seed = authenticateInit(); + + authenticateComplete(seed); + } + + /** + * Authenticate init. + * + * @return seed for phase 2 of login + */ + private String authenticateInit() { + + Method method = new Method(METHOD_AUTH_INIT); + + method.addParam(userName); + + // sync test + HttpRequest req = new GatewayRequest(conn, SERVICE, method).send(); + Object resp; + + String seed = null; + + while ((resp = req.recv()) != null) { + System.out.println("Sync Response: " + resp); + seed = resp.toString(); + } + + System.out.println("Seed " + seed); + + return seed; + } + + /** + * Authenticate complete. Phase 2 of login process Application send's + * username and hash to confirm login + * + * @param seed + * the seed + */ + private void authenticateComplete(String seed) { + + // calculate hash to pass to server for authentication process phase 2 + // seed = "b18a9063e0c6f49dfe7a854cc6ab5775"; + String hash = md5(seed + md5(password)); + System.out.println("Hash " + hash); + + Method method = new Method(METHOD_AUTH_COMPLETE); + + HashMap complexParam = new HashMap(); + + complexParam.put("username", userName); + complexParam.put("password", hash + "'"); + + method.addParam(complexParam); + System.out.println("Compelx param " + complexParam); + + // sync test + HttpRequest req = new GatewayRequest(conn, SERVICE, method).send(); + Object resp; + + while ((resp = req.recv()) != null) { + System.out.println("Sync Response: " + resp); + + String queryResult = ((Map) resp).get("desc"); + + System.out.println("Result " + queryResult); + + if (queryResult.equals("Success")) { + authToken = ((Map) resp).get("authtoken"); + } + } + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/MaxRenewalsException.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/MaxRenewalsException.java index 5b2eaaafab..6d4330d7f7 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/MaxRenewalsException.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/MaxRenewalsException.java @@ -1,10 +1,10 @@ package org.evergreen.android.accountAccess; -public class MaxRenewalsException extends Exception{ +public class MaxRenewalsException extends Exception { - /** + /** * */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/ServerErrorMessage.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/ServerErrorMessage.java index 0da01bb5d8..bfefb1c63f 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/ServerErrorMessage.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/ServerErrorMessage.java @@ -1,16 +1,16 @@ package org.evergreen.android.accountAccess; -public class ServerErrorMessage extends Exception{ +public class ServerErrorMessage extends Exception { - /** + /** * */ - private static final long serialVersionUID = 3341617529835568018L; + private static final long serialVersionUID = 3341617529835568018L; + + public String message; + + public ServerErrorMessage(String message) { + this.message = message; + } - public String message; - - public ServerErrorMessage(String message){ - this.message = message; - } - } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/SessionNotFoundException.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/SessionNotFoundException.java index ee4afa96db..5b34d30d06 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/SessionNotFoundException.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/SessionNotFoundException.java @@ -1,10 +1,10 @@ package org.evergreen.android.accountAccess; -public class SessionNotFoundException extends Exception{ +public class SessionNotFoundException extends Exception { - /** + /** * */ - private static final long serialVersionUID = 123232L; + private static final long serialVersionUID = 123232L; } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBag.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBag.java index 2ca96f8ea8..6dbd7d6044 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBag.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBag.java @@ -5,32 +5,31 @@ import java.util.ArrayList; import org.opensrf.util.OSRFObject; -public class BookBag implements Serializable{ - - public int id; - - public String name = null; - - public String description = null; - - public Boolean shared = null; - - public ArrayList items = null; - - public BookBag(OSRFObject object){ - - this.id = object.getInt("id"); - this.name = object.getString("name"); - this.description = object.getString("description"); - this.items = new ArrayList(); - - - String pub_visible = object.getString("pub"); - - if(pub_visible.equals("f")) - this.shared = false; - else - this.shared = true; - } - +public class BookBag implements Serializable { + + public int id; + + public String name = null; + + public String description = null; + + public Boolean shared = null; + + public ArrayList items = null; + + public BookBag(OSRFObject object) { + + this.id = object.getInt("id"); + this.name = object.getString("name"); + this.description = object.getString("description"); + this.items = new ArrayList(); + + String pub_visible = object.getString("pub"); + + if (pub_visible.equals("f")) + this.shared = false; + else + this.shared = true; + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagDetails.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagDetails.java index b1a53e636f..9c38c26010 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagDetails.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagDetails.java @@ -37,320 +37,322 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; -public class BookBagDetails extends Activity{ - -private String TAG = "BookBags"; - - public static final int RESULT_CODE_UPDATE = 1; - - private SearchCatalog search; - - private AccountAccess accountAccess; - - private ListView lv; - - private BookBagItemsArrayAdapter listAdapter = null; - - private ArrayList bookBagItems = null; - - private Context context; - - private ProgressDialog progressDialog; - - private BookBag bookBag; - - private TextView bookbag_name; - - private Button delete_bookbag_button; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private Runnable getBookBagsItemsRunnable; - @Override - public void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - setContentView(R.layout.bookbagitem_list); - //header portion actions +public class BookBagDetails extends Activity { + + private String TAG = "BookBags"; + + public static final int RESULT_CODE_UPDATE = 1; + + private SearchCatalog search; + + private AccountAccess accountAccess; + + private ListView lv; + + private BookBagItemsArrayAdapter listAdapter = null; + + private ArrayList bookBagItems = null; + + private Context context; + + private ProgressDialog progressDialog; + + private BookBag bookBag; + + private TextView bookbag_name; + + private Button delete_bookbag_button; + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + private Runnable getBookBagsItemsRunnable; + + @Override + public void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + + setContentView(R.layout.bookbagitem_list); + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.bookbag_details_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - - accountAccess = AccountAccess.getAccountAccess(); - bookBag = (BookBag) getIntent().getSerializableExtra("bookBag"); - - context = this; - search = SearchCatalog.getInstance((ConnectivityManager)getSystemService(Service.CONNECTIVITY_SERVICE)); - bookbag_name = (TextView) findViewById(R.id.bookbag_name); - delete_bookbag_button = (Button) findViewById(R.id.remove_bookbag); - bookbag_name.setText(bookBag.name); - delete_bookbag_button.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - final Thread deleteBookbag = new Thread(new Runnable() { - - @Override - public void run() { - - try { - accountAccess.deleteBookBag(bookBag.id); - } catch (SessionNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoNetworkAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoAccessToServer e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - setResult(RESULT_CODE_UPDATE); - finish(); - } - }); - } - }); - - Builder confirmationDialogBuilder = new AlertDialog.Builder( - context); - confirmationDialogBuilder - .setMessage("Delete bookbag?"); - - confirmationDialogBuilder.setNegativeButton( - android.R.string.no, null); - confirmationDialogBuilder.setPositiveButton( - android.R.string.yes, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, - int which) { - - - progressDialog = ProgressDialog.show(context, "Please wait", "Deleting Bookbag"); - deleteBookbag.start(); - } - }); - - confirmationDialogBuilder.create().show(); - - } - }); - - lv = (ListView) findViewById(R.id.bookbagitem_list); - bookBagItems = new ArrayList(); - listAdapter = new BookBagItemsArrayAdapter(context, R.layout.bookbagitem_list_item, bookBagItems); - lv.setAdapter(listAdapter); - - lv.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView arg0, View arg1, - int arg2, long arg3) { - - - } - - @Override - public void onNothingSelected(AdapterView arg0) { - // TODO Auto-generated method stub - - } - - }); - - getBookBagsItemsRunnable = new Runnable() { - - @Override - public void run() { - - ArrayList records = new ArrayList(); - ArrayList ids = new ArrayList(); - - for(int i=0;i { - private static final String tag = "BookbagArrayAdapter"; - - private TextView title; - private TextView author; - private Button remove; - - - private List records = new ArrayList(); - - public BookBagItemsArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public BookBagItem getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - final BookBagItem record = getItem(position); - - - //if it is the right type of view - if (row == null ) { - - Log.d(tag, "Starting XML Row Inflation ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.bookbagitem_list_item, parent, false); - Log.d(tag, "Successfully completed XML Row Inflation!"); - - } - - title = (TextView) row.findViewById(R.id.bookbagitem_title); - - author = (TextView) row.findViewById(R.id.bookbagitem_author); - - remove = (Button) row.findViewById(R.id.bookbagitem_remove_button); - - title.setText(record.recordInfo.title); - - author.setText(record.recordInfo.author); - - remove.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - - - Thread removeItem = new Thread(new Runnable() { - - @Override - public void run() { - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog = ProgressDialog.show(context, "Please wait", "Removing item"); - } - }); - - try { - accountAccess.removeBookbagItem(record.id); - } catch (SessionNotFoundException e) { - - try{ - if(accountAccess.authenticate()) - accountAccess.removeBookbagItem(record.id); - }catch(Exception e1){}; - - e.printStackTrace(); - } catch (NoNetworkAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoAccessToServer e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - - Thread getBookBags = new Thread(getBookBagsItemsRunnable); - setResult(RESULT_CODE_UPDATE); - - - bookBag.items.remove(record); - progressDialog = ProgressDialog.show(context, "Please wait", "retrieving bookbag data"); - getBookBags.start(); - - - } - }); - } - }); - - removeItem.start(); - } - }); - - return row; - } - } + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + accountAccess = AccountAccess.getAccountAccess(); + bookBag = (BookBag) getIntent().getSerializableExtra("bookBag"); + + context = this; + search = SearchCatalog + .getInstance((ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE)); + bookbag_name = (TextView) findViewById(R.id.bookbag_name); + delete_bookbag_button = (Button) findViewById(R.id.remove_bookbag); + bookbag_name.setText(bookBag.name); + delete_bookbag_button.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + final Thread deleteBookbag = new Thread(new Runnable() { + + @Override + public void run() { + + try { + accountAccess.deleteBookBag(bookBag.id); + } catch (SessionNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + setResult(RESULT_CODE_UPDATE); + finish(); + } + }); + } + }); + + Builder confirmationDialogBuilder = new AlertDialog.Builder( + context); + confirmationDialogBuilder.setMessage("Delete bookbag?"); + + confirmationDialogBuilder.setNegativeButton( + android.R.string.no, null); + confirmationDialogBuilder.setPositiveButton( + android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int which) { + + progressDialog = ProgressDialog.show(context, + "Please wait", "Deleting Bookbag"); + deleteBookbag.start(); + } + }); + + confirmationDialogBuilder.create().show(); + + } + }); + + lv = (ListView) findViewById(R.id.bookbagitem_list); + bookBagItems = new ArrayList(); + listAdapter = new BookBagItemsArrayAdapter(context, + R.layout.bookbagitem_list_item, bookBagItems); + lv.setAdapter(listAdapter); + + lv.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView arg0, View arg1, + int arg2, long arg3) { + + } + + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + + } + + }); + + getBookBagsItemsRunnable = new Runnable() { + + @Override + public void run() { + + ArrayList records = new ArrayList(); + ArrayList ids = new ArrayList(); + + for (int i = 0; i < bookBag.items.size(); i++) { + ids.add(bookBag.items.get(i).target_copy); + } + records = search.getRecordsInfo(ids); + + for (int i = 0; i < bookBag.items.size(); i++) { + bookBag.items.get(i).recordInfo = records.get(i); + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + + listAdapter.clear(); + + for (int i = 0; i < bookBag.items.size(); i++) + listAdapter.add(bookBag.items.get(i)); + + progressDialog.dismiss(); + + if (bookBagItems.size() == 0) + Toast.makeText(context, "No circ records", + Toast.LENGTH_LONG); + + listAdapter.notifyDataSetChanged(); + } + }); + + } + }; + + Thread getBookBags = new Thread(getBookBagsItemsRunnable); + + progressDialog = ProgressDialog.show(context, "Please wait", + "retrieving bookbag data"); + getBookBags.start(); + + } + + class BookBagItemsArrayAdapter extends ArrayAdapter { + private static final String tag = "BookbagArrayAdapter"; + + private TextView title; + private TextView author; + private Button remove; + + private List records = new ArrayList(); + + public BookBagItemsArrayAdapter(Context context, + int textViewResourceId, List objects) { + super(context, textViewResourceId, objects); + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public BookBagItem getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + final BookBagItem record = getItem(position); + + // if it is the right type of view + if (row == null) { + + Log.d(tag, "Starting XML Row Inflation ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.bookbagitem_list_item, parent, + false); + Log.d(tag, "Successfully completed XML Row Inflation!"); + + } + + title = (TextView) row.findViewById(R.id.bookbagitem_title); + + author = (TextView) row.findViewById(R.id.bookbagitem_author); + + remove = (Button) row.findViewById(R.id.bookbagitem_remove_button); + + title.setText(record.recordInfo.title); + + author.setText(record.recordInfo.author); + + remove.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + Thread removeItem = new Thread(new Runnable() { + + @Override + public void run() { + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog = ProgressDialog.show( + context, "Please wait", + "Removing item"); + } + }); + + try { + accountAccess.removeBookbagItem(record.id); + } catch (SessionNotFoundException e) { + + try { + if (accountAccess.authenticate()) + accountAccess + .removeBookbagItem(record.id); + } catch (Exception e1) { + } + ; + + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + + Thread getBookBags = new Thread( + getBookBagsItemsRunnable); + setResult(RESULT_CODE_UPDATE); + + bookBag.items.remove(record); + progressDialog = ProgressDialog.show( + context, "Please wait", + "retrieving bookbag data"); + getBookBags.start(); + + } + }); + } + }); + + removeItem.start(); + } + }); + + return row; + } + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagItem.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagItem.java index 899f61fa79..1522d3ff63 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagItem.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookBagItem.java @@ -5,19 +5,18 @@ import java.io.Serializable; import org.evergreen.android.searchCatalog.RecordInfo; import org.opensrf.util.OSRFObject; -public class BookBagItem implements Serializable{ - - public int target_copy; - - public int id; - - public RecordInfo recordInfo; - - public BookBagItem(OSRFObject cbrebi){ - - - this.target_copy = cbrebi.getInt("target_biblio_record_entry"); - this.id = cbrebi.getInt("id"); - - } +public class BookBagItem implements Serializable { + + public int target_copy; + + public int id; + + public RecordInfo recordInfo; + + public BookBagItem(OSRFObject cbrebi) { + + this.target_copy = cbrebi.getInt("target_biblio_record_entry"); + this.id = cbrebi.getInt("id"); + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookbagsListView.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookbagsListView.java index f47e0b294d..b806b420cb 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookbagsListView.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/bookbags/BookbagsListView.java @@ -33,280 +33,288 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; -public class BookbagsListView extends Activity{ - - private String TAG = "BookBags"; - - private AccountAccess accountAccess = null; - - private ListView lv; - - private BookBagsArrayAdapter listAdapter = null; - - private ArrayList bookBags = null; - - private Context context; - - private ProgressDialog progressDialog; - - private EditText bookbag_name; - - private Button create_bookbag; - - private Runnable getBookbagsRunnable; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - @Override - public void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - setContentView(R.layout.bookbag_list); - - //header portion actions +public class BookbagsListView extends Activity { + + private String TAG = "BookBags"; + + private AccountAccess accountAccess = null; + + private ListView lv; + + private BookBagsArrayAdapter listAdapter = null; + + private ArrayList bookBags = null; + + private Context context; + + private ProgressDialog progressDialog; + + private EditText bookbag_name; + + private Button create_bookbag; + + private Runnable getBookbagsRunnable; + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + @Override + public void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + + setContentView(R.layout.bookbag_list); + + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.bookbag_items_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - - context = this; - accountAccess = AccountAccess.getAccountAccess(); - - bookbag_name = (EditText) findViewById(R.id.bookbag_create_name); - create_bookbag = (Button) findViewById(R.id.bookbag_create_button); - lv = (ListView) findViewById(R.id.bookbag_list); - bookBags = new ArrayList(); - listAdapter = new BookBagsArrayAdapter(context, R.layout.bookbag_list_item, bookBags); - lv.setAdapter(listAdapter); - - lv.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView arg0, View arg1, - int position, long arg3) { - - - Toast.makeText(getApplicationContext(), "Text", Toast.LENGTH_LONG).show(); - } - - @Override - public void onNothingSelected(AdapterView arg0) { - // TODO Auto-generated method stub - - } - - }); - create_bookbag.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - final String name = bookbag_name.getText().toString(); - - Thread createBookbag = new Thread(new Runnable() { - @Override - public void run() { - - if(name.length()>1){ - try { - accountAccess.createBookbag(name); - } catch (SessionNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoNetworkAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoAccessToServer e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - } - }); - - Thread getBookBags = new Thread(getBookbagsRunnable); - getBookBags.start(); - } - - } - }); - - if(name.length()>1){ - progressDialog = ProgressDialog.show(context, "Please wait", "Creating Bookbag"); - createBookbag.start(); - } - else - Toast.makeText(context, "Bookbag name must be at least 2 characters long", Toast.LENGTH_SHORT).show(); - } - }); - - getBookbagsRunnable = new Runnable() { - - @Override - public void run() { - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog = ProgressDialog.show(context, "Plese wait", "retrieving Bookbag data"); - } - }); - - try { - bookBags = accountAccess.getBookbags(); - - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - - }catch (SessionNotFoundException e) { - //TODO other way? - try{ - if(accountAccess.authenticate()) - accountAccess.getBookbags(); - }catch(Exception eauth){ - System.out.println("Exception in reAuth"); - } - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - listAdapter.clear(); - for(int i=0;i { - private static final String tag = "BookbagArrayAdapter"; - - private TextView name; - private TextView items; - private CheckBox shared; - private Button detailsButton; - - private List records = new ArrayList(); - - public BookBagsArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public BookBag getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - final BookBag record = getItem(position); - - - //if it is the right type of view - if (row == null ) { - - Log.d(tag, "Starting XML Row Inflation ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.bookbag_list_item, parent, false); - Log.d(tag, "Successfully completed XML Row Inflation!"); - - } - - name = (TextView) row.findViewById(R.id.bookbag_name); - - items = (TextView) row.findViewById(R.id.bookbag_items); - - shared = (CheckBox) row.findViewById(R.id.bookbag_shared); - - detailsButton = (Button) row.findViewById(R.id.details_button); - - name.setText(record.name+""); - - items.setText(record.items.size() + ""); - - shared.setChecked(record.shared); - - detailsButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - Intent intent = new Intent(context,BookBagDetails.class); - intent.putExtra("bookBag", record); - startActivityForResult(intent, 0); - - } - }); - - return row; - } - } + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + context = this; + accountAccess = AccountAccess.getAccountAccess(); + + bookbag_name = (EditText) findViewById(R.id.bookbag_create_name); + create_bookbag = (Button) findViewById(R.id.bookbag_create_button); + lv = (ListView) findViewById(R.id.bookbag_list); + bookBags = new ArrayList(); + listAdapter = new BookBagsArrayAdapter(context, + R.layout.bookbag_list_item, bookBags); + lv.setAdapter(listAdapter); + + lv.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView arg0, View arg1, + int position, long arg3) { + + Toast.makeText(getApplicationContext(), "Text", + Toast.LENGTH_LONG).show(); + } + + @Override + public void onNothingSelected(AdapterView arg0) { + // TODO Auto-generated method stub + + } + + }); + create_bookbag.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + final String name = bookbag_name.getText().toString(); + + Thread createBookbag = new Thread(new Runnable() { + @Override + public void run() { + + if (name.length() > 1) { + try { + accountAccess.createBookbag(name); + } catch (SessionNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + } + }); + + Thread getBookBags = new Thread(getBookbagsRunnable); + getBookBags.start(); + } + + } + }); + + if (name.length() > 1) { + progressDialog = ProgressDialog.show(context, + "Please wait", "Creating Bookbag"); + createBookbag.start(); + } else + Toast.makeText(context, + "Bookbag name must be at least 2 characters long", + Toast.LENGTH_SHORT).show(); + } + }); + + getBookbagsRunnable = new Runnable() { + + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog = ProgressDialog.show(context, + "Plese wait", "retrieving Bookbag data"); + } + }); + + try { + bookBags = accountAccess.getBookbags(); + + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + + } catch (SessionNotFoundException e) { + // TODO other way? + try { + if (accountAccess.authenticate()) + accountAccess.getBookbags(); + } catch (Exception eauth) { + System.out.println("Exception in reAuth"); + } + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + listAdapter.clear(); + for (int i = 0; i < bookBags.size(); i++) + listAdapter.add(bookBags.get(i)); + + progressDialog.dismiss(); + + if (bookBags.size() == 0) + Toast.makeText(context, "No data", + Toast.LENGTH_LONG); + + listAdapter.notifyDataSetChanged(); + } + }); + + } + }; + + Thread getBookBags = new Thread(getBookbagsRunnable); + + if (accountAccess.isAuthenticated()) { + getBookBags.start(); + } else + Toast.makeText(context, + "You must be authenticated to retrieve circ records", + Toast.LENGTH_LONG); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + super.onActivityResult(requestCode, resultCode, data); + + switch (resultCode) { + + case BookBagDetails.RESULT_CODE_UPDATE: { + Thread getBookBags = new Thread(getBookbagsRunnable); + getBookBags.start(); + } + break; + + } + } + + class BookBagsArrayAdapter extends ArrayAdapter { + private static final String tag = "BookbagArrayAdapter"; + + private TextView name; + private TextView items; + private CheckBox shared; + private Button detailsButton; + + private List records = new ArrayList(); + + public BookBagsArrayAdapter(Context context, int textViewResourceId, + List objects) { + super(context, textViewResourceId, objects); + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public BookBag getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + final BookBag record = getItem(position); + + // if it is the right type of view + if (row == null) { + + Log.d(tag, "Starting XML Row Inflation ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.bookbag_list_item, parent, + false); + Log.d(tag, "Successfully completed XML Row Inflation!"); + + } + + name = (TextView) row.findViewById(R.id.bookbag_name); + + items = (TextView) row.findViewById(R.id.bookbag_items); + + shared = (CheckBox) row.findViewById(R.id.bookbag_shared); + + detailsButton = (Button) row.findViewById(R.id.details_button); + + name.setText(record.name + ""); + + items.setText(record.items.size() + ""); + + shared.setChecked(record.shared); + + detailsButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Intent intent = new Intent(context, BookBagDetails.class); + intent.putExtra("bookBag", record); + startActivityForResult(intent, 0); + + } + }); + + return row; + } + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/CircRecord.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/CircRecord.java index ae9d797e86..1e46430a91 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/CircRecord.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/CircRecord.java @@ -8,118 +8,121 @@ import org.evergreen.android.globals.GlobalConfigs; import org.opensrf.util.OSRFObject; /** - * This is a wrapper class that get the information out for a circ object + * This is a wrapper class that get the information out for a circ object + * * @author daniel - * + * */ public class CircRecord { - public static final int MVR_OBJ_TYPE = 1; - public static final int ACP_OBJ_TYPE = 2; - public static final int UNDEF_OBJ_TYPE = 0; - - public OSRFObject mvr = null; - - public OSRFObject acp = null; - - public OSRFObject circ = null; - - public int circ_info_type = UNDEF_OBJ_TYPE; - - public int circ_type; - - public static final int OUT = 0; - public static final int CLAIMS_RETURNED = 1; - public static final int LONG_OVERDUE = 2; - public static final int OVERDUE = 3; - public static final int LOST = 4; - - public int circ_id = -1; - - private Date circ_due_date = null; - - public CircRecord(OSRFObject circ, OSRFObject mvr, OSRFObject acp, int circ_type, int circ_id) { - - this.circ = circ; - - //one of the acp or mvr will be null this will determine the circ OSRFObject type - this.acp = acp; - this.mvr = mvr; - - if(this.acp != null) - this.circ_info_type = ACP_OBJ_TYPE; - - if(this.mvr != null) - this.circ_info_type = MVR_OBJ_TYPE; - - this.circ_type = circ_type; - this.circ_id = circ_id; - //parse due date - parseDate(circ); - } - - public CircRecord(OSRFObject circ,int circ_type, int circ_id){ - this.circ = circ; - this.circ_type = circ_type; - this.circ_id = circ_id; - //parse due date - parseDate(circ); - } - - public String getAuthor(){ - - String author = null; - - if(this.circ_info_type == MVR_OBJ_TYPE) - author = mvr.getString("author"); - if(this.circ_info_type == ACP_OBJ_TYPE) - author = acp.getString("dummy_author"); - - return author; - } - - - public String getDueDate(){ - - return circ_due_date.toLocaleString(); - } - - public Date getDueDateObject(){ - return circ_due_date; - } - - public String getTitle(){ - - String title = null; - - if(this.circ_info_type == MVR_OBJ_TYPE) - title = mvr.getString("title"); - if(this.circ_info_type == ACP_OBJ_TYPE) - title = acp.getString("dummy_title"); - - return title; - } - - public Integer getRenewals(){ - - if(circ != null) - return circ.getInt("renewal_remaining"); - - return null; - } - - public Integer getTargetCopy(){ - if(circ != null) - return circ.getInt("target_copy"); - - return null; - } - - private void parseDate(OSRFObject circ){ - - this.circ_due_date = GlobalConfigs.parseDate(circ.getString("due_date")); - System.out.println(this.circ_due_date); - - } - + public static final int MVR_OBJ_TYPE = 1; + public static final int ACP_OBJ_TYPE = 2; + public static final int UNDEF_OBJ_TYPE = 0; + + public OSRFObject mvr = null; + + public OSRFObject acp = null; + + public OSRFObject circ = null; + + public int circ_info_type = UNDEF_OBJ_TYPE; + + public int circ_type; + + public static final int OUT = 0; + public static final int CLAIMS_RETURNED = 1; + public static final int LONG_OVERDUE = 2; + public static final int OVERDUE = 3; + public static final int LOST = 4; + + public int circ_id = -1; + + private Date circ_due_date = null; + + public CircRecord(OSRFObject circ, OSRFObject mvr, OSRFObject acp, + int circ_type, int circ_id) { + + this.circ = circ; + + // one of the acp or mvr will be null this will determine the circ + // OSRFObject type + this.acp = acp; + this.mvr = mvr; + + if (this.acp != null) + this.circ_info_type = ACP_OBJ_TYPE; + + if (this.mvr != null) + this.circ_info_type = MVR_OBJ_TYPE; + + this.circ_type = circ_type; + this.circ_id = circ_id; + // parse due date + parseDate(circ); + } + + public CircRecord(OSRFObject circ, int circ_type, int circ_id) { + this.circ = circ; + this.circ_type = circ_type; + this.circ_id = circ_id; + // parse due date + parseDate(circ); + } + + public String getAuthor() { + + String author = null; + + if (this.circ_info_type == MVR_OBJ_TYPE) + author = mvr.getString("author"); + if (this.circ_info_type == ACP_OBJ_TYPE) + author = acp.getString("dummy_author"); + + return author; + } + + public String getDueDate() { + + return circ_due_date.toLocaleString(); + } + + public Date getDueDateObject() { + return circ_due_date; + } + + public String getTitle() { + + String title = null; + + if (this.circ_info_type == MVR_OBJ_TYPE) + title = mvr.getString("title"); + if (this.circ_info_type == ACP_OBJ_TYPE) + title = acp.getString("dummy_title"); + + return title; + } + + public Integer getRenewals() { + + if (circ != null) + return circ.getInt("renewal_remaining"); + + return null; + } + + public Integer getTargetCopy() { + if (circ != null) + return circ.getInt("target_copy"); + + return null; + } + + private void parseDate(OSRFObject circ) { + + this.circ_due_date = GlobalConfigs + .parseDate(circ.getString("due_date")); + System.out.println(this.circ_due_date); + + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/ItemsCheckOutListView.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/ItemsCheckOutListView.java index bfb8e6ced5..e4f86b606e 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/ItemsCheckOutListView.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/checkout/ItemsCheckOutListView.java @@ -41,357 +41,356 @@ import android.widget.Toast; public class ItemsCheckOutListView extends Activity { - private String TAG = "ItemsCheckOutListView"; + private String TAG = "ItemsCheckOutListView"; - private AccountAccess accountAccess = null; - - private ListView lv; + private AccountAccess accountAccess = null; - private CheckOutArrayAdapter listAdapter = null; + private ListView lv; - private ArrayList circRecords = null; + private CheckOutArrayAdapter listAdapter = null; - private Context context; + private ArrayList circRecords = null; - private ProgressDialog progressDialog; + private Context context; - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private TextView itemsNo; + private ProgressDialog progressDialog; - private Activity thisActivity; - - private TextView overdueItems; - - private Date currentDate; - - @Override - public void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - thisActivity = this; - setContentView(R.layout.checkout_list); - setTitle("Checkout items"); - - currentDate = new Date(System.currentTimeMillis()); - - // header portion actions - homeButton = (Button) findViewById(R.id.library_logo); - myAccountButton = (Button) findViewById(R.id.my_account_button); - headerTitle = (TextView) findViewById(R.id.header_title); - headerTitle.setText(R.string.checkout_items_title); - - myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(), - AccountScreenDashboard.class); - startActivity(intent); - } - }); + private Button homeButton; - homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(), - SearchCatalogListView.class); - startActivity(intent); - } - }); - // end header portion actions + private Button myAccountButton; - context = this; - itemsNo = (TextView) findViewById(R.id.checkout_items_number); - overdueItems = (TextView) findViewById(R.id.checkout_items_overdue); - accountAccess = AccountAccess.getAccountAccess(); - lv = (ListView) findViewById(R.id.checkout_items_list); - circRecords = new ArrayList(); - listAdapter = new CheckOutArrayAdapter(context, - R.layout.checkout_list_item, circRecords); - lv.setAdapter(listAdapter); + private TextView headerTitle; - Thread getCirc = new Thread(new Runnable() { - - @Override - public void run() { + private TextView itemsNo; - try { - circRecords = accountAccess.getItemsCheckedOut(); - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); + private Activity thisActivity; - } catch (SessionNotFoundException e) { - // TODO other way? - try { + private TextView overdueItems; - Log.d(TAG, "REAUTH " + "in process"); + private Date currentDate; - if (accountAccess.authenticate()) - circRecords = accountAccess.getItemsCheckedOut(); - } catch (Exception eauth) { - System.out.println("Exception in reAuth"); - } - } + @Override + public void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); - runOnUiThread(new Runnable() { + thisActivity = this; + setContentView(R.layout.checkout_list); + setTitle("Checkout items"); - @Override - public void run() { - for (int i = 0; i < circRecords.size(); i++) - listAdapter.add(circRecords.get(i)); - - itemsNo.setText(" " + circRecords.size() + " "); - - int overdueNo = 0; - //find overdue items - - for(int i=0;i { - private static final String tag = "CheckoutArrayAdapter"; - - private TextView recordTitle; - private TextView recordAuthor; - private TextView recordDueDate; - private TextView recordRenewals; - private TextView renewButton; - - private List records = new ArrayList(); - - public CheckOutArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public CircRecord getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - final CircRecord record = getItem(position); - - if (record == null) { - Log.d(tag, "Starting XML view more infaltion ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.search_result_footer_view, - parent, false); - Log.d(tag, "Successfully completed XML view more Inflation!"); - - } else { - - // if it is the right type of view - if (row == null) { - - Log.d(tag, "Starting XML Row Inflation ... "); - LayoutInflater inflater = (LayoutInflater) this - .getContext().getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.checkout_list_item, parent, - false); - Log.d(tag, "Successfully completed XML Row Inflation!"); - - } - - // Get reference to TextView - title - recordTitle = (TextView) row - .findViewById(R.id.checkout_record_title); - - // Get reference to TextView - author - recordAuthor = (TextView) row - .findViewById(R.id.checkout_record_author); - - // Get reference to TextView - record Publisher date+publisher - recordDueDate = (TextView) row - .findViewById(R.id.checkout_due_date); - - renewButton = (TextView) row.findViewById(R.id.renew_button); - - renewButton.setText("renew : " + record.getRenewals()); - - renewButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - - Thread renew = new Thread(new Runnable() { - - @Override - public void run() { - boolean refresh = true; - AccountAccess ac = AccountAccess - .getAccountAccess(); - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog = new ProgressDialog( - context); - progressDialog - .setMessage("Renew item please wait."); - progressDialog.show(); - } - }); - - try { - ac.renewCirc(record.getTargetCopy()); - } catch (MaxRenewalsException e1) { - runOnUiThread(new Runnable() { - - @Override - public void run() { - progressDialog.dismiss(); - Toast.makeText(context, - "Max renewals reached", - Toast.LENGTH_LONG).show(); - } - }); - - refresh = false; - }catch (ServerErrorMessage error) { - - final String errorMessage = error.message; - runOnUiThread(new Runnable() { - - @Override - public void run() { - progressDialog.dismiss(); - Toast.makeText(context, - errorMessage, - Toast.LENGTH_LONG).show(); - } - }); - }catch (SessionNotFoundException e1) { - try { - if (accountAccess.authenticate()) - ac.renewCirc(record.getTargetCopy()); - } catch (Exception eauth) { - System.out - .println("Exception in reAuth"); - } - } catch (NoNetworkAccessException e1) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e1) { - Utils.showServerNotAvailableDialog(context); - } - - if (refresh) { - - try { - circRecords = accountAccess - .getItemsCheckedOut(); - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - - } catch (SessionNotFoundException e) { - // TODO other way? - try { - if (accountAccess.authenticate()) - circRecords = accountAccess - .getItemsCheckedOut(); - } catch (Exception eauth) { - System.out - .println("Exception in reAuth"); - } - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - listAdapter.clear(); - for (int i = 0; i < circRecords - .size(); i++) { - listAdapter.add(circRecords - .get(i)); - } - - progressDialog.dismiss(); - listAdapter.notifyDataSetChanged(); - } - }); - } - } - }); - - renew.start(); - } - }); - - // set text - System.out.println("Row" + record.getTitle() + " " - + record.getAuthor() + " " + record.getDueDate() + " " - + record.getRenewals()); - recordTitle.setText(record.getTitle()); - recordAuthor.setText(record.getAuthor()); - recordDueDate.setText(record.getDueDate()); - } - - return row; - } - } + currentDate = new Date(System.currentTimeMillis()); + + // header portion actions + homeButton = (Button) findViewById(R.id.library_logo); + myAccountButton = (Button) findViewById(R.id.my_account_button); + headerTitle = (TextView) findViewById(R.id.header_title); + headerTitle.setText(R.string.checkout_items_title); + + myAccountButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + + homeButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + context = this; + itemsNo = (TextView) findViewById(R.id.checkout_items_number); + overdueItems = (TextView) findViewById(R.id.checkout_items_overdue); + accountAccess = AccountAccess.getAccountAccess(); + lv = (ListView) findViewById(R.id.checkout_items_list); + circRecords = new ArrayList(); + listAdapter = new CheckOutArrayAdapter(context, + R.layout.checkout_list_item, circRecords); + lv.setAdapter(listAdapter); + + Thread getCirc = new Thread(new Runnable() { + + @Override + public void run() { + + try { + circRecords = accountAccess.getItemsCheckedOut(); + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + + } catch (SessionNotFoundException e) { + // TODO other way? + try { + + Log.d(TAG, "REAUTH " + "in process"); + + if (accountAccess.authenticate()) + circRecords = accountAccess.getItemsCheckedOut(); + } catch (Exception eauth) { + System.out.println("Exception in reAuth"); + } + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + for (int i = 0; i < circRecords.size(); i++) + listAdapter.add(circRecords.get(i)); + + itemsNo.setText(" " + circRecords.size() + " "); + + int overdueNo = 0; + // find overdue items + + for (int i = 0; i < circRecords.size(); i++) { + CircRecord circ = circRecords.get(i); + + if (circ.getDueDateObject().compareTo(currentDate) < 0) + overdueNo++; + } + + overdueItems.setText(" " + overdueNo); + + progressDialog.dismiss(); + + if (circRecords.size() == 0) + Toast.makeText(context, "No circ records", + Toast.LENGTH_LONG); + + listAdapter.notifyDataSetChanged(); + } + }); + } + }); + + if (accountAccess.isAuthenticated()) { + progressDialog = new ProgressDialog(context); + progressDialog.setMessage("Please wait while retrieving circ data"); + progressDialog.show(); + getCirc.start(); + + } else + Toast.makeText(context, + "You must be authenticated to retrieve circ records", + Toast.LENGTH_LONG); + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater menuInflater = getMenuInflater(); + menuInflater.inflate(R.menu.checkout_menu, menu); + return super.onCreateOptionsMenu(menu); + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + + return super.onOptionsItemSelected(item); + } + + class CheckOutArrayAdapter extends ArrayAdapter { + private static final String tag = "CheckoutArrayAdapter"; + + private TextView recordTitle; + private TextView recordAuthor; + private TextView recordDueDate; + private TextView recordRenewals; + private TextView renewButton; + + private List records = new ArrayList(); + + public CheckOutArrayAdapter(Context context, int textViewResourceId, + List objects) { + super(context, textViewResourceId, objects); + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public CircRecord getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + final CircRecord record = getItem(position); + + if (record == null) { + Log.d(tag, "Starting XML view more infaltion ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.search_result_footer_view, + parent, false); + Log.d(tag, "Successfully completed XML view more Inflation!"); + + } else { + + // if it is the right type of view + if (row == null) { + + Log.d(tag, "Starting XML Row Inflation ... "); + LayoutInflater inflater = (LayoutInflater) this + .getContext().getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.checkout_list_item, parent, + false); + Log.d(tag, "Successfully completed XML Row Inflation!"); + + } + + // Get reference to TextView - title + recordTitle = (TextView) row + .findViewById(R.id.checkout_record_title); + + // Get reference to TextView - author + recordAuthor = (TextView) row + .findViewById(R.id.checkout_record_author); + + // Get reference to TextView - record Publisher date+publisher + recordDueDate = (TextView) row + .findViewById(R.id.checkout_due_date); + + renewButton = (TextView) row.findViewById(R.id.renew_button); + + renewButton.setText("renew : " + record.getRenewals()); + + renewButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + Thread renew = new Thread(new Runnable() { + + @Override + public void run() { + boolean refresh = true; + AccountAccess ac = AccountAccess + .getAccountAccess(); + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog = new ProgressDialog( + context); + progressDialog + .setMessage("Renew item please wait."); + progressDialog.show(); + } + }); + + try { + ac.renewCirc(record.getTargetCopy()); + } catch (MaxRenewalsException e1) { + runOnUiThread(new Runnable() { + + @Override + public void run() { + progressDialog.dismiss(); + Toast.makeText(context, + "Max renewals reached", + Toast.LENGTH_LONG).show(); + } + }); + + refresh = false; + } catch (ServerErrorMessage error) { + + final String errorMessage = error.message; + runOnUiThread(new Runnable() { + + @Override + public void run() { + progressDialog.dismiss(); + Toast.makeText(context, + errorMessage, + Toast.LENGTH_LONG).show(); + } + }); + } catch (SessionNotFoundException e1) { + try { + if (accountAccess.authenticate()) + ac.renewCirc(record.getTargetCopy()); + } catch (Exception eauth) { + System.out + .println("Exception in reAuth"); + } + } catch (NoNetworkAccessException e1) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e1) { + Utils.showServerNotAvailableDialog(context); + } + + if (refresh) { + + try { + circRecords = accountAccess + .getItemsCheckedOut(); + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + + } catch (SessionNotFoundException e) { + // TODO other way? + try { + if (accountAccess.authenticate()) + circRecords = accountAccess + .getItemsCheckedOut(); + } catch (Exception eauth) { + System.out + .println("Exception in reAuth"); + } + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + listAdapter.clear(); + for (int i = 0; i < circRecords + .size(); i++) { + listAdapter.add(circRecords + .get(i)); + } + + progressDialog.dismiss(); + listAdapter.notifyDataSetChanged(); + } + }); + } + } + }); + + renew.start(); + } + }); + + // set text + System.out.println("Row" + record.getTitle() + " " + + record.getAuthor() + " " + record.getDueDate() + " " + + record.getRenewals()); + recordTitle.setText(record.getTitle()); + recordAuthor.setText(record.getAuthor()); + recordDueDate.setText(record.getDueDate()); + } + + return row; + } + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesActivity.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesActivity.java index 743733acda..d60e671bc8 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesActivity.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesActivity.java @@ -29,206 +29,206 @@ import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; -public class FinesActivity extends Activity{ - - - private TextView total_owned; - - private TextView total_paid; - - private TextView balance_owed; - - private ListView lv; - - private Runnable getFinesInfo; - - private AccountAccess ac; - - private ProgressDialog progressDialog; - - private OverdueMaterialsArrayAdapter listAdapter; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private Context context; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.fines); - - //header portion actions +public class FinesActivity extends Activity { + + private TextView total_owned; + + private TextView total_paid; + + private TextView balance_owed; + + private ListView lv; + + private Runnable getFinesInfo; + + private AccountAccess ac; + + private ProgressDialog progressDialog; + + private OverdueMaterialsArrayAdapter listAdapter; + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + private Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.fines); + + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.fines_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - - lv = (ListView) findViewById(R.id.fines_overdue_materials_list); - - total_owned = (TextView) findViewById(R.id.fines_total_owned); - total_paid = (TextView) findViewById(R.id.fines_total_paid); - balance_owed = (TextView) findViewById(R.id.fined_balance_owed); - context = this; - - ac = AccountAccess.getAccountAccess(); - - - - ArrayList finesRecords = new ArrayList(); - listAdapter = new OverdueMaterialsArrayAdapter(context, R.layout.fines_list_item,finesRecords); - lv.setAdapter(listAdapter); - - - progressDialog = ProgressDialog.show(this, null, "Retrieving fines"); - - getFinesInfo = new Runnable() { - @Override - public void run() { - - float[] finesR = null; - try { - finesR = ac.getFinesSummary(); - } catch (SessionNotFoundException e) { - try{ - if(ac.authenticate()) - finesR = ac.getFinesSummary(); - }catch(Exception e1){} - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - } - - ArrayList frecords = null; - try { - frecords = ac.getTransactions(); - } catch (SessionNotFoundException e) { - - try{ - if(ac.authenticate()) - frecords = ac.getTransactions(); - }catch(Exception e1){} - - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - } - - final ArrayList finesRecords = frecords; - final float[] fines = finesR; - runOnUiThread(new Runnable() { - @Override - public void run() { - - listAdapter.clear(); - - for(int i=0;i { - private static final String tag = "CheckoutArrayAdapter"; - - private TextView fineTitle; - private TextView fineAuthor; - private TextView fineBalanceOwed; - private TextView fineStatus; - - private List records = new ArrayList(); - - public OverdueMaterialsArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public FinesRecord getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - final FinesRecord record = getItem(position); - - if(row == null){ - - Log.d(tag, "Starting XML view more infaltion ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.fines_list_item, parent, false); - Log.d(tag, "Successfully completed XML view more Inflation!"); - - - } - // Get reference to TextView - title - fineTitle = (TextView) row.findViewById(R.id.fines_title); - - // Get reference to TextView author - fineAuthor = (TextView) row.findViewById(R.id.fines_author); - - //Get hold status - fineBalanceOwed = (TextView) row.findViewById(R.id.fines_balance_owed); - - fineStatus = (TextView) row.findViewById(R.id.fines_status); - //set text - - - //set raw information - fineTitle.setText(record.title); - fineAuthor.setText(record.author); - fineBalanceOwed.setText(record.balance_owed); - //status.setText(record.getHoldStatus()); - fineStatus.setText(record.getStatus()); - - if(record.getStatus().equals("returned")){ - fineStatus.setTextColor(Color.argb(255, 0, 255, 0)); - } - else - fineStatus.setTextColor(Color.argb(255, 255, 0, 0)); - - return row; - } + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + lv = (ListView) findViewById(R.id.fines_overdue_materials_list); + + total_owned = (TextView) findViewById(R.id.fines_total_owned); + total_paid = (TextView) findViewById(R.id.fines_total_paid); + balance_owed = (TextView) findViewById(R.id.fined_balance_owed); + context = this; + + ac = AccountAccess.getAccountAccess(); + + ArrayList finesRecords = new ArrayList(); + listAdapter = new OverdueMaterialsArrayAdapter(context, + R.layout.fines_list_item, finesRecords); + lv.setAdapter(listAdapter); + + progressDialog = ProgressDialog.show(this, null, "Retrieving fines"); + + getFinesInfo = new Runnable() { + @Override + public void run() { + + float[] finesR = null; + try { + finesR = ac.getFinesSummary(); + } catch (SessionNotFoundException e) { + try { + if (ac.authenticate()) + finesR = ac.getFinesSummary(); + } catch (Exception e1) { + } + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + } + + ArrayList frecords = null; + try { + frecords = ac.getTransactions(); + } catch (SessionNotFoundException e) { + + try { + if (ac.authenticate()) + frecords = ac.getTransactions(); + } catch (Exception e1) { + } + + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + } + + final ArrayList finesRecords = frecords; + final float[] fines = finesR; + runOnUiThread(new Runnable() { + @Override + public void run() { + + listAdapter.clear(); + + for (int i = 0; i < finesRecords.size(); i++) + listAdapter.add(finesRecords.get(i)); + + listAdapter.notifyDataSetChanged(); + + total_owned.setText(fines[0] + ""); + total_paid.setText(fines[1] + ""); + balance_owed.setText(fines[2] + ""); + progressDialog.dismiss(); + } + }); + } + }; + + Thread getFinesTh = new Thread(getFinesInfo); + getFinesTh.start(); + } + + class OverdueMaterialsArrayAdapter extends ArrayAdapter { + private static final String tag = "CheckoutArrayAdapter"; + + private TextView fineTitle; + private TextView fineAuthor; + private TextView fineBalanceOwed; + private TextView fineStatus; + + private List records = new ArrayList(); + + public OverdueMaterialsArrayAdapter(Context context, + int textViewResourceId, List objects) { + super(context, textViewResourceId, objects); + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public FinesRecord getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + final FinesRecord record = getItem(position); + + if (row == null) { + + Log.d(tag, "Starting XML view more infaltion ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.fines_list_item, parent, false); + Log.d(tag, "Successfully completed XML view more Inflation!"); + + } + // Get reference to TextView - title + fineTitle = (TextView) row.findViewById(R.id.fines_title); + + // Get reference to TextView author + fineAuthor = (TextView) row.findViewById(R.id.fines_author); + + // Get hold status + fineBalanceOwed = (TextView) row + .findViewById(R.id.fines_balance_owed); + + fineStatus = (TextView) row.findViewById(R.id.fines_status); + // set text + + // set raw information + fineTitle.setText(record.title); + fineAuthor.setText(record.author); + fineBalanceOwed.setText(record.balance_owed); + // status.setText(record.getHoldStatus()); + fineStatus.setText(record.getStatus()); + + if (record.getStatus().equals("returned")) { + fineStatus.setTextColor(Color.argb(255, 0, 255, 0)); + } else + fineStatus.setTextColor(Color.argb(255, 255, 0, 0)); + + return row; + } } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesRecord.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesRecord.java index bfcabda69e..ce64a42746 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesRecord.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/fines/FinesRecord.java @@ -7,61 +7,58 @@ import org.opensrf.util.OSRFObject; public class FinesRecord { - public String title; - - public String author; - - public Date checkoutDate; - - public Date dueDate; - - public Date dateReturned; - - public String balance_owed; - - private Date checkin_time; - - // types are grocery and circulation - private int type; - - public static int FINE_GROCERY_TYPE = 1; - public static int FINE_CIRCULATION = 2; - - public FinesRecord(OSRFObject circ, OSRFObject mvr_record, OSRFObject mbts_transaction){ - - - if(mbts_transaction.get("xact_type").toString().equals("circulation")){ - - title = mvr_record.getString("title"); - author = mvr_record.getString("author"); - - if(circ.get("checkin_time") != null){ - checkin_time = GlobalConfigs.parseDate(circ.getString("checkin_time")); - } - else - checkin_time = null; - - } - else - { - //grocery - title = "Grocery billing"; - author = mbts_transaction.getString("last_billing_note"); - - } - - balance_owed = mbts_transaction.getString("total_owed"); - - - } - - //if returned or fines still acumulating - public String getStatus(){ - - if(checkin_time != null) - return "returned"; - - return "fines accruing"; - - } + public String title; + + public String author; + + public Date checkoutDate; + + public Date dueDate; + + public Date dateReturned; + + public String balance_owed; + + private Date checkin_time; + + // types are grocery and circulation + private int type; + + public static int FINE_GROCERY_TYPE = 1; + public static int FINE_CIRCULATION = 2; + + public FinesRecord(OSRFObject circ, OSRFObject mvr_record, + OSRFObject mbts_transaction) { + + if (mbts_transaction.get("xact_type").toString().equals("circulation")) { + + title = mvr_record.getString("title"); + author = mvr_record.getString("author"); + + if (circ.get("checkin_time") != null) { + checkin_time = GlobalConfigs.parseDate(circ + .getString("checkin_time")); + } else + checkin_time = null; + + } else { + // grocery + title = "Grocery billing"; + author = mbts_transaction.getString("last_billing_note"); + + } + + balance_owed = mbts_transaction.getString("total_owed"); + + } + + // if returned or fines still acumulating + public String getStatus() { + + if (checkin_time != null) + return "returned"; + + return "fines accruing"; + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldDetails.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldDetails.java index d385e0e68e..22d5b848cf 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldDetails.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldDetails.java @@ -43,403 +43,414 @@ import android.widget.Toast; public class HoldDetails extends Activity { - public static final int RESULT_CODE_DELETE_HOLD = 5; + public static final int RESULT_CODE_DELETE_HOLD = 5; - public static final int RESULT_CODE_UPDATE_HOLD = 6; - - public static final int RESULT_CODE_CANCEL = 7; + public static final int RESULT_CODE_UPDATE_HOLD = 6; - private TextView recipient; + public static final int RESULT_CODE_CANCEL = 7; - private TextView title; + private TextView recipient; - private TextView author; + private TextView title; - private TextView physical_description; + private TextView author; - private TextView screen_title; + private TextView physical_description; - private AccountAccess accountAccess; + private TextView screen_title; - private EditText expiration_date; + private AccountAccess accountAccess; - private Button updateHold; + private EditText expiration_date; - private Button cancelHold; + private Button updateHold; - private Button back; + private Button cancelHold; - private EditText phone_number; + private Button back; - private CheckBox phone_notification; + private EditText phone_number; - private CheckBox email_notification; + private CheckBox phone_notification; - private DatePickerDialog datePicker = null; + private CheckBox email_notification; - private CheckBox suspendHold; + private DatePickerDialog datePicker = null; - private Spinner orgSelector; + private CheckBox suspendHold; - private DatePickerDialog thaw_datePicker = null; + private Spinner orgSelector; - private EditText thaw_date_edittext; + private DatePickerDialog thaw_datePicker = null; - private Date expire_date = null; - - private Date thaw_date = null; - - private Context context; - - private int selectedOrgPos = 0; - - public Runnable updateHoldRunnable; - - private ProgressDialog progressDialog; - - private GlobalConfigs globalConfigs; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - context = this; - setContentView(R.layout.hold_details); - globalConfigs = GlobalConfigs.getGlobalConfigs(this); - - - homeButton = (Button) findViewById(R.id.library_logo); - myAccountButton = (Button) findViewById(R.id.my_account_button); - headerTitle = (TextView) findViewById(R.id.header_title); - headerTitle.setText(R.string.hold_details_title); - homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(), AccountScreenDashboard.class); - startActivity(intent); - } - }); - - - final HoldRecord record = (HoldRecord) getIntent() - .getSerializableExtra("holdRecord"); - - System.out.println("Record " + record + " " + record.title + " " - + record.ahr); - - accountAccess = AccountAccess.getAccountAccess(); - - recipient = (TextView) findViewById(R.id.hold_recipient); - title = (TextView) findViewById(R.id.hold_title); - author = (TextView) findViewById(R.id.hold_author); - physical_description = (TextView) findViewById(R.id.hold_physical_description); - cancelHold = (Button) findViewById(R.id.cancel_hold_button); - updateHold = (Button) findViewById(R.id.update_hold_button); - back = (Button) findViewById(R.id.back_button); - - phone_number = (EditText) findViewById(R.id.hold_contact_telephone); - phone_notification = (CheckBox) findViewById(R.id.hold_enable_phone_notification); - email_notification = (CheckBox) findViewById(R.id.hold_enable_email_notification); - suspendHold = (CheckBox) findViewById(R.id.hold_suspend_hold); - - orgSelector = (Spinner) findViewById(R.id.hold_pickup_location); - expiration_date = (EditText) findViewById(R.id.hold_expiration_date); - thaw_date_edittext = (EditText) findViewById(R.id.hold_thaw_date); - - recipient.setText(accountAccess.userName); - title.setText(record.title); - author.setText(record.author); - if (record.recordInfo != null) - physical_description - .setText(record.recordInfo.physical_description); - - // set record info - phone_notification.setChecked(record.phone_notification); - email_notification.setChecked(record.email_notification); - suspendHold.setChecked(record.suspended); - - if (record.thaw_date != null) { - thaw_date = record.thaw_date; - thaw_date_edittext.setText(DateFormat.format("MMMM dd, yyyy", - thaw_date)); - } - if (record.expire_time != null) { - expire_date = record.expire_time; - expiration_date.setText(DateFormat.format("MMMM dd, yyyy", - expire_date)); - } - - // hide edit text - if( record.thaw_date == null) - disableView(thaw_date_edittext); - - if(!record.phone_notification) - disableView(phone_number); - - System.out.println(record.title + " " + record.author); - - back.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - cancelHold.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - - Builder confirmationDialogBuilder = new AlertDialog.Builder( - context); - confirmationDialogBuilder - .setMessage(R.string.cancel_hold_dialog_message); - - confirmationDialogBuilder.setNegativeButton( - android.R.string.no, null); - confirmationDialogBuilder.setPositiveButton( - android.R.string.yes, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, - int which) { - - System.out.println("Remove hold with id" - + record.ahr.getInt("id")); - - progressDialog = ProgressDialog.show(context, "Please wait", "Canceling hold"); - Thread cancelHoldThread = new Thread(new Runnable() { - - @Override - public void run() { - - try { - accountAccess.cancelHold(record.ahr); - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - - }catch (SessionNotFoundException e) { - //TODO other way? - try{ - if(accountAccess.authenticate()) - accountAccess.cancelHold(record.ahr); - }catch(Exception eauth){ - System.out.println("Exception in reAuth"); - } - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - setResult(RESULT_CODE_DELETE_HOLD); - - finish(); - } - }); - } - }); - cancelHoldThread.start(); - - } - }); - confirmationDialogBuilder.create().show(); - - } - }); - - updateHoldRunnable = new Runnable() { - @Override - public void run() { - // update new values - String expire_date_s = null; - String thaw_date_s = null; - if (expire_date != null) - expire_date_s = GlobalConfigs.getStringDate(expire_date); - if (thaw_date != null) - thaw_date_s = GlobalConfigs.getStringDate(thaw_date); - - try { - accountAccess.updateHold(record.ahr, selectedOrgPos, - email_notification.isChecked(), phone_notification - .isChecked(), - phone_number.getText().toString(), suspendHold - .isChecked(), expire_date_s, thaw_date_s); - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - - }catch (SessionNotFoundException e) { - //TODO other way? - try{ - if(accountAccess.authenticate()) - accountAccess.updateHold(record.ahr, selectedOrgPos, - email_notification.isChecked(), phone_notification - .isChecked(), - phone_number.getText().toString(), suspendHold - .isChecked(), expire_date_s, thaw_date_s); - }catch(Exception eauth){ - System.out.println("Exception in reAuth"); - } - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - Toast.makeText(context, "Hold updated", Toast.LENGTH_SHORT); - setResult(RESULT_CODE_UPDATE_HOLD); - finish(); - } - }); - } - }; - - updateHold.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - progressDialog = ProgressDialog.show(context, "Please wait", "Updating hold"); - Thread updateHoldThread = new Thread(updateHoldRunnable); - updateHoldThread.start(); - } - }); - - phone_notification - .setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - - if (isChecked) { - enableView(phone_number); - } else - disableView(phone_number); - } - }); - - suspendHold.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - - if (isChecked) { - enableView(thaw_date_edittext); - } else { - disableView(thaw_date_edittext); - } - } - }); - Calendar cal = Calendar.getInstance(); - - datePicker = new DatePickerDialog(this, - new DatePickerDialog.OnDateSetListener() { - - public void onDateSet(DatePicker view, int year, - int monthOfYear, int dayOfMonth) { - - Date chosenDate = new Date(year - 1900, monthOfYear, - dayOfMonth); - expire_date = chosenDate; - CharSequence strDate = DateFormat.format( - "MMMM dd, yyyy", chosenDate); - expiration_date.setText(strDate); - // set current date - } - }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), - cal.get(Calendar.DAY_OF_MONTH)); - - expiration_date.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - datePicker.show(); - } - }); - - thaw_datePicker = new DatePickerDialog(this, - new DatePickerDialog.OnDateSetListener() { - - public void onDateSet(DatePicker view, int year, - int monthOfYear, int dayOfMonth) { - - Date chosenDate = new Date(year - 1900, monthOfYear, - dayOfMonth); - thaw_date = chosenDate; - CharSequence strDate = DateFormat.format( - "MMMM dd, yyyy", chosenDate); - thaw_date_edittext.setText(strDate); - // set current date - } - }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), - cal.get(Calendar.DAY_OF_MONTH)); - - thaw_date_edittext.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - thaw_datePicker.show(); - } - }); - - ArrayList list = new ArrayList(); - for (int i = 0; i < globalConfigs.organisations.size(); i++) { - list.add(globalConfigs.organisations.get(i).padding - + globalConfigs.organisations.get(i).name); - - if (globalConfigs.organisations.get(i).id == record.pickup_lib) - selectedOrgPos = i; - } - ArrayAdapter adapter = new ArrayAdapter(this, - R.layout.spinner_layout, list); - orgSelector.setAdapter(adapter); - - orgSelector.setSelection(selectedOrgPos); - - orgSelector.setOnItemSelectedListener(new OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView arg0, View arg1, int ID, - long arg3) { - - selectedOrgPos = ID; - - } - - public void onNothingSelected(android.widget.AdapterView arg0) { - } - }); - } - - public void disableView(View view) { - - // view.setFocusable(false); - view.setFocusable(false); - - view.setBackgroundColor(Color.argb(255, 100, 100, 100)); - // view.setVisibility(View.INVISIBLE); - } - - public void enableView(View view) { - // view.setVisibility(View.VISIBLE); - - view.setFocusableInTouchMode(true); - - view.setBackgroundColor(Color.argb(255, 255, 255, 255)); - } + private EditText thaw_date_edittext; + + private Date expire_date = null; + + private Date thaw_date = null; + + private Context context; + + private int selectedOrgPos = 0; + + public Runnable updateHoldRunnable; + + private ProgressDialog progressDialog; + + private GlobalConfigs globalConfigs; + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + context = this; + setContentView(R.layout.hold_details); + globalConfigs = GlobalConfigs.getGlobalConfigs(this); + + homeButton = (Button) findViewById(R.id.library_logo); + myAccountButton = (Button) findViewById(R.id.my_account_button); + headerTitle = (TextView) findViewById(R.id.header_title); + headerTitle.setText(R.string.hold_details_title); + homeButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + myAccountButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + + final HoldRecord record = (HoldRecord) getIntent() + .getSerializableExtra("holdRecord"); + + System.out.println("Record " + record + " " + record.title + " " + + record.ahr); + + accountAccess = AccountAccess.getAccountAccess(); + + recipient = (TextView) findViewById(R.id.hold_recipient); + title = (TextView) findViewById(R.id.hold_title); + author = (TextView) findViewById(R.id.hold_author); + physical_description = (TextView) findViewById(R.id.hold_physical_description); + cancelHold = (Button) findViewById(R.id.cancel_hold_button); + updateHold = (Button) findViewById(R.id.update_hold_button); + back = (Button) findViewById(R.id.back_button); + + phone_number = (EditText) findViewById(R.id.hold_contact_telephone); + phone_notification = (CheckBox) findViewById(R.id.hold_enable_phone_notification); + email_notification = (CheckBox) findViewById(R.id.hold_enable_email_notification); + suspendHold = (CheckBox) findViewById(R.id.hold_suspend_hold); + + orgSelector = (Spinner) findViewById(R.id.hold_pickup_location); + expiration_date = (EditText) findViewById(R.id.hold_expiration_date); + thaw_date_edittext = (EditText) findViewById(R.id.hold_thaw_date); + + recipient.setText(accountAccess.userName); + title.setText(record.title); + author.setText(record.author); + if (record.recordInfo != null) + physical_description + .setText(record.recordInfo.physical_description); + + // set record info + phone_notification.setChecked(record.phone_notification); + email_notification.setChecked(record.email_notification); + suspendHold.setChecked(record.suspended); + + if (record.thaw_date != null) { + thaw_date = record.thaw_date; + thaw_date_edittext.setText(DateFormat.format("MMMM dd, yyyy", + thaw_date)); + } + if (record.expire_time != null) { + expire_date = record.expire_time; + expiration_date.setText(DateFormat.format("MMMM dd, yyyy", + expire_date)); + } + + // hide edit text + if (record.thaw_date == null) + disableView(thaw_date_edittext); + + if (!record.phone_notification) + disableView(phone_number); + + System.out.println(record.title + " " + record.author); + + back.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + + cancelHold.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + Builder confirmationDialogBuilder = new AlertDialog.Builder( + context); + confirmationDialogBuilder + .setMessage(R.string.cancel_hold_dialog_message); + + confirmationDialogBuilder.setNegativeButton( + android.R.string.no, null); + confirmationDialogBuilder.setPositiveButton( + android.R.string.yes, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, + int which) { + + System.out.println("Remove hold with id" + + record.ahr.getInt("id")); + + progressDialog = ProgressDialog.show(context, + "Please wait", "Canceling hold"); + Thread cancelHoldThread = new Thread( + new Runnable() { + + @Override + public void run() { + + try { + accountAccess + .cancelHold(record.ahr); + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + + } catch (SessionNotFoundException e) { + // TODO other way? + try { + if (accountAccess + .authenticate()) + accountAccess + .cancelHold(record.ahr); + } catch (Exception eauth) { + System.out + .println("Exception in reAuth"); + } + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog + .dismiss(); + setResult(RESULT_CODE_DELETE_HOLD); + + finish(); + } + }); + } + }); + cancelHoldThread.start(); + + } + }); + confirmationDialogBuilder.create().show(); + + } + }); + + updateHoldRunnable = new Runnable() { + @Override + public void run() { + // update new values + String expire_date_s = null; + String thaw_date_s = null; + if (expire_date != null) + expire_date_s = GlobalConfigs.getStringDate(expire_date); + if (thaw_date != null) + thaw_date_s = GlobalConfigs.getStringDate(thaw_date); + + try { + accountAccess.updateHold(record.ahr, selectedOrgPos, + email_notification.isChecked(), phone_notification + .isChecked(), phone_number.getText() + .toString(), suspendHold.isChecked(), + expire_date_s, thaw_date_s); + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + + } catch (SessionNotFoundException e) { + // TODO other way? + try { + if (accountAccess.authenticate()) + accountAccess.updateHold(record.ahr, + selectedOrgPos, + email_notification.isChecked(), + phone_notification.isChecked(), + phone_number.getText().toString(), + suspendHold.isChecked(), expire_date_s, + thaw_date_s); + } catch (Exception eauth) { + System.out.println("Exception in reAuth"); + } + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + Toast.makeText(context, "Hold updated", + Toast.LENGTH_SHORT); + setResult(RESULT_CODE_UPDATE_HOLD); + finish(); + } + }); + } + }; + + updateHold.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + progressDialog = ProgressDialog.show(context, "Please wait", + "Updating hold"); + Thread updateHoldThread = new Thread(updateHoldRunnable); + updateHoldThread.start(); + } + }); + + phone_notification + .setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + + if (isChecked) { + enableView(phone_number); + } else + disableView(phone_number); + } + }); + + suspendHold.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + + if (isChecked) { + enableView(thaw_date_edittext); + } else { + disableView(thaw_date_edittext); + } + } + }); + Calendar cal = Calendar.getInstance(); + + datePicker = new DatePickerDialog(this, + new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, + int monthOfYear, int dayOfMonth) { + + Date chosenDate = new Date(year - 1900, monthOfYear, + dayOfMonth); + expire_date = chosenDate; + CharSequence strDate = DateFormat.format( + "MMMM dd, yyyy", chosenDate); + expiration_date.setText(strDate); + // set current date + } + }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), + cal.get(Calendar.DAY_OF_MONTH)); + + expiration_date.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + datePicker.show(); + } + }); + + thaw_datePicker = new DatePickerDialog(this, + new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, + int monthOfYear, int dayOfMonth) { + + Date chosenDate = new Date(year - 1900, monthOfYear, + dayOfMonth); + thaw_date = chosenDate; + CharSequence strDate = DateFormat.format( + "MMMM dd, yyyy", chosenDate); + thaw_date_edittext.setText(strDate); + // set current date + } + }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), + cal.get(Calendar.DAY_OF_MONTH)); + + thaw_date_edittext.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + thaw_datePicker.show(); + } + }); + + ArrayList list = new ArrayList(); + for (int i = 0; i < globalConfigs.organisations.size(); i++) { + list.add(globalConfigs.organisations.get(i).padding + + globalConfigs.organisations.get(i).name); + + if (globalConfigs.organisations.get(i).id == record.pickup_lib) + selectedOrgPos = i; + } + ArrayAdapter adapter = new ArrayAdapter(this, + R.layout.spinner_layout, list); + orgSelector.setAdapter(adapter); + + orgSelector.setSelection(selectedOrgPos); + + orgSelector.setOnItemSelectedListener(new OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView arg0, View arg1, int ID, + long arg3) { + + selectedOrgPos = ID; + + } + + public void onNothingSelected(android.widget.AdapterView arg0) { + } + }); + } + + public void disableView(View view) { + + // view.setFocusable(false); + view.setFocusable(false); + + view.setBackgroundColor(Color.argb(255, 100, 100, 100)); + // view.setVisibility(View.INVISIBLE); + } + + public void enableView(View view) { + // view.setVisibility(View.VISIBLE); + + view.setFocusableInTouchMode(true); + + view.setBackgroundColor(Color.argb(255, 255, 255, 255)); + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldRecord.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldRecord.java index c6ac35feb4..8480d4f724 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldRecord.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldRecord.java @@ -8,122 +8,117 @@ import org.evergreen.android.globals.GlobalConfigs; import org.evergreen.android.searchCatalog.RecordInfo; import org.opensrf.util.OSRFObject; -public class HoldRecord implements Serializable{ - - //metarecord - public static final int M = 0; - //record - public static final int T = 1; - //volume - public static final int V = 2; - //issuance - public static final int I = 3; - //copy - public static final int C = 4; - //part - public static final int P = 5; - - private Integer requestLibID = null; - - private Integer pickupLibID = null; - - public Integer holdType = null; - //id for target object - public Integer target = null; - public Date expire_time = null; - - public String title = null; - - public String author = null; - - public String types_of_resource; - - /* Hold status - * holdStatus == 4 => AVAILABLE - * holdStatus == 3 => WAITING - * holdStatus <= 3 => TRANSIT - */ - - //only for P types - public String part_label = null; - - public Integer status = null; - - public Boolean active = null; - - //must also be serializable - public OSRFObject ahr = null; - //record info with more etails - public RecordInfo recordInfo = null; - - - public boolean email_notification = false; - - public boolean phone_notification = false; - - public boolean suspended = false; - - public Date thaw_date; - - public int pickup_lib; - - public HoldRecord(OSRFObject ahr){ - - this.target = ahr.getInt("target"); - String type = ahr.getString("hold_type"); - - this.ahr = ahr; - - if(type.equals("M")){ - holdType = M; - }else - if(type.equals("T")){ - holdType = T; - }else - if(type.equals("V")){ - holdType = V; - }else - if(type.equals("I")){ - holdType = I; - }else - if(type.equals("C")){ - holdType = C; - }else - if(type.equals("P")) - holdType = P; - - this.expire_time = GlobalConfigs.parseDate(ahr.getString("expire_time")); - - this.thaw_date = GlobalConfigs.parseDate(ahr.getString("thaw_date")); - String res = ahr.getString("email_notify"); - - if(res.equals("t")) - this.email_notification = true; - res = ahr.getString("phone_notify"); - if(res.equals("t")) - this.phone_notification = true; - - res = ahr.getString("frozen"); - if(res.equals("t")) - this.suspended = true; - pickup_lib = ahr.getInt("pickup_lib"); - - } - //based on status integer field retreive hold status in text - public String getHoldStatus(){ - - String holdStatus = ""; - - if(holdType == 7) - return "Suspended"; - if(holdType == 4) - return "Available"; - if(holdType == 3) - return "Waiting"; - if(holdType < 3) - return "Transit"; - - return holdStatus; - } - +public class HoldRecord implements Serializable { + + // metarecord + public static final int M = 0; + // record + public static final int T = 1; + // volume + public static final int V = 2; + // issuance + public static final int I = 3; + // copy + public static final int C = 4; + // part + public static final int P = 5; + + private Integer requestLibID = null; + + private Integer pickupLibID = null; + + public Integer holdType = null; + // id for target object + public Integer target = null; + public Date expire_time = null; + + public String title = null; + + public String author = null; + + public String types_of_resource; + + /* + * Hold status holdStatus == 4 => AVAILABLE holdStatus == 3 => WAITING + * holdStatus <= 3 => TRANSIT + */ + + // only for P types + public String part_label = null; + + public Integer status = null; + + public Boolean active = null; + + // must also be serializable + public OSRFObject ahr = null; + // record info with more etails + public RecordInfo recordInfo = null; + + public boolean email_notification = false; + + public boolean phone_notification = false; + + public boolean suspended = false; + + public Date thaw_date; + + public int pickup_lib; + + public HoldRecord(OSRFObject ahr) { + + this.target = ahr.getInt("target"); + String type = ahr.getString("hold_type"); + + this.ahr = ahr; + + if (type.equals("M")) { + holdType = M; + } else if (type.equals("T")) { + holdType = T; + } else if (type.equals("V")) { + holdType = V; + } else if (type.equals("I")) { + holdType = I; + } else if (type.equals("C")) { + holdType = C; + } else if (type.equals("P")) + holdType = P; + + this.expire_time = GlobalConfigs + .parseDate(ahr.getString("expire_time")); + + this.thaw_date = GlobalConfigs.parseDate(ahr.getString("thaw_date")); + String res = ahr.getString("email_notify"); + + if (res.equals("t")) + this.email_notification = true; + res = ahr.getString("phone_notify"); + if (res.equals("t")) + this.phone_notification = true; + + res = ahr.getString("frozen"); + if (res.equals("t")) + this.suspended = true; + pickup_lib = ahr.getInt("pickup_lib"); + + } + + // based on status integer field retreive hold status in text + public String getHoldStatus() { + + String holdStatus = ""; + + if (holdType == 7) + return "Suspended"; + if (holdType == 4) + return "Available"; + if (holdType == 3) + return "Waiting"; + if (holdType < 3) + return "Transit"; + + return holdStatus; + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldsListView.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldsListView.java index 47f13d9de7..4369f6604c 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldsListView.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/HoldsListView.java @@ -35,249 +35,258 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; -public class HoldsListView extends Activity{ - - private String TAG = "HoldsListView"; - - private AccountAccess accountAccess = null; - - private ListView lv; - - private HoldsArrayAdapter listAdapter = null; - - private List holdRecords = null; - - private Context context; - - Runnable getHoldsRunnable= null; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private TextView holdsNoText; - - private ProgressDialog progressDialog; - - private ImageDownloader imageDownloader; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.holds_list); - - //header portion actions +public class HoldsListView extends Activity { + + private String TAG = "HoldsListView"; + + private AccountAccess accountAccess = null; + + private ListView lv; + + private HoldsArrayAdapter listAdapter = null; + + private List holdRecords = null; + + private Context context; + + Runnable getHoldsRunnable = null; + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + private TextView holdsNoText; + + private ProgressDialog progressDialog; + + private ImageDownloader imageDownloader; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.holds_list); + + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.hold_items_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - - holdsNoText = (TextView)findViewById(R.id.holds_number); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + holdsNoText = (TextView) findViewById(R.id.holds_number); + imageDownloader = new ImageDownloader(40, 40, false); - - lv = (ListView)findViewById(R.id.holds_item_list); - context = this; - accountAccess = AccountAccess.getAccountAccess(); - - holdRecords = new ArrayList(); - listAdapter = new HoldsArrayAdapter(context, R.layout.holds_list_item, holdRecords); - lv.setAdapter(listAdapter); - - getHoldsRunnable = new Runnable() { - @Override - public void run() { - - try { - holdRecords = accountAccess.getHolds(); - } catch (SessionNotFoundException e) { - //TODO other way? - try{ - if(accountAccess.authenticate()) - holdRecords = accountAccess.getHolds(); - }catch(Exception eauth){ - System.out.println("Exception in reAuth"); - } - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - listAdapter.clear(); - - for(int i=0;i arg0, View arg1, int position, - long arg3) { - HoldRecord record = (HoldRecord) lv.getItemAtPosition(position); - - Intent intent = new Intent(getApplicationContext(),HoldDetails.class); - - intent.putExtra("holdRecord", record); - - //doae not matter request code, only result code - startActivityForResult(intent, 0); - } - }); - } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - // TODO Auto-generated method stub - super.onActivityResult(requestCode, resultCode, data); - - switch(resultCode){ - - case HoldDetails.RESULT_CODE_CANCEL : { - //nothing - Log.d(TAG, "Do nothing"); - }break; - - case HoldDetails.RESULT_CODE_DELETE_HOLD : { - //refresh ui - progressDialog = new ProgressDialog(context); - progressDialog.setMessage("Loading holds"); - progressDialog.show(); - //thread to retrieve holds - Thread getHoldsThread = new Thread(getHoldsRunnable); - getHoldsThread.start(); - Log.d(TAG, "Update on delete hold"); - }break; - - case HoldDetails.RESULT_CODE_UPDATE_HOLD : { - //refresh ui - progressDialog = new ProgressDialog(context); - progressDialog.setMessage("Loading holds"); - progressDialog.show(); - //thread to retrieve holds - Thread getHoldsThread = new Thread(getHoldsRunnable); - getHoldsThread.start(); - Log.d(TAG, "Update on update hold"); - }break; - - } - } - - class HoldsArrayAdapter extends ArrayAdapter { - private static final String tag = "CheckoutArrayAdapter"; - - private TextView holdTitle; - private TextView holdAuthor; - private TextView status; - private ImageView hold_icon; - - private List records = new ArrayList(); - - public HoldsArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public HoldRecord getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - final HoldRecord record = getItem(position); - - if(row == null){ - - Log.d(tag, "Starting XML view more infaltion ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.holds_list_item, parent, false); - Log.d(tag, "Successfully completed XML view more Inflation!"); - - - } - - hold_icon = (ImageView) row.findViewById(R.id.hold_resource_icon); - - // Get reference to TextView - title - holdTitle = (TextView) row.findViewById(R.id.hold_title); - - // Get reference to TextView author - holdAuthor = (TextView) row.findViewById(R.id.hold_author); - - //Get hold status - status = (TextView) row.findViewById(R.id.hold_status); - - //set text - String imageResourceHref = GlobalConfigs.httpAddress + GlobalConfigs.hold_icon_address +record.types_of_resource +".jpg"; - - if(imageResourceHref.contains(" ")){ - imageResourceHref = imageResourceHref.replace(" ", "%20"); - } - - imageDownloader.download(imageResourceHref, hold_icon); - - System.out.println("Image " + imageResourceHref + " Row " + record.title + " " + record.author + " " + record.getHoldStatus() ); - //set raw information - holdTitle.setText(record.title); - holdAuthor.setText(record.author); - status.setText(record.getHoldStatus()); - - - return row; - } + + lv = (ListView) findViewById(R.id.holds_item_list); + context = this; + accountAccess = AccountAccess.getAccountAccess(); + + holdRecords = new ArrayList(); + listAdapter = new HoldsArrayAdapter(context, R.layout.holds_list_item, + holdRecords); + lv.setAdapter(listAdapter); + + getHoldsRunnable = new Runnable() { + @Override + public void run() { + + try { + holdRecords = accountAccess.getHolds(); + } catch (SessionNotFoundException e) { + // TODO other way? + try { + if (accountAccess.authenticate()) + holdRecords = accountAccess.getHolds(); + } catch (Exception eauth) { + System.out.println("Exception in reAuth"); + } + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + listAdapter.clear(); + + for (int i = 0; i < holdRecords.size(); i++) + listAdapter.add(holdRecords.get(i)); + + holdsNoText.setText(" " + listAdapter.getCount()); + progressDialog.dismiss(); + listAdapter.notifyDataSetChanged(); + + } + }); + } + }; + + if (accountAccess.isAuthenticated()) { + progressDialog = new ProgressDialog(context); + progressDialog.setMessage("Loading holds"); + progressDialog.show(); + + // thread to retrieve holds + Thread getHoldsThread = new Thread(getHoldsRunnable); + getHoldsThread.start(); + + } else + Toast.makeText(context, + "You must be authenticated to retrieve circ records", + Toast.LENGTH_LONG); + + lv.setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(AdapterView arg0, View arg1, + int position, long arg3) { + HoldRecord record = (HoldRecord) lv.getItemAtPosition(position); + + Intent intent = new Intent(getApplicationContext(), + HoldDetails.class); + + intent.putExtra("holdRecord", record); + + // doae not matter request code, only result code + startActivityForResult(intent, 0); + } + }); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + super.onActivityResult(requestCode, resultCode, data); + + switch (resultCode) { + + case HoldDetails.RESULT_CODE_CANCEL: { + // nothing + Log.d(TAG, "Do nothing"); + } + break; + + case HoldDetails.RESULT_CODE_DELETE_HOLD: { + // refresh ui + progressDialog = new ProgressDialog(context); + progressDialog.setMessage("Loading holds"); + progressDialog.show(); + // thread to retrieve holds + Thread getHoldsThread = new Thread(getHoldsRunnable); + getHoldsThread.start(); + Log.d(TAG, "Update on delete hold"); + } + break; + + case HoldDetails.RESULT_CODE_UPDATE_HOLD: { + // refresh ui + progressDialog = new ProgressDialog(context); + progressDialog.setMessage("Loading holds"); + progressDialog.show(); + // thread to retrieve holds + Thread getHoldsThread = new Thread(getHoldsRunnable); + getHoldsThread.start(); + Log.d(TAG, "Update on update hold"); + } + break; + + } + } + + class HoldsArrayAdapter extends ArrayAdapter { + private static final String tag = "CheckoutArrayAdapter"; + + private TextView holdTitle; + private TextView holdAuthor; + private TextView status; + private ImageView hold_icon; + + private List records = new ArrayList(); + + public HoldsArrayAdapter(Context context, int textViewResourceId, + List objects) { + super(context, textViewResourceId, objects); + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public HoldRecord getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + final HoldRecord record = getItem(position); + + if (row == null) { + + Log.d(tag, "Starting XML view more infaltion ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.holds_list_item, parent, false); + Log.d(tag, "Successfully completed XML view more Inflation!"); + + } + + hold_icon = (ImageView) row.findViewById(R.id.hold_resource_icon); + + // Get reference to TextView - title + holdTitle = (TextView) row.findViewById(R.id.hold_title); + + // Get reference to TextView author + holdAuthor = (TextView) row.findViewById(R.id.hold_author); + + // Get hold status + status = (TextView) row.findViewById(R.id.hold_status); + + // set text + String imageResourceHref = GlobalConfigs.httpAddress + + GlobalConfigs.hold_icon_address + + record.types_of_resource + ".jpg"; + + if (imageResourceHref.contains(" ")) { + imageResourceHref = imageResourceHref.replace(" ", "%20"); + } + + imageDownloader.download(imageResourceHref, hold_icon); + + System.out.println("Image " + imageResourceHref + " Row " + + record.title + " " + record.author + " " + + record.getHoldStatus()); + // set raw information + holdTitle.setText(record.title); + holdAuthor.setText(record.author); + status.setText(record.getHoldStatus()); + + return row; + } } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/PlaceHold.java b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/PlaceHold.java index edd58e13ac..65e5201863 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/PlaceHold.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/accountAccess/holds/PlaceHold.java @@ -39,320 +39,342 @@ import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; -public class PlaceHold extends Activity{ - - - private TextView recipient; - - private TextView title; - - private TextView author; - - private TextView physical_description; - - private TextView screen_title; - - private AccountAccess accountAccess; - - private EditText expiration_date; - - private EditText phone_number; - - private CheckBox phone_notification; - - private CheckBox email_notification; - - private Button placeHold; - - private Button cancel; - - private CheckBox suspendHold; - - private Spinner orgSelector; - - private DatePickerDialog datePicker = null; - - private DatePickerDialog thaw_datePicker = null; - - private EditText thaw_date_edittext; - - private Date expire_date = null; - - private Date thaw_date = null; - - private Runnable placeHoldRunnable; - - private GlobalConfigs globalConfigs = null; - - private int selectedOrgPos = 0; - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private ProgressDialog progressDialog; - - - private Context context; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.place_hold); - globalConfigs = GlobalConfigs.getGlobalConfigs(this); - RecordInfo record = (RecordInfo) getIntent().getSerializableExtra("recordInfo"); - - homeButton = (Button) findViewById(R.id.library_logo); - myAccountButton = (Button) findViewById(R.id.my_account_button); - headerTitle = (TextView) findViewById(R.id.header_title); - headerTitle.setText(R.string.hold_place_title); - - myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - - homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - - context = this; - - accountAccess = AccountAccess.getAccountAccess(); - - recipient = (TextView) findViewById(R.id.hold_recipient); - title = (TextView) findViewById(R.id.hold_title); - author = (TextView) findViewById(R.id.hold_author); - physical_description = (TextView) findViewById(R.id.hold_physical_description); - screen_title = (TextView) findViewById(R.id.header_title); - cancel = (Button) findViewById(R.id.cancel_hold); - placeHold = (Button) findViewById(R.id.place_hold); - expiration_date = (EditText) findViewById(R.id.hold_expiration_date); - phone_notification = (CheckBox) findViewById(R.id.hold_enable_phone_notification); - phone_number= (EditText) findViewById(R.id.hold_contact_telephone); - email_notification = (CheckBox) findViewById(R.id.hold_enable_email_notification); - suspendHold = (CheckBox) findViewById(R.id.hold_suspend_hold); - orgSelector = (Spinner) findViewById(R.id.hold_pickup_location); - thaw_date_edittext = (EditText) findViewById(R.id.hold_thaw_date); - screen_title.setText("Place Hold"); - - recipient.setText(accountAccess.userName); - title.setText(record.title); - author.setText(record.author); - physical_description.setText(record.physical_description); - - //hide edit text - disableView(thaw_date_edittext); - disableView(phone_number); - - cancel.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - final Integer record_id = record.doc_id; - - placeHoldRunnable = new Runnable() { - - @Override - public void run() { - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog = ProgressDialog.show(context, "Please wait", "Placing hold"); - } - }); - //TODO verify hold possible - - //accountAccess.getHoldPreCreateInfo(record_id, 4); - //accountAccess.isHoldPossible(4, record_id); - - - String expire_date_s = null; - String thaw_date_s = null; - if (expire_date != null) - expire_date_s = GlobalConfigs.getStringDate(expire_date); - if (thaw_date != null) - thaw_date_s = GlobalConfigs.getStringDate(thaw_date); - - System.out.println("date expire: " + expire_date_s + " " + expire_date); - int selectedOrgID = -1; - if(globalConfigs.organisations.size() > selectedOrgPos) - selectedOrgID = globalConfigs.organisations.get(selectedOrgPos).id; - - - - String[] stringResponse = new String[]{"false"}; - try { - stringResponse = accountAccess.createHold(record_id,selectedOrgID,email_notification.isChecked(),phone_notification.isChecked(),phone_number.getText().toString(),suspendHold.isChecked(),expire_date_s,thaw_date_s); - } catch (SessionNotFoundException e) { - - try{ - if(accountAccess.authenticate()) - stringResponse = accountAccess.createHold(record_id,selectedOrgID,email_notification.isChecked(),phone_notification.isChecked(),phone_number.getText().toString(),suspendHold.isChecked(),expire_date_s,thaw_date_s); - }catch(Exception e1){} - - } catch (NoNetworkAccessException e) { - Utils.showNetworkNotAvailableDialog(context); - } catch (NoAccessToServer e) { - Utils.showServerNotAvailableDialog(context); - } - - final String[] holdPlaced = stringResponse; - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - - if(holdPlaced[0].equals("true")){ - Toast.makeText(context, "Hold Succesfully placed", Toast.LENGTH_LONG).show(); - finish(); - } - else - Toast.makeText(context, "Error in placing hold : " + holdPlaced[2], Toast.LENGTH_LONG).show(); - - - } - }); - } - }; - - placeHold.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - Thread placeholdThread = new Thread(placeHoldRunnable); - placeholdThread.start(); - } - }); - - phone_notification.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - - if(isChecked){ - enableView(phone_number); - } - else - disableView(phone_number); - } - }); - - suspendHold.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - - if(isChecked){ - enableView(thaw_date_edittext); - }else - { - disableView(thaw_date_edittext); - } - } - }); - - Calendar cal = Calendar.getInstance(); - - datePicker = new DatePickerDialog(this, - new DatePickerDialog.OnDateSetListener() { - - public void onDateSet(DatePicker view, int year, - int monthOfYear, int dayOfMonth) - { - - - Date chosenDate = new Date(year-1900, monthOfYear,dayOfMonth); - expire_date = chosenDate; - CharSequence strDate = DateFormat.format("MMMM dd, yyyy", chosenDate); - expiration_date.setText(strDate); - //set current date - }}, cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); - - expiration_date.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - datePicker.show(); - } - }); - - thaw_datePicker = new DatePickerDialog(this, - new DatePickerDialog.OnDateSetListener() { - - public void onDateSet(DatePicker view, int year, - int monthOfYear, int dayOfMonth) - { - - - Date chosenDate = new Date(year-1900, monthOfYear,dayOfMonth); - thaw_date = chosenDate; - CharSequence strDate = DateFormat.format("MMMM dd, yyyy", chosenDate); - thaw_date_edittext.setText(strDate); - //set current date - }}, cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); - - thaw_date_edittext.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - thaw_datePicker.show(); - } - }); - - ArrayList list = new ArrayList(); - for(int i=0;i selectedOrgPos) + selectedOrgID = globalConfigs.organisations + .get(selectedOrgPos).id; + + String[] stringResponse = new String[] { "false" }; + try { + stringResponse = accountAccess.createHold(record_id, + selectedOrgID, email_notification.isChecked(), + phone_notification.isChecked(), phone_number + .getText().toString(), suspendHold + .isChecked(), expire_date_s, thaw_date_s); + } catch (SessionNotFoundException e) { + + try { + if (accountAccess.authenticate()) + stringResponse = accountAccess.createHold( + record_id, selectedOrgID, + email_notification.isChecked(), + phone_notification.isChecked(), + phone_number.getText().toString(), + suspendHold.isChecked(), expire_date_s, + thaw_date_s); + } catch (Exception e1) { + } + + } catch (NoNetworkAccessException e) { + Utils.showNetworkNotAvailableDialog(context); + } catch (NoAccessToServer e) { + Utils.showServerNotAvailableDialog(context); + } + + final String[] holdPlaced = stringResponse; + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + + if (holdPlaced[0].equals("true")) { + Toast.makeText(context, "Hold Succesfully placed", + Toast.LENGTH_LONG).show(); + finish(); + } else + Toast.makeText(context, + "Error in placing hold : " + holdPlaced[2], + Toast.LENGTH_LONG).show(); + + } + }); + } + }; + + placeHold.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + Thread placeholdThread = new Thread(placeHoldRunnable); + placeholdThread.start(); + } + }); + + phone_notification + .setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + + if (isChecked) { + enableView(phone_number); + } else + disableView(phone_number); + } + }); + + suspendHold.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + + if (isChecked) { + enableView(thaw_date_edittext); + } else { + disableView(thaw_date_edittext); + } + } + }); + + Calendar cal = Calendar.getInstance(); + + datePicker = new DatePickerDialog(this, + new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, + int monthOfYear, int dayOfMonth) { + + Date chosenDate = new Date(year - 1900, monthOfYear, + dayOfMonth); + expire_date = chosenDate; + CharSequence strDate = DateFormat.format( + "MMMM dd, yyyy", chosenDate); + expiration_date.setText(strDate); + // set current date + } + }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), + cal.get(Calendar.DAY_OF_MONTH)); + + expiration_date.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + datePicker.show(); + } + }); + + thaw_datePicker = new DatePickerDialog(this, + new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, + int monthOfYear, int dayOfMonth) { + + Date chosenDate = new Date(year - 1900, monthOfYear, + dayOfMonth); + thaw_date = chosenDate; + CharSequence strDate = DateFormat.format( + "MMMM dd, yyyy", chosenDate); + thaw_date_edittext.setText(strDate); + // set current date + } + }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), + cal.get(Calendar.DAY_OF_MONTH)); + + thaw_date_edittext.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + thaw_datePicker.show(); + } + }); + + ArrayList list = new ArrayList(); + for (int i = 0; i < globalConfigs.organisations.size(); i++) { + list.add(globalConfigs.organisations.get(i).padding + + globalConfigs.organisations.get(i).name); + + if (globalConfigs.organisations.get(i).level - 1 == 0) + selectedOrgPos = i; } - ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,list); + ArrayAdapter adapter = new ArrayAdapter(this, + android.R.layout.simple_spinner_item, list); orgSelector.setAdapter(adapter); - + orgSelector.setSelection(selectedOrgPos); - + orgSelector.setOnItemSelectedListener(new OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView arg0, View arg1, - int ID, long arg3) { - - selectedOrgPos = ID; - - } - - public void onNothingSelected(android.widget.AdapterView arg0) { - } + @Override + public void onItemSelected(AdapterView arg0, View arg1, int ID, + long arg3) { + + selectedOrgPos = ID; + + } + + public void onNothingSelected(android.widget.AdapterView arg0) { + } }); - } - public void disableView(View view){ - - //view.setFocusable(false); - view.setFocusable(false); - - view.setBackgroundColor(Color.argb(255, 100, 100, 100)); - //view.setVisibility(View.INVISIBLE); - } - - public void enableView(View view){ - //view.setVisibility(View.VISIBLE); - - view.setFocusableInTouchMode(true); - - view.setBackgroundColor(Color.argb(255, 255,255,255)); - } - + } + + public void disableView(View view) { + + // view.setFocusable(false); + view.setFocusable(false); + + view.setBackgroundColor(Color.argb(255, 100, 100, 100)); + // view.setVisibility(View.INVISIBLE); + } + + public void enableView(View view) { + // view.setVisibility(View.VISIBLE); + + view.setFocusableInTouchMode(true); + + view.setBackgroundColor(Color.argb(255, 255, 255, 255)); + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/database/DatabaseManager.java b/Open-ILS/src/Android/src/org/evergreen/android/database/DatabaseManager.java index b5ea337848..a6d186cf22 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/database/DatabaseManager.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/database/DatabaseManager.java @@ -1,4 +1,3 @@ - package org.evergreen.android.database; import java.util.HashMap; @@ -18,71 +17,83 @@ import android.util.Log; */ public class DatabaseManager { - public static String TAG = "DatabaseManager"; - - /** The DATABASE NAME. */ - public static final String DATABASE_NAME = "evergreen.db"; + public static String TAG = "DatabaseManager"; + + /** The DATABASE NAME. */ + public static final String DATABASE_NAME = "evergreen.db"; - /** The DATABASE VERSION. */ - public static final int DATABASE_VERSION = 1; + /** The DATABASE VERSION. */ + public static final int DATABASE_VERSION = 1; - /** The db helper. */ - private static DefaultDatabaseHelper dbHelper = null; + /** The db helper. */ + private static DefaultDatabaseHelper dbHelper = null; - /** The singleton reflection managers map. */ - @SuppressWarnings("rawtypes") - private static HashMap rmMap = new HashMap(); + /** The singleton reflection managers map. */ + @SuppressWarnings("rawtypes") + private static HashMap rmMap = new HashMap(); - @SuppressWarnings("rawtypes") - private static HashMap daoMap = new HashMap(); + @SuppressWarnings("rawtypes") + private static HashMap daoMap = new HashMap(); - /** - * Gets the Singleton database helper. - * - * @return the dB helper - */ - public static DefaultDatabaseHelper getDBHelper(Context context) { - if (dbHelper == null) - dbHelper = new DefaultDatabaseHelper(context, DATABASE_NAME, DATABASE_VERSION, new Class[] { NotificationAlert.class}, new String[] { - NotificationAlert.tableName}); - return dbHelper; - } + /** + * Gets the Singleton database helper. + * + * @return the dB helper + */ + public static DefaultDatabaseHelper getDBHelper(Context context) { + if (dbHelper == null) + dbHelper = new DefaultDatabaseHelper(context, DATABASE_NAME, + DATABASE_VERSION, new Class[] { NotificationAlert.class }, + new String[] { NotificationAlert.tableName }); + return dbHelper; + } - /** - * Gets a singleton instance of a reflection manager corresponding to a class. - * - * @param cls the class - * @return the reflection manager instance - */ - public static ReflectionManager getReflectionManagerInstance(Class cls) { - if (rmMap.containsKey(cls)) - return rmMap.get(cls); - try { - ReflectionManager rm = new ReflectionManager(cls); - rmMap.put(cls, rm); - return rm; - } catch (IllegalClassStructureException ex) { - ex.printStackTrace(); - Log.d(TAG, "Illegal Class Structure for class " + cls + ": " + ex.getMessage()); - return null; - } - } + /** + * Gets a singleton instance of a reflection manager corresponding to a + * class. + * + * @param cls + * the class + * @return the reflection manager instance + */ + public static ReflectionManager getReflectionManagerInstance( + Class cls) { + if (rmMap.containsKey(cls)) + return rmMap.get(cls); + try { + ReflectionManager rm = new ReflectionManager(cls); + rmMap.put(cls, rm); + return rm; + } catch (IllegalClassStructureException ex) { + ex.printStackTrace(); + Log.d(TAG, + "Illegal Class Structure for class " + cls + ": " + + ex.getMessage()); + return null; + } + } - /** - * Gets a singleton instance of a DefaultDAO object corresponding to a class. - * - * @param the generic type - * @param cls the class - * @param tableName the table name - * @return the DAO instance - */ - @SuppressWarnings("unchecked") - public static synchronized DefaultDAO getDAOInstance(Context context, Class cls, String tableName) { - if (daoMap.containsKey(cls)) - return daoMap.get(cls); - DefaultDAO dao = new DefaultDAO(cls, DatabaseManager.getDBHelper(context), - DatabaseManager.getReflectionManagerInstance(cls), tableName); - daoMap.put(cls, dao); - return dao; - } + /** + * Gets a singleton instance of a DefaultDAO object corresponding to a + * class. + * + * @param + * the generic type + * @param cls + * the class + * @param tableName + * the table name + * @return the DAO instance + */ + @SuppressWarnings("unchecked") + public static synchronized DefaultDAO getDAOInstance( + Context context, Class cls, String tableName) { + if (daoMap.containsKey(cls)) + return daoMap.get(cls); + DefaultDAO dao = new DefaultDAO(cls, + DatabaseManager.getDBHelper(context), + DatabaseManager.getReflectionManagerInstance(cls), tableName); + daoMap.put(cls, dao); + return dao; + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/GlobalConfigs.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/GlobalConfigs.java index d48e84adc1..b01fbd16aa 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/GlobalConfigs.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/GlobalConfigs.java @@ -23,325 +23,348 @@ import android.util.Log; public class GlobalConfigs { - public static String IDL_FILE_FROM_ROOT = "/reports/fm_IDL.xml"; - - public static String httpAddress = ""; - - private boolean init = false; - - private static String TAG = "GlobalConfigs"; - - public static boolean loadedIDL = false; - - public static boolean loadedOrgTree = false; - - public static String hold_icon_address = "/opac/images/tor/"; - - //two days notification before checkout expires, this can be modified from preferences - public static int NOTIFICATION_BEFORE_CHECKOUT_EXPIRATION = 2; - - //to parse date from requests - public static final String datePattern = "yyyy-MM-dd'T'hh:mm:ssZ"; - - /** The locale. */ - public String locale = "en-US"; - - private static GlobalConfigs globalConfigSingleton = null; - /** The organisations. */ - public ArrayList organisations; - - /** The collections request. */ - private String collectionsRequest = "/opac/common/js/" + locale + "/OrgTree.js"; - - - private GlobalConfigs(Context context){ - - initialize(context); - } - - public static GlobalConfigs getGlobalConfigs(Context context){ - - if(globalConfigSingleton == null) - { - globalConfigSingleton = new GlobalConfigs(context); - } - - return globalConfigSingleton; - } - - /* Initialize function that retrieves IDL file and Orgs file - */ - private boolean initialize(Context context){ - - if(init == false){ - - init = true; - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - GlobalConfigs.httpAddress = preferences.getString("library_url", ""); - boolean noNetworkAccess = false; - System.out.println("Check for network conenctivity"); - try{ - Utils.checkNetworkStatus((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)); - - }catch(NoNetworkAccessException e){ - noNetworkAccess = true; - }catch(NoAccessToServer e){ - - System.out.println("No access to network"); - Intent preferencesAnctivity = new Intent(context, ApplicationPreferences.class); - context.startActivity(preferencesAnctivity); - - noNetworkAccess = true; - - } - if(!noNetworkAccess){ - loadIDLFile(); - getOrganisations(); - - getCopyStatusesAvailable((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)); - - AccountAccess.setAccountInfo(preferences.getString("username", ""), preferences.getString("password", "")); - - //TODO getorg hidding levels - //getOrgHiddentDepth(); - - return true; - } - return false; - } - return false; - } - - public void loadIDLFile(){ - - - try{ - Log.d("debug","Read fm"); - InputStream in_IDL = Utils.getNetInputStream(httpAddress + IDL_FILE_FROM_ROOT); - IDLParser parser = new IDLParser(in_IDL); - parser.parse(); - }catch(Exception e){ - System.err.println("Error in parsing IDL file " + IDL_FILE_FROM_ROOT + " " + e.getMessage()); - }; - - loadedIDL = true; - } - - /** - * Gets the organisations get's OrgTree.js from server, parses the input and recovers the organisations - * - * @return the organisations - */ - public void getOrganisations(){ - - String orgFile = null; - - - organisations = new ArrayList(); - - try{ - //using https: address - orgFile = Utils.getNetPageContent(httpAddress+collectionsRequest); - System.out.println("Request org " + httpAddress + collectionsRequest ); - }catch(Exception e){}; - - if(orgFile != null){ - organisations = new ArrayList(); - - System.out.println("Page content " + orgFile); - //in case of wrong file - if(orgFile.indexOf("=") == -1) - return; - - String orgArray = orgFile.substring( orgFile.indexOf("=")+1, orgFile.indexOf(";")); - - String arrayContent = orgArray.substring(orgArray.indexOf("[")+1,orgArray.lastIndexOf("]")); - - - Log.d(TAG,"Array to pe parsed " + arrayContent); - - //parser for list - - //format [104,2,1,"Curriculum Center",1,"CURRICULUM"] : [id,level,parent,name,can_have_volumes_bool,short_name] - - int index = 0; - while(true){ - - if(index >= arrayContent.length()) - break; - - int start = arrayContent.indexOf("[", index)+1; - int stop = arrayContent.indexOf("]", index); - - Log.d(TAG," start stop length index" + start+ " " + stop + " " + arrayContent.length() + " " + index); - if(start == -1 || stop == -1) - break; - - index = stop+1; - - String content = arrayContent.substring(start,stop); - - System.out.println("Content " + content); - - StringTokenizer tokenizer = new StringTokenizer(content,","); - - Organisation org = new Organisation(); - - //first is ID - String element = (String)tokenizer.nextElement(); - System.out.println("Id " + element); - try{ - org.id = Integer.parseInt(element); - }catch(Exception e){}; - - //level - element = (String)tokenizer.nextElement(); - System.out.println("Level " + element); - try{ - org.level = Integer.parseInt(element); - }catch(Exception e){}; - - //parent - element = (String)tokenizer.nextElement(); - System.out.println("parent " + element); - try{ - org.parent = Integer.parseInt(element); - }catch(Exception e){}; - - //name - element = (String)tokenizer.nextToken("\","); - System.out.println("Element " + element); - org.name = element; - - //can_have_volume_boo. - element = (String)tokenizer.nextElement(); - System.out.println("Element " + element); - try{ - org.canHaveVolumesBool = Integer.parseInt(element); - }catch(Exception e){}; - - //short name - element = (String)tokenizer.nextToken("\","); - System.out.println("Element " + element); - org.shortName = element; - - organisations.add(org); - } - - ArrayList orgs = new ArrayList(); - - for(int i=0;i organisations; + + /** The collections request. */ + private String collectionsRequest = "/opac/common/js/" + locale + + "/OrgTree.js"; + + private GlobalConfigs(Context context) { + + initialize(context); + } + + public static GlobalConfigs getGlobalConfigs(Context context) { + + if (globalConfigSingleton == null) { + globalConfigSingleton = new GlobalConfigs(context); + } + + return globalConfigSingleton; + } + + /* + * Initialize function that retrieves IDL file and Orgs file + */ + private boolean initialize(Context context) { + + if (init == false) { + + init = true; + SharedPreferences preferences = PreferenceManager + .getDefaultSharedPreferences(context); + GlobalConfigs.httpAddress = preferences + .getString("library_url", ""); + boolean noNetworkAccess = false; + System.out.println("Check for network conenctivity"); + try { + Utils.checkNetworkStatus((ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE)); + + } catch (NoNetworkAccessException e) { + noNetworkAccess = true; + } catch (NoAccessToServer e) { + + System.out.println("No access to network"); + Intent preferencesAnctivity = new Intent(context, + ApplicationPreferences.class); + context.startActivity(preferencesAnctivity); + + noNetworkAccess = true; + + } + if (!noNetworkAccess) { + loadIDLFile(); + getOrganisations(); + + getCopyStatusesAvailable((ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE)); + + AccountAccess.setAccountInfo( + preferences.getString("username", ""), + preferences.getString("password", "")); + + // TODO getorg hidding levels + // getOrgHiddentDepth(); + + return true; + } + return false; + } + return false; + } + + public void loadIDLFile() { + + try { + Log.d("debug", "Read fm"); + InputStream in_IDL = Utils.getNetInputStream(httpAddress + + IDL_FILE_FROM_ROOT); + IDLParser parser = new IDLParser(in_IDL); + parser.parse(); + } catch (Exception e) { + System.err.println("Error in parsing IDL file " + + IDL_FILE_FROM_ROOT + " " + e.getMessage()); + } + ; + + loadedIDL = true; + } + + /** + * Gets the organisations get's OrgTree.js from server, parses the input and + * recovers the organisations + * + * @return the organisations + */ + public void getOrganisations() { + + String orgFile = null; + + organisations = new ArrayList(); + + try { + // using https: address + orgFile = Utils.getNetPageContent(httpAddress + collectionsRequest); + System.out.println("Request org " + httpAddress + + collectionsRequest); + } catch (Exception e) { + } + ; + + if (orgFile != null) { + organisations = new ArrayList(); + + System.out.println("Page content " + orgFile); + // in case of wrong file + if (orgFile.indexOf("=") == -1) + return; + + String orgArray = orgFile.substring(orgFile.indexOf("=") + 1, + orgFile.indexOf(";")); + + String arrayContent = orgArray.substring(orgArray.indexOf("[") + 1, + orgArray.lastIndexOf("]")); + + Log.d(TAG, "Array to pe parsed " + arrayContent); + + // parser for list + + // format [104,2,1,"Curriculum Center",1,"CURRICULUM"] : + // [id,level,parent,name,can_have_volumes_bool,short_name] + + int index = 0; + while (true) { + + if (index >= arrayContent.length()) + break; + + int start = arrayContent.indexOf("[", index) + 1; + int stop = arrayContent.indexOf("]", index); + + Log.d(TAG, " start stop length index" + start + " " + stop + + " " + arrayContent.length() + " " + index); + if (start == -1 || stop == -1) + break; + + index = stop + 1; + + String content = arrayContent.substring(start, stop); + + System.out.println("Content " + content); + + StringTokenizer tokenizer = new StringTokenizer(content, ","); + + Organisation org = new Organisation(); + + // first is ID + String element = (String) tokenizer.nextElement(); + System.out.println("Id " + element); + try { + org.id = Integer.parseInt(element); + } catch (Exception e) { + } + ; + + // level + element = (String) tokenizer.nextElement(); + System.out.println("Level " + element); + try { + org.level = Integer.parseInt(element); + } catch (Exception e) { + } + ; + + // parent + element = (String) tokenizer.nextElement(); + System.out.println("parent " + element); + try { + org.parent = Integer.parseInt(element); + } catch (Exception e) { + } + ; + + // name + element = (String) tokenizer.nextToken("\","); + System.out.println("Element " + element); + org.name = element; + + // can_have_volume_boo. + element = (String) tokenizer.nextElement(); + System.out.println("Element " + element); + try { + org.canHaveVolumesBool = Integer.parseInt(element); + } catch (Exception e) { + } + ; + + // short name + element = (String) tokenizer.nextToken("\","); + System.out.println("Element " + element); + org.shortName = element; + + organisations.add(org); + } + + ArrayList orgs = new ArrayList(); + + for (int i = 0; i < organisations.size(); i++) { + + StringBuilder padding = new StringBuilder(); + for (int j = 0; j < organisations.get(i).level - 1; j++) + padding.append(" "); + + organisations.get(i).padding = padding.toString(); + } + + int size = organisations.size(); + int level = 0; + while (orgs.size() < size) { + + for (int i = 0; i < organisations.size(); i++) { + Organisation org = organisations.get(i); + if (level == org.level) { + boolean add = false; + for (int j = 0; j < orgs.size(); j++) { + + if (orgs.get(j).id == org.parent) { + orgs.add(j + 1, org); + add = true; + Log.d(TAG, "Added " + org.name + " " + + org.level); + break; + } + } + + if (add == false) { + orgs.add(org); + Log.d(TAG, "Added " + org.name + " " + org.level); + } + } + + } + level++; + } + organisations = orgs; + + loadedOrgTree = true; + } + } + + public void getCopyStatusesAvailable(ConnectivityManager cm) { + + SearchCatalog search = SearchCatalog.getInstance(cm); + + try { + search.getCopyStatuses(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void getOrgHiddentDepth() { + + // logic can be found in the opac_utils.js file in web/opac/common/js + + for (int i = 0; i < organisations.size(); i++) { + AccountAccess ac = AccountAccess.getAccountAccess(); + try { + Object obj = ac.fetchOrgSettings(organisations.get(i).id, + "opac.org_unit_hiding.depth"); + } catch (NoNetworkAccessException e) { + } catch (NoAccessToServer e) { + } catch (SessionNotFoundException e) {// not used here + } + + } + + } + + public static String getStringDate(Date date) { + + final SimpleDateFormat sdf = new SimpleDateFormat( + GlobalConfigs.datePattern); + + return sdf.format(date); + + } + + // parse from opac methods query results to Java date + public static Date parseDate(String dateString) { + + if (dateString == null) + return null; + + Date date = null; + final SimpleDateFormat sdf = new SimpleDateFormat( + GlobalConfigs.datePattern); + + try { + date = sdf.parse(dateString); + System.out.println(date); + } catch (ParseException e) { + e.printStackTrace(); + } + + return date; + } + + public String getOrganizationName(int id) { + + for (int i = 0; i < organisations.size(); i++) { + System.out.println("Id " + organisations.get(i).id + " " + i); + if (organisations.get(i).id == id) + return organisations.get(i).name; + } + + System.out.println("out here"); + return null; + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/NoAccessToServer.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/NoAccessToServer.java index bfa7337a8b..7c71da04da 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/NoAccessToServer.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/NoAccessToServer.java @@ -1,10 +1,10 @@ package org.evergreen.android.globals; -public class NoAccessToServer extends Exception{ +public class NoAccessToServer extends Exception { - /** + /** * */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/NoNetworkAccessException.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/NoNetworkAccessException.java index e13b34aafc..05fb225e06 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/NoNetworkAccessException.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/NoNetworkAccessException.java @@ -1,8 +1,8 @@ package org.evergreen.android.globals; -public class NoNetworkAccessException extends Exception{ - /** +public class NoNetworkAccessException extends Exception { + /** */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowNetworkNotAvailableRunnable.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowNetworkNotAvailableRunnable.java index b547afbded..d27fa5ca63 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowNetworkNotAvailableRunnable.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowNetworkNotAvailableRunnable.java @@ -4,30 +4,29 @@ import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; -class ShowNetworkNotAvailableRunnable implements Runnable{ - - public Context context; - - public ShowNetworkNotAvailableRunnable(Context context) { - this.context = context; - } - - @Override - public void run() { - // TODO Auto-generated method stub - AlertDialog alertDialog = new AlertDialog.Builder(context).create(); - alertDialog.setTitle("Error"); - alertDialog.setMessage("You need to have an internet connection"); - alertDialog.setButton("OK", - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - - alertDialog.show(); - } - - } \ No newline at end of file +class ShowNetworkNotAvailableRunnable implements Runnable { + + public Context context; + + public ShowNetworkNotAvailableRunnable(Context context) { + this.context = context; + } + + @Override + public void run() { + // TODO Auto-generated method stub + AlertDialog alertDialog = new AlertDialog.Builder(context).create(); + alertDialog.setTitle("Error"); + alertDialog.setMessage("You need to have an internet connection"); + alertDialog.setButton("OK", new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + + alertDialog.show(); + } + +} \ No newline at end of file diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowServerNotAvailableRunnable.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowServerNotAvailableRunnable.java index 0d9d2615bf..5c6c6ad03e 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowServerNotAvailableRunnable.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/ShowServerNotAvailableRunnable.java @@ -4,31 +4,29 @@ import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; -public class ShowServerNotAvailableRunnable implements Runnable{ - - private Context context; - - public ShowServerNotAvailableRunnable(Context context) { - this.context = context; - } - - @Override - public void run() { - AlertDialog alertDialog = new AlertDialog.Builder(context).create(); - alertDialog.setTitle("Error"); - alertDialog.setMessage("There is no network connectivity to " + GlobalConfigs.httpAddress); - alertDialog.setButton("OK", - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - }); - - - - alertDialog.show(); - } - +public class ShowServerNotAvailableRunnable implements Runnable { + + private Context context; + + public ShowServerNotAvailableRunnable(Context context) { + this.context = context; + } + + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(context).create(); + alertDialog.setTitle("Error"); + alertDialog.setMessage("There is no network connectivity to " + + GlobalConfigs.httpAddress); + alertDialog.setButton("OK", new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.dismiss(); + } + }); + + alertDialog.show(); + } + } \ No newline at end of file diff --git a/Open-ILS/src/Android/src/org/evergreen/android/globals/Utils.java b/Open-ILS/src/Android/src/org/evergreen/android/globals/Utils.java index bf9028fd3d..858ba3608a 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/globals/Utils.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/globals/Utils.java @@ -37,315 +37,350 @@ import android.widget.ImageView; public class Utils { - private static String TAG = "Utils"; - /** - * Gets the net page content. - * - * @param url the url of the page to be retrieved - * @return the net page content - */ - public static String getNetPageContent(String url){ - - String result = ""; - - HttpResponse response = null; - - try{ - HttpClient client = new DefaultHttpClient(); - HttpGet request = new HttpGet(url); - response = client.execute(request); - }catch(Exception e){ - System.out.println("Exception to GET page " + url); - } - StringBuilder str = null; - - try{ - InputStream in = response.getEntity().getContent(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - str = new StringBuilder(); - String line = null; - while((line = reader.readLine()) != null) - { - str.append(line); - } - in.close(); - }catch(Exception e){ - System.err.println("Error in retrieving response " + e.getMessage()); - } - - result = str.toString(); - - - return result; - } - - public static InputStream getNetInputStream(String url){ - - InputStream in = null; - - HttpResponse response = null; - - try{ - HttpClient client = new DefaultHttpClient(); - HttpGet request = new HttpGet(url); - response = client.execute(request); - }catch(Exception e){ - System.out.println("Exception to GET page " + url); - } - StringBuilder str = null; - - try{ - in = response.getEntity().getContent(); - - return in; - }catch(Exception e){ - System.err.println("Error in retrieving response " + e.getMessage()); - } - - return in; - } - - /** - * Checks to see if network access is enabled - * - * @throws NoNetworkAccessException if neither data connection or wifi are enabled - * NoAccessToHttpAddress if the library remote server can't be reached - * - */ - public static boolean checkNetworkStatus(ConnectivityManager cm) - throws NoNetworkAccessException, NoAccessToServer{ - - boolean HaveConnectedWifi = false; - boolean HaveConnectedMobile = false; - - - boolean networkAccessEnabled = false; - boolean httpAddressAccessReachable = false; - - NetworkInfo ni = cm.getActiveNetworkInfo(); - if ( ni != null ) - { - if (ni.getType() == ConnectivityManager.TYPE_WIFI) - if (ni.isConnected()){ - HaveConnectedWifi = true; - networkAccessEnabled = true; - } - if (ni.getType() == ConnectivityManager.TYPE_MOBILE) - if (ni.isConnected()){ - HaveConnectedMobile = true; - networkAccessEnabled = true; - } - } - - System.out.println("Network access " + networkAccessEnabled); - - if(networkAccessEnabled){ - //check to see if httpAddress is avaialble using the network connection - // 2 seconds timeout - httpAddressAccessReachable = checkIfNetAddressIsReachable(GlobalConfigs.httpAddress); - if(httpAddressAccessReachable == false) - throw new NoAccessToServer(); - } - - if(!networkAccessEnabled) - throw new NoNetworkAccessException(); - - return networkAccessEnabled; - - } - - - public static boolean checkIfNetAddressIsReachable(String url) throws NoAccessToServer{ - - boolean result = false; - try - { - HttpGet request = new HttpGet(url); - - HttpParams httpParameters = new BasicHttpParams(); - - //timeout to 1 seconds - HttpConnectionParams.setConnectionTimeout(httpParameters, 1000); - HttpClient httpClient = new DefaultHttpClient(httpParameters); - HttpResponse response = httpClient.execute(request); - - //System.out.println("Check network response" + response); - int status = response.getStatusLine().getStatusCode(); - - if (status == HttpStatus.SC_OK) - { - result = true; - } - - } - catch (SocketTimeoutException e) - { - result = false; // this is somewhat expected - throw new NoAccessToServer(); - } - catch (Exception e) { - Log.d(TAG, "Exception in is reachable " + e.getMessage()); - } - - return result; - } - - public static void bookCoverImage(ImageView picture, String imageID, int size){ - - String urlS = (GlobalConfigs.httpAddress + "/opac/extras/ac/jacket/small/" + imageID); - - Bitmap bmp = null; //create a new Bitmap variable called bmp, and initialize it to null + private static String TAG = "Utils"; + + /** + * Gets the net page content. + * + * @param url + * the url of the page to be retrieved + * @return the net page content + */ + public static String getNetPageContent(String url) { + + String result = ""; + + HttpResponse response = null; + + try { + HttpClient client = new DefaultHttpClient(); + HttpGet request = new HttpGet(url); + response = client.execute(request); + } catch (Exception e) { + System.out.println("Exception to GET page " + url); + } + StringBuilder str = null; + + try { + InputStream in = response.getEntity().getContent(); + BufferedReader reader = new BufferedReader( + new InputStreamReader(in)); + str = new StringBuilder(); + String line = null; + while ((line = reader.readLine()) != null) { + str.append(line); + } + in.close(); + } catch (Exception e) { + System.err + .println("Error in retrieving response " + e.getMessage()); + } + + result = str.toString(); + + return result; + } + + public static InputStream getNetInputStream(String url) { + + InputStream in = null; + + HttpResponse response = null; + + try { + HttpClient client = new DefaultHttpClient(); + HttpGet request = new HttpGet(url); + response = client.execute(request); + } catch (Exception e) { + System.out.println("Exception to GET page " + url); + } + StringBuilder str = null; + + try { + in = response.getEntity().getContent(); + + return in; + } catch (Exception e) { + System.err + .println("Error in retrieving response " + e.getMessage()); + } + + return in; + } + + /** + * Checks to see if network access is enabled + * + * @throws NoNetworkAccessException + * if neither data connection or wifi are enabled + * NoAccessToHttpAddress if the library remote server can't be + * reached + * + */ + public static boolean checkNetworkStatus(ConnectivityManager cm) + throws NoNetworkAccessException, NoAccessToServer { + + boolean HaveConnectedWifi = false; + boolean HaveConnectedMobile = false; + + boolean networkAccessEnabled = false; + boolean httpAddressAccessReachable = false; + + NetworkInfo ni = cm.getActiveNetworkInfo(); + if (ni != null) { + if (ni.getType() == ConnectivityManager.TYPE_WIFI) + if (ni.isConnected()) { + HaveConnectedWifi = true; + networkAccessEnabled = true; + } + if (ni.getType() == ConnectivityManager.TYPE_MOBILE) + if (ni.isConnected()) { + HaveConnectedMobile = true; + networkAccessEnabled = true; + } + } + + System.out.println("Network access " + networkAccessEnabled); + + if (networkAccessEnabled) { + // check to see if httpAddress is avaialble using the network + // connection + // 2 seconds timeout + httpAddressAccessReachable = checkIfNetAddressIsReachable(GlobalConfigs.httpAddress); + if (httpAddressAccessReachable == false) + throw new NoAccessToServer(); + } + + if (!networkAccessEnabled) + throw new NoNetworkAccessException(); + + return networkAccessEnabled; + + } + + public static boolean checkIfNetAddressIsReachable(String url) + throws NoAccessToServer { + + boolean result = false; + try { + HttpGet request = new HttpGet(url); + + HttpParams httpParameters = new BasicHttpParams(); + + // timeout to 1 seconds + HttpConnectionParams.setConnectionTimeout(httpParameters, 1000); + HttpClient httpClient = new DefaultHttpClient(httpParameters); + HttpResponse response = httpClient.execute(request); + + // System.out.println("Check network response" + response); + int status = response.getStatusLine().getStatusCode(); + + if (status == HttpStatus.SC_OK) { + result = true; + } + + } catch (SocketTimeoutException e) { + result = false; // this is somewhat expected + throw new NoAccessToServer(); + } catch (Exception e) { + Log.d(TAG, "Exception in is reachable " + e.getMessage()); + } + + return result; + } + + public static void bookCoverImage(ImageView picture, String imageID, + int size) { + + String urlS = (GlobalConfigs.httpAddress + + "/opac/extras/ac/jacket/small/" + imageID); + + Bitmap bmp = null; // create a new Bitmap variable called bmp, and + // initialize it to null try { - URL url = new URL(urlS); //create a URL object from the urlS string above - URLConnection conn = url.openConnection(); //save conn as a URLConnection - - conn.connect(); //connect to the URLConnection conn - InputStream is = conn.getInputStream(); //get the image from the URLConnection conn using InputStream is - BufferedInputStream bis = new BufferedInputStream(is); //create a BufferedInputStream called bis from is - bmp = BitmapFactory.decodeStream(bis); //use bis to convert the stream to a bitmap image, and save it to bmp - int bmpHeight = bmp.getHeight(); //stores the original height of the image - if(bmpHeight != 1){ - double scale = size/(double)bmpHeight; //sets the scaling number to match the desired size - double bmpWidthh = (double)bmp.getWidth() * scale; //scales and stores the original width into the desired one - int bmpWidth = (int)bmpWidthh; //gets the width of the picture and saves it - bmp = Bitmap.createScaledBitmap(bmp, bmpWidth, size, true); //creates and stores a new bmp with desired dimensions + URL url = new URL(urlS); // create a URL object from the urlS string + // above + URLConnection conn = url.openConnection(); // save conn as a + // URLConnection + + conn.connect(); // connect to the URLConnection conn + InputStream is = conn.getInputStream(); // get the image from the + // URLConnection conn using + // InputStream is + BufferedInputStream bis = new BufferedInputStream(is); // create a + // BufferedInputStream + // called bis + // from is + bmp = BitmapFactory.decodeStream(bis); // use bis to convert the + // stream to a bitmap image, + // and save it to bmp + int bmpHeight = bmp.getHeight(); // stores the original height of + // the image + if (bmpHeight != 1) { + double scale = size / (double) bmpHeight; // sets the scaling + // number to match the + // desired size + double bmpWidthh = (double) bmp.getWidth() * scale; // scales + // and + // stores + // the + // original + // width + // into the + // desired + // one + int bmpWidth = (int) bmpWidthh; // gets the width of the picture + // and saves it + bmp = Bitmap.createScaledBitmap(bmp, bmpWidth, size, true); // creates + // and + // stores + // a + // new + // bmp + // with + // desired + // dimensions + } + + } catch (MalformedURLException e) { // catch errors + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalStateException e) { + e.printStackTrace(); + } + picture.setImageBitmap(bmp); // send the Bitmap image bmp to pic, and + // call the method to set the image. + + } + + public static Object doRequest(HttpConnection conn, String service, + String methodName, String authToken, ConnectivityManager cm, + Object[] params) throws SessionNotFoundException, + NoNetworkAccessException, NoAccessToServer { + + // check for network connectivity + checkNetworkStatus(cm); + + // check to see if EG http server is reachable + checkIfNetAddressIsReachable(GlobalConfigs.httpAddress); + + // TODO check params and throw errors + Method method = new Method(methodName); + + System.out.println("Method :" + methodName + " param:"); + for (int i = 0; i < params.length; i++) { + method.addParam(params[i]); + System.out.print("Param " + i + ":" + params[i]); + } + // need space + System.out.println(); + + // sync request + HttpRequest req = new GatewayRequest(conn, service, method).send(); + Object resp; + + while ((resp = req.recv()) != null) { + System.out.println("Sync Response: " + resp); + Object response = (Object) resp; + + String textcode = null; + try { + textcode = ((Map) response).get("textcode"); + } catch (Exception e) { + System.err.println("Exception in retreive" + e.getMessage()); + } + + if (textcode != null) { + if (textcode.equals("NO_SESSION")) { + // System.out.println("REQUIRE NEW SESSION"); + throw new SessionNotFoundException(); } - - } catch (MalformedURLException e) { //catch errors - e.printStackTrace(); - } catch(IOException e){ - e.printStackTrace(); - } catch(IllegalStateException e){ - e.printStackTrace(); + + } + + return response; + } - picture.setImageBitmap(bmp); //send the Bitmap image bmp to pic, and call the method to set the image. - - - } - - public static Object doRequest(HttpConnection conn, String service, String methodName, String authToken, ConnectivityManager cm, Object[] params ) - throws SessionNotFoundException, NoNetworkAccessException, NoAccessToServer{ - - - //check for network connectivity - checkNetworkStatus(cm); - - //check to see if EG http server is reachable - checkIfNetAddressIsReachable(GlobalConfigs.httpAddress); - - - //TODO check params and throw errors - Method method = new Method(methodName); - - System.out.println("Method :" + methodName + " param:"); - for(int i=0;i)response).get("textcode"); - }catch(Exception e){ - System.err.println("Exception in retreive" + e.getMessage()); - } - - if(textcode != null){ - if(textcode.equals("NO_SESSION")){ - //System.out.println("REQUIRE NEW SESSION"); - throw new SessionNotFoundException(); - } - - } - - return response; - - } - return null; - - } - - //does not require authToken - public static Object doRequest(HttpConnection conn, String service, String methodName, ConnectivityManager cm, Object[] params ) - throws NoNetworkAccessException, NoAccessToServer{ - - - //check for network connectivity - checkNetworkStatus(cm); - - //check to see if EG http server is reachable - checkIfNetAddressIsReachable(GlobalConfigs.httpAddress); - - Method method = new Method(methodName); - - System.out.println("Method :" + methodName + " param:"); - for(int i=0;i)map).get("org_unit"); - this.count = ((Map)map).get("count"); - this.available = ((Map)map).get("available"); - this.depth = ((Map)map).get("depth"); - this.unshadow = ((Map)map).get("unshadow"); - - System.out.println(org_id + " " + available + " " + count); - } - - + private static final long serialVersionUID = 12343248767867L; + public Integer org_id; + public Integer count; + public Integer available; + public Integer depth; + public Integer unshadow; + + public CopyCountInformation(Object map) { + + this.org_id = ((Map) map).get("org_unit"); + this.count = ((Map) map).get("count"); + this.available = ((Map) map).get("available"); + this.depth = ((Map) map).get("depth"); + this.unshadow = ((Map) map).get("unshadow"); + + System.out.println(org_id + " " + available + " " + count); + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/CopyInformation.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/CopyInformation.java index bb686791f4..3136645ed1 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/CopyInformation.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/CopyInformation.java @@ -8,55 +8,55 @@ import java.util.List; import java.util.Map.Entry; import java.util.Set; -public class CopyInformation implements Serializable{ +public class CopyInformation implements Serializable { - - /** + /** * */ - private static final long serialVersionUID = -7269334218707079463L; - - public Integer org_id = -1; - - public String call_number_sufix; - - public String copy_location; - - public HashMap statuses; - - //the hash from the request method - private HashMap hashValCopy; - - //global, it is initialized when orgTree and fm_ild is downloaded - - public static LinkedHashMap availableOrgStatuses; - - public LinkedHashMap statusInformation = null; - - public CopyInformation(List list){ - - org_id = Integer.parseInt((String)list.get(0)); - call_number_sufix = (String)list.get(2); - copy_location = (String)list.get(4); - - hashValCopy = (HashMap)list.get(5); - - statusInformation = new LinkedHashMap(); - - Set> set = availableOrgStatuses.entrySet(); - - Iterator> it = set.iterator(); - - while(it.hasNext()){ - Entry entry = it.next(); - - if(hashValCopy.containsKey(entry.getKey())){ - statusInformation.put(entry.getValue(), hashValCopy.get(entry.getKey())+""); - System.out.println("Added " + entry.getKey()+ " " + entry.getValue() + " " + hashValCopy.get(entry.getKey())); - } - } - } - - - + private static final long serialVersionUID = -7269334218707079463L; + + public Integer org_id = -1; + + public String call_number_sufix; + + public String copy_location; + + public HashMap statuses; + + // the hash from the request method + private HashMap hashValCopy; + + // global, it is initialized when orgTree and fm_ild is downloaded + + public static LinkedHashMap availableOrgStatuses; + + public LinkedHashMap statusInformation = null; + + public CopyInformation(List list) { + + org_id = Integer.parseInt((String) list.get(0)); + call_number_sufix = (String) list.get(2); + copy_location = (String) list.get(4); + + hashValCopy = (HashMap) list.get(5); + + statusInformation = new LinkedHashMap(); + + Set> set = availableOrgStatuses.entrySet(); + + Iterator> it = set.iterator(); + + while (it.hasNext()) { + Entry entry = it.next(); + + if (hashValCopy.containsKey(entry.getKey())) { + statusInformation.put(entry.getValue(), + hashValCopy.get(entry.getKey()) + ""); + System.out.println("Added " + entry.getKey() + " " + + entry.getValue() + " " + + hashValCopy.get(entry.getKey())); + } + } + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/ImageDownloader.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/ImageDownloader.java index f5e90ea64b..fe9b902f9d 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/ImageDownloader.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/ImageDownloader.java @@ -29,49 +29,60 @@ import android.util.Log; import android.widget.ImageView; /** - * This helper class download images from the Internet and binds those with the provided ImageView. - * - *

It requires the INTERNET permission, which should be added to your application's manifest - * file.

- * - * A local cache of downloaded images is maintained internally to improve performance. + * This helper class download images from the Internet and binds those with the + * provided ImageView. + * + *

+ * It requires the INTERNET permission, which should be added to your + * application's manifest file. + *

+ * + * A local cache of downloaded images is maintained internally to improve + * performance. */ public class ImageDownloader { private static final String LOG_TAG = "ImageDownloader"; - public enum Mode { NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT } + public enum Mode { + NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT + } + private Mode mode = Mode.CORRECT; - + private int MIN_IMG_HEIGHT = 75; - + private int MIN_IMG_WIDTH = 30; - + private int bitmap_width; private int bitmap_height; private boolean scale; - - public ImageDownloader(int min_img_height){ - - MIN_IMG_HEIGHT = min_img_height; + + public ImageDownloader(int min_img_height) { + + MIN_IMG_HEIGHT = min_img_height; } - - public ImageDownloader(){ - + + public ImageDownloader() { + } - - public ImageDownloader(int w, int h, boolean scale){ - this.bitmap_height = h; - this.bitmap_width = w; - this.scale = scale; - MIN_IMG_HEIGHT = h; + + public ImageDownloader(int w, int h, boolean scale) { + this.bitmap_height = h; + this.bitmap_width = w; + this.scale = scale; + MIN_IMG_HEIGHT = h; } + /** - * Download the specified image from the Internet and binds it to the provided ImageView. The - * binding is immediate if the image is found in the cache and will be done asynchronously - * otherwise. A null bitmap will be associated to the ImageView if an error occurs. - * - * @param url The URL of the image to download. - * @param imageView The ImageView to bind the downloaded image to. + * Download the specified image from the Internet and binds it to the + * provided ImageView. The binding is immediate if the image is found in the + * cache and will be done asynchronously otherwise. A null bitmap will be + * associated to the ImageView if an error occurs. + * + * @param url + * The URL of the image to download. + * @param imageView + * The ImageView to bind the downloaded image to. */ public void download(String url, ImageView imageView) { resetPurgeTimer(); @@ -86,19 +97,19 @@ public class ImageDownloader { } /* - * Same as download but the image is always downloaded and the cache is not used. - * Kept private at the moment as its interest is not clear. - private void forceDownload(String url, ImageView view) { - forceDownload(url, view, null); - } + * Same as download but the image is always downloaded and the cache is not + * used. Kept private at the moment as its interest is not clear. private + * void forceDownload(String url, ImageView view) { forceDownload(url, view, + * null); } */ /** - * Same as download but the image is always downloaded and the cache is not used. - * Kept private at the moment as its interest is not clear. + * Same as download but the image is always downloaded and the cache is not + * used. Kept private at the moment as its interest is not clear. */ private void forceDownload(String url, ImageView imageView) { - // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys. + // State sanity: url is guaranteed to never be null in + // DownloadedDrawable and cache keys. if (url == null) { imageView.setImageDrawable(null); return; @@ -106,37 +117,39 @@ public class ImageDownloader { if (cancelPotentialDownload(url, imageView)) { switch (mode) { - case NO_ASYNC_TASK: - Bitmap bitmap = downloadBitmap(url); - addBitmapToCache(url, bitmap); - imageView.setImageBitmap(bitmap); - break; - - case NO_DOWNLOADED_DRAWABLE: - imageView.setMinimumHeight(MIN_IMG_HEIGHT); - BitmapDownloaderTask task = new BitmapDownloaderTask(imageView); - task.execute(url); - break; - - case CORRECT: - task = new BitmapDownloaderTask(imageView); - DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task); - imageView.setImageDrawable(downloadedDrawable); - imageView.setMinimumHeight(MIN_IMG_HEIGHT); - imageView.setMinimumWidth(MIN_IMG_WIDTH); - task.execute(url); - break; + case NO_ASYNC_TASK: + Bitmap bitmap = downloadBitmap(url); + addBitmapToCache(url, bitmap); + imageView.setImageBitmap(bitmap); + break; + + case NO_DOWNLOADED_DRAWABLE: + imageView.setMinimumHeight(MIN_IMG_HEIGHT); + BitmapDownloaderTask task = new BitmapDownloaderTask(imageView); + task.execute(url); + break; + + case CORRECT: + task = new BitmapDownloaderTask(imageView); + DownloadedDrawable downloadedDrawable = new DownloadedDrawable( + task); + imageView.setImageDrawable(downloadedDrawable); + imageView.setMinimumHeight(MIN_IMG_HEIGHT); + imageView.setMinimumWidth(MIN_IMG_WIDTH); + task.execute(url); + break; } } } /** - * Returns true if the current download has been canceled or if there was no download in - * progress on this image view. - * Returns false if the download in progress deals with the same url. The download is not - * stopped in that case. + * Returns true if the current download has been canceled or if there was no + * download in progress on this image view. Returns false if the download in + * progress deals with the same url. The download is not stopped in that + * case. */ - private static boolean cancelPotentialDownload(String url, ImageView imageView) { + private static boolean cancelPotentialDownload(String url, + ImageView imageView) { BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); if (bitmapDownloaderTask != null) { @@ -152,15 +165,17 @@ public class ImageDownloader { } /** - * @param imageView Any imageView - * @return Retrieve the currently active download task (if any) associated with this imageView. - * null if there is no such task. + * @param imageView + * Any imageView + * @return Retrieve the currently active download task (if any) associated + * with this imageView. null if there is no such task. */ - private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) { + private static BitmapDownloaderTask getBitmapDownloaderTask( + ImageView imageView) { if (imageView != null) { Drawable drawable = imageView.getDrawable(); if (drawable instanceof DownloadedDrawable) { - DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable; + DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; return downloadedDrawable.getBitmapDownloaderTask(); } } @@ -171,25 +186,25 @@ public class ImageDownloader { final int IO_BUFFER_SIZE = 4 * 1024; // AndroidHttpClient is not allowed to be used from the main thread - final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() : - AndroidHttpClient.newInstance("Android"); - + final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() + : AndroidHttpClient.newInstance("Android"); + HttpGet getRequest = null; - try{ - getRequest = new HttpGet(url); - }catch(Exception e){ + try { + getRequest = new HttpGet(url); + } catch (Exception e) { if ((client instanceof AndroidHttpClient)) { ((AndroidHttpClient) client).close(); } - return null; + return null; } - + try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { - Log.w("ImageDownloader", "Error " + statusCode + - " while retrieving bitmap from " + url); + Log.w("ImageDownloader", "Error " + statusCode + + " while retrieving bitmap from " + url); return null; } @@ -200,7 +215,8 @@ public class ImageDownloader { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. - return BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); + return BitmapFactory.decodeStream(new FlushedInputStream( + inputStream)); } finally { if (inputStream != null) { inputStream.close(); @@ -226,7 +242,8 @@ public class ImageDownloader { } /* - * An InputStream that skips the exact number of bytes provided, unless it reaches EOF. + * An InputStream that skips the exact number of bytes provided, unless it + * reaches EOF. */ static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(InputStream inputStream) { @@ -241,7 +258,7 @@ public class ImageDownloader { if (bytesSkipped == 0L) { int b = read(); if (b < 0) { - break; // we reached EOF + break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } @@ -282,49 +299,53 @@ public class ImageDownloader { } addBitmapToCache(url, bitmap); - - if (imageViewReference != null) { ImageView imageView = imageViewReference.get(); BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); - // Change bitmap only if this process is still associated with it - // Or if we don't use any bitmap to task association (NO_DOWNLOADED_DRAWABLE mode) + // Change bitmap only if this process is still associated with + // it + // Or if we don't use any bitmap to task association + // (NO_DOWNLOADED_DRAWABLE mode) if ((this == bitmapDownloaderTask) || (mode != Mode.CORRECT)) { - Bitmap newScaledBitmap = null; - if(bitmap != null && scale == true){ - newScaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap_width, bitmap_height, true); - imageView.setImageBitmap(newScaledBitmap); - }else{ - imageView.setImageBitmap(bitmap); - } - } - - if(bitmap == null){ - if(imageView != null) - imageView.setImageResource(R.drawable.no_image); + Bitmap newScaledBitmap = null; + if (bitmap != null && scale == true) { + newScaledBitmap = Bitmap.createScaledBitmap(bitmap, + bitmap_width, bitmap_height, true); + imageView.setImageBitmap(newScaledBitmap); + } else { + imageView.setImageBitmap(bitmap); + } + } + + if (bitmap == null) { + if (imageView != null) + imageView.setImageResource(R.drawable.no_image); } } } } - /** - * A fake Drawable that will be attached to the imageView while the download is in progress. - * - *

Contains a reference to the actual download task, so that a download task can be stopped - * if a new binding is required, and makes sure that only the last started download process can - * bind its result, independently of the download finish order.

+ * A fake Drawable that will be attached to the imageView while the download + * is in progress. + * + *

+ * Contains a reference to the actual download task, so that a download task + * can be stopped if a new binding is required, and makes sure that only the + * last started download process can bind its result, independently of the + * download finish order. + *

*/ static class DownloadedDrawable extends ColorDrawable { private final WeakReference bitmapDownloaderTaskReference; public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) { super(Color.BLACK); - - bitmapDownloaderTaskReference = - new WeakReference(bitmapDownloaderTask); + + bitmapDownloaderTaskReference = new WeakReference( + bitmapDownloaderTask); } public BitmapDownloaderTask getBitmapDownloaderTask() { @@ -337,25 +358,27 @@ public class ImageDownloader { clearCache(); } - /* * Cache-related fields and methods. - * - * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the - * Garbage Collector. + * + * We use a hard and a soft cache. A soft reference cache is too + * aggressively cleared by the Garbage Collector. */ - + private static final int HARD_CACHE_CAPACITY = 20; private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds // Hard cache, with a fixed maximum capacity and a life duration - private final HashMap sHardBitmapCache = - new LinkedHashMap(HARD_CACHE_CAPACITY / 2, 0.75f, true) { + private final HashMap sHardBitmapCache = new LinkedHashMap( + HARD_CACHE_CAPACITY / 2, 0.75f, true) { @Override - protected boolean removeEldestEntry(LinkedHashMap.Entry eldest) { + protected boolean removeEldestEntry( + LinkedHashMap.Entry eldest) { if (size() > HARD_CACHE_CAPACITY) { - // Entries push-out of hard reference cache are transferred to soft reference cache - sSoftBitmapCache.put(eldest.getKey(), new SoftReference(eldest.getValue())); + // Entries push-out of hard reference cache are transferred to + // soft reference cache + sSoftBitmapCache.put(eldest.getKey(), + new SoftReference(eldest.getValue())); return true; } else return false; @@ -363,8 +386,8 @@ public class ImageDownloader { }; // Soft cache for bitmaps kicked out of hard cache - private final static ConcurrentHashMap> sSoftBitmapCache = - new ConcurrentHashMap>(HARD_CACHE_CAPACITY / 2); + private final static ConcurrentHashMap> sSoftBitmapCache = new ConcurrentHashMap>( + HARD_CACHE_CAPACITY / 2); private final Handler purgeHandler = new Handler(); @@ -376,7 +399,9 @@ public class ImageDownloader { /** * Adds this bitmap to the cache. - * @param bitmap The newly downloaded bitmap. + * + * @param bitmap + * The newly downloaded bitmap. */ private void addBitmapToCache(String url, Bitmap bitmap) { if (bitmap != null) { @@ -387,7 +412,8 @@ public class ImageDownloader { } /** - * @param url The URL of the image that will be retrieved from the cache. + * @param url + * The URL of the image that will be retrieved from the cache. * @return The cached bitmap or null if it was not found. */ private Bitmap getBitmapFromCache(String url) { @@ -418,10 +444,11 @@ public class ImageDownloader { return null; } - + /** - * Clears the image cache used internally to improve performance. Note that for memory - * efficiency reasons, the cache will automatically be cleared after a certain inactivity delay. + * Clears the image cache used internally to improve performance. Note that + * for memory efficiency reasons, the cache will automatically be cleared + * after a certain inactivity delay. */ public void clearCache() { sHardBitmapCache.clear(); @@ -436,5 +463,3 @@ public class ImageDownloader { purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE); } } - - diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/MoreCopyInformation.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/MoreCopyInformation.java index d54e0eee6f..0890bb7b75 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/MoreCopyInformation.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/MoreCopyInformation.java @@ -35,100 +35,111 @@ import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; -public class MoreCopyInformation extends Activity{ - - - private Button homeButton; - - private Button myAccountButton; - - private TextView headerTitle; - - private Context context; - - private RecordInfo record; - - private GlobalConfigs gl; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.copy_information_more); - gl = GlobalConfigs.getGlobalConfigs(context); - context = this; - record = (RecordInfo) getIntent().getSerializableExtra("recordInfo"); - - //header portion actions +public class MoreCopyInformation extends Activity { + + private Button homeButton; + + private Button myAccountButton; + + private TextView headerTitle; + + private Context context; + + private RecordInfo record; + + private GlobalConfigs gl; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.copy_information_more); + gl = GlobalConfigs.getGlobalConfigs(context); + context = this; + record = (RecordInfo) getIntent().getSerializableExtra("recordInfo"); + + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.copy_information_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - - LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - // insert into main view - LinearLayout insertPoint = (LinearLayout) findViewById(R.id.record_details_copy_information); - addCopyInfo(inf, insertPoint); - - } - - public void addCopyInfo( LayoutInflater inflater, LinearLayout insertPoint){ - - for(int i=0;i> set = info.statusInformation.entrySet(); - - Iterator> it = set.iterator(); - - while(it.hasNext()){ - - Entry ent = it.next(); - TextView statusName = new TextView(context); - statusName.setText(ent.getKey() + " : " + ent.getValue()); - - copy_statuses.addView(statusName, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - - } - - } - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + + LayoutInflater inf = (LayoutInflater) context + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + // insert into main view + LinearLayout insertPoint = (LinearLayout) findViewById(R.id.record_details_copy_information); + addCopyInfo(inf, insertPoint); + + } + + public void addCopyInfo(LayoutInflater inflater, LinearLayout insertPoint) { + + for (int i = 0; i < record.copyInformationList.size(); i++) { + + View copy_info_view = inflater.inflate(R.layout.copy_information, + null); + + // fill in any details dynamically here + TextView library = (TextView) copy_info_view + .findViewById(R.id.copy_information_library); + TextView call_number = (TextView) copy_info_view + .findViewById(R.id.copy_information_call_number); + TextView copy_location = (TextView) copy_info_view + .findViewById(R.id.copy_information_copy_location); + + library.setText(gl.getOrganizationName(record.copyInformationList + .get(i).org_id) + " "); + call_number + .setText(record.copyInformationList.get(i).call_number_sufix); + copy_location + .setText(record.copyInformationList.get(i).copy_location); + + // insert into main view + insertPoint.addView(copy_info_view, new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT)); + + LinearLayout copy_statuses = (LinearLayout) copy_info_view + .findViewById(R.id.copy_information_statuses); + + CopyInformation info = record.copyInformationList.get(i); + + Set> set = info.statusInformation.entrySet(); + + Iterator> it = set.iterator(); + + while (it.hasNext()) { + + Entry ent = it.next(); + TextView statusName = new TextView(context); + statusName.setText(ent.getKey() + " : " + ent.getValue()); + + copy_statuses.addView(statusName, new LayoutParams( + LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + + } + + } + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/Organisation.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/Organisation.java index 13cbab59e9..40ffb82bad 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/Organisation.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/Organisation.java @@ -2,24 +2,24 @@ package org.evergreen.android.searchCatalog; public class Organisation { - public String name = null; - - public String shortName = null; - - public Integer id = null; - - public Integer level = null; - - public Integer parent = null; - - public Integer canHaveVolumesBool = null; - - public Integer hiddenDepth = null; - - //used for indent display - public String padding = ""; - - public Organisation(){ - - } + public String name = null; + + public String shortName = null; + + public Integer id = null; + + public Integer level = null; + + public Integer parent = null; + + public Integer canHaveVolumesBool = null; + + public Integer hiddenDepth = null; + + // used for indent display + public String padding = ""; + + public Organisation() { + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/RecordInfo.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/RecordInfo.java index b964c25981..196025382c 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/RecordInfo.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/RecordInfo.java @@ -8,121 +8,129 @@ import java.util.Map.Entry; import org.opensrf.util.OSRFObject; -public class RecordInfo implements Serializable{ +public class RecordInfo implements Serializable { - - //{"title","author","doc_id","doc_type","pubdate","isbn","publisher","tcn","subject","type_of_resources","call_numbers","edition","online_loc","synopsis","physical_description","toc","copy_count","series","serials","foreign_copy_maps"}); - - /** + // {"title","author","doc_id","doc_type","pubdate","isbn","publisher","tcn","subject","type_of_resources","call_numbers","edition","online_loc","synopsis","physical_description","toc","copy_count","series","serials","foreign_copy_maps"}); + + /** * */ - private static final long serialVersionUID = 10123L; - - public String title = null; - - public String author = null; - - public String pubdate = null; - - public String isbn = null; - - public Integer doc_id = null; - - public String publisher = null; - - public String subject = null; - - public String doc_type = null; - - public String online_loc = null; - - public String synopsis = null; - - public String physical_description = null; - - public String series = null; - - //tcn field - public String image = null; - - public boolean dummy = false; - - public ArrayList copyCountListInfo = null; - - public List copyInformationList = null; - - public RecordInfo(){ - this.title = "Test title"; - this.author = "Test author"; - this.pubdate = "Publication date"; - copyInformationList = new ArrayList(); - - //marks the fact that this is a record made from no info - this.dummy = true; - } - public RecordInfo(OSRFObject info){ - copyInformationList = new ArrayList(); - try{ - - this.title = info.getString("title"); - this.author = info.getString("author"); - this.pubdate = info.getString("pubdate"); - this.publisher = info.getString("publisher"); - this.doc_id = info.getInt("doc_id"); - this.image = info.getString("tcn"); - this.doc_type = info.getString("doc_type"); - } - catch(Exception e){System.out.println("Exception basic info " + e.getMessage());}; - - try{ - this.isbn = (String)info.get("isbn"); - }catch(Exception e){ - System.out.println("Exception isbn " + e.getMessage()); - }; - - try{ - - Map subjectMap = (Map) info.get("subject"); - - this.subject = ""; - - int no = subjectMap.entrySet().size(); - int i=0; - for(Entry entry : subjectMap.entrySet()){ - i++; - if(i seriesList = (List) info.get("series"); - for(int i=0;i copyCountListInfo = null; + + public List copyInformationList = null; + + public RecordInfo() { + this.title = "Test title"; + this.author = "Test author"; + this.pubdate = "Publication date"; + copyInformationList = new ArrayList(); + + // marks the fact that this is a record made from no info + this.dummy = true; + } + + public RecordInfo(OSRFObject info) { + copyInformationList = new ArrayList(); + try { + + this.title = info.getString("title"); + this.author = info.getString("author"); + this.pubdate = info.getString("pubdate"); + this.publisher = info.getString("publisher"); + this.doc_id = info.getInt("doc_id"); + this.image = info.getString("tcn"); + this.doc_type = info.getString("doc_type"); + } catch (Exception e) { + System.out.println("Exception basic info " + e.getMessage()); + } + ; + + try { + this.isbn = (String) info.get("isbn"); + } catch (Exception e) { + System.out.println("Exception isbn " + e.getMessage()); + } + ; + + try { + + Map subjectMap = (Map) info.get("subject"); + + this.subject = ""; + + int no = subjectMap.entrySet().size(); + int i = 0; + for (Entry entry : subjectMap.entrySet()) { + i++; + if (i < no) + this.subject += entry.getKey() + " \n"; + else + this.subject += entry.getKey(); + } + + } catch (Exception e) { + System.out.println("Exception subject " + e.getMessage()); + } + ; + try { + + this.online_loc = ((List) info.get("online_loc")).get(0).toString(); + + } catch (Exception e) { + System.out.println("Exception online_loc " + e.getMessage()); + } + ; + try { + this.physical_description = (String) info + .get("physical_description"); + } catch (Exception e) { + System.out.println("Exception physical_description " + + e.getMessage()); + } + ; + try { + this.series = ""; + List seriesList = (List) info.get("series"); + for (int i = 0; i < seriesList.size(); i++) + if (i < seriesList.size() - 1) + this.series += seriesList.get(i) + ", "; + else + this.series += seriesList.get(i); + } catch (Exception e) { + System.out.println("Exception series " + e.getMessage()); + } + ; + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SampleUnderlinesNoFade.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SampleUnderlinesNoFade.java index d76d2e9cce..b1eec12d40 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SampleUnderlinesNoFade.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SampleUnderlinesNoFade.java @@ -22,64 +22,65 @@ import android.widget.TextView; public class SampleUnderlinesNoFade extends BaseSampleActivity { - private List records; - - private Button myAccountButton; - - private Button homeButton; - - private TextView headerTitle; - - @Override + private List records; + + private Button myAccountButton; + + private Button homeButton; + + private TextView headerTitle; + + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_underlines); - - records = (List)getIntent().getSerializableExtra("recordList"); - - if(records.get(records.size()-1).dummy == true) - records.remove(records.size()-1); - - - //header portion actions + + records = (List) getIntent().getSerializableExtra( + "recordList"); + + if (records.get(records.size() - 1).dummy == true) + records.remove(records.size() - 1); + + // header portion actions homeButton = (Button) findViewById(R.id.library_logo); myAccountButton = (Button) findViewById(R.id.my_account_button); headerTitle = (TextView) findViewById(R.id.header_title); headerTitle.setText(R.string.search_details_title); - + myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),AccountScreenDashboard.class); - startActivity(intent); - } - }); - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); + homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - //end header portion actions - + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + // end header portion actions + int record_position = getIntent().getIntExtra("recordPosition", 0); mAdapter = new SearchFragmentAdapter(getSupportFragmentManager()); - mPager = (ViewPager)findViewById(R.id.pager); + mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); - mPager.setCurrentItem(record_position); - - UnderlinePageIndicator indicator = (UnderlinePageIndicator)findViewById(R.id.indicator); + + UnderlinePageIndicator indicator = (UnderlinePageIndicator) findViewById(R.id.indicator); indicator.setViewPager(mPager); indicator.setFades(false); mIndicator = indicator; - + } - + class SearchFragmentAdapter extends TestFragmentAdapter { public SearchFragmentAdapter(FragmentManager fm) { super(fm); @@ -87,14 +88,15 @@ public class SampleUnderlinesNoFade extends BaseSampleActivity { @Override public Fragment getItem(int position) { - // position +1 for 1 - size values - return BasicDetailsFragment.newInstance(records.get(position),position+1,records.size()); + // position +1 for 1 - size values + return BasicDetailsFragment.newInstance(records.get(position), + position + 1, records.size()); } @Override public int getCount() { return records.size(); - //return TabsView.CONTENT.length; + // return TabsView.CONTENT.length; } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalog.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalog.java index b6a9d8850e..1e2e82c2d9 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalog.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalog.java @@ -1,4 +1,3 @@ - package org.evergreen.android.searchCatalog; import java.util.ArrayList; @@ -26,322 +25,352 @@ import android.util.Log; */ public class SearchCatalog { - /** The SERVICE. */ - public static String SERVICE = "open-ils.search"; - - /** The METHO d_ multicas s_ search. */ - public static String METHOD_MULTICASS_SEARCH = "open-ils.search.biblio.multiclass.query"; - - /** The METHO d_ sli m_ retrive. */ - public static String METHOD_SLIM_RETRIVE = "open-ils.search.biblio.record.mods_slim.retrieve"; - - /** Method - * @param : no parameters - * @returns : returns array of ccs objects - */ - - public static String METHOD_COPY_STATUS_ALL ="open-ils.search.config.copy_status.retrieve.all"; - - /** - * Method that returns library where record with id is - * @param : record ID to get all libraries, or just book ID, Current Library ID, User ID - * @returns : [[["4","","CONCERTO 27","","Stacks",{"0":5}],["4","","PERFORM 27","","Stacks",{"0":2}]]] - * "0":% is the available books - * [org_id, call_number_sufix, copy_location, status1:count, status2:count ..] - */ - public static String METHOD_COPY_LOCATION_COUNTS = "open-ils.search.biblio.copy_location_counts.summary.retrieve"; - - /** - * Get copy statuses like Available, Checked_out , in_progress and others, ccs OSRFObjects - */ - public static String METHOD_GET_COPY_STATUSES = "open-ils.search.config.copy_status.retrieve.all"; - - /** - * Get copy count information - * @param : org_unit_id, record_id, "" ? - * @returns: objects [{"transcendant":null,"count":35,"org_unit":1,"depth":0,"unshadow":35,"available":35}, - * {"transcendant":null,"count":14,"org_unit":2,"depth":1,"unshadow":14,"available":14},{"transcendant":null,"count":7,"org_unit":4,"depth":2,"unshadow":7,"available":7}] - */ - public static String METHOD_GET_COPY_COUNT = "open-ils.search.biblio.record.copy_count"; - - - - public static SearchCatalog searchCatalogSingleton = null; - /** The conn. */ - public HttpConnection conn; - - //TODO get statuses on load - //open-ils.search.config.copy_status.retrieve.all - - /** The TAG. */ - public String TAG = "SearchCatalog"; - - //the org on witch the searches will be made - /** The selected organization. */ - public Organisation selectedOrganization = null; - - public Integer offset; - - public Integer visible; - - public Integer searchLimit = 10; - - private ConnectivityManager cm; - - public static SearchCatalog getInstance(ConnectivityManager cm){ - - if(searchCatalogSingleton == null){ - searchCatalogSingleton = new SearchCatalog(cm); - } - - return searchCatalogSingleton; - } - - public static SearchCatalog getInstance(){ - - return searchCatalogSingleton; - } - - /** - * Instantiates a new search catalog. - * - * @param httpAddress the http address - * @param locale the locale - */ - private SearchCatalog(ConnectivityManager cm) { - super(); - - this.cm = cm; - - try{ - // configure the connection - conn = new HttpConnection(GlobalConfigs.httpAddress+"/osrf-gateway-v1"); - - - }catch(Exception e){ - System.err.println("Exception in establishing connection " + e.getMessage()); - } - //registering classes so no longer necessary to register object classes manually - - } - - - - - /** - * Gets the search results - * - * @param searchWords the search words - * @return the search results - */ - public ArrayList getSearchResults(String searchWords, Integer offset) throws NoNetworkAccessException, NoAccessToServer{ - - - ArrayList resultsRecordInfo = new ArrayList(); - - - Method method = new Method(METHOD_MULTICASS_SEARCH); - - HashMap complexParm = new HashMap(); - - try{ - if(this.selectedOrganization != null){ - if(this.selectedOrganization.id != null) - complexParm.put("org_unit", this.selectedOrganization.id); - if(this.selectedOrganization.level != null) - complexParm.put("depth", this.selectedOrganization.level-1); - } - //TODO change here, multiple result per page - complexParm.put("limit", searchLimit); - - complexParm.put("offset",offset); - - /* - complexParm.put("offset",0); - complexParm.put("visibility_limit", 3000); - complexParm.put("default_class","keyword"); - */ - - }catch(Exception e) - { - System.out.println("Exception in JSON " + e.getMessage()); - } - - //do request and check for connectivity - Object resp = Utils.doRequest(conn, SERVICE, METHOD_MULTICASS_SEARCH, cm, new Object[]{complexParm,searchWords,1}); - - ArrayList ids = new ArrayList(); - - System.out.println("Sync Response: " + resp); - - Map response = (Map) resp; - - System.out.println(" ids : " + response.get("ids") + " " ); - - List> result_ids = (List) response.get("ids"); - - visible =Integer.parseInt((String)response.get("count")); - - for(int i=0;i> list= (List>)getLocationCount(Integer.parseInt(ids.get(i)), this.selectedOrganization.id, this.selectedOrganization.level-1); - - if(list != null) - for(int j=0; j getSearchResults(String searchWords, + Integer offset) throws NoNetworkAccessException, NoAccessToServer { + + ArrayList resultsRecordInfo = new ArrayList(); + + Method method = new Method(METHOD_MULTICASS_SEARCH); + + HashMap complexParm = new HashMap(); + + try { + if (this.selectedOrganization != null) { + if (this.selectedOrganization.id != null) + complexParm.put("org_unit", this.selectedOrganization.id); + if (this.selectedOrganization.level != null) + complexParm.put("depth", + this.selectedOrganization.level - 1); + } + // TODO change here, multiple result per page + complexParm.put("limit", searchLimit); + + complexParm.put("offset", offset); + + /* + * complexParm.put("offset",0); complexParm.put("visibility_limit", + * 3000); complexParm.put("default_class","keyword"); + */ + + } catch (Exception e) { + System.out.println("Exception in JSON " + e.getMessage()); + } + + // do request and check for connectivity + Object resp = Utils.doRequest(conn, SERVICE, METHOD_MULTICASS_SEARCH, + cm, new Object[] { complexParm, searchWords, 1 }); + + ArrayList ids = new ArrayList(); + + System.out.println("Sync Response: " + resp); + + Map response = (Map) resp; + + System.out.println(" ids : " + response.get("ids") + " "); + + List> result_ids = (List) response.get("ids"); + + visible = Integer.parseInt((String) response.get("count")); + + for (int i = 0; i < result_ids.size(); i++) { + ids.add(result_ids.get(i).get(0)); + } + + System.out.println("Ids " + ids); + + // request other info based on ids + + for (int i = 0; i < ids.size(); i++) { + + RecordInfo record = new RecordInfo( + getItemShortInfo(Integer.parseInt(ids.get(i)))); + // get copy information + resultsRecordInfo.add(record); + + record.copyCountListInfo = getCopyCount( + Integer.parseInt(ids.get(i)), this.selectedOrganization.id); + + // get copy count + List> list = (List>) getLocationCount( + Integer.parseInt(ids.get(i)), this.selectedOrganization.id, + this.selectedOrganization.level - 1); + + if (list != null) + for (int j = 0; j < list.size(); j++) { + CopyInformation copyInfo = new CopyInformation(list.get(j)); + + record.copyInformationList.add(copyInfo); + } + + System.out.println("Title " + record.title + " Author " + + record.author + " Pub date" + record.pubdate + + " Publisher" + record.publisher); + } + + return resultsRecordInfo; + } + + /** + * Gets the item short info. + * + * @param id + * the id + * @return the item short info + */ + private OSRFObject getItemShortInfo(Integer id) { + + Method method = new Method(METHOD_SLIM_RETRIVE); + + method.addParam(id); + + HttpRequest req = new GatewayRequest(conn, SERVICE, method).send(); + Object resp; + while ((resp = req.recv()) != null) { + System.out.println("Sync Response: " + resp); + return (OSRFObject) resp; + } + + return null; + } + + /** + * Search catalog. + * + * @param searchWords + * the search words + * @return the object + */ + public Object searchCatalog(String searchWords) + throws NoNetworkAccessException, NoAccessToServer { + + Object response = Utils.doRequest(conn, SERVICE, METHOD_SLIM_RETRIVE, + cm, new Object[] { "keyword", searchWords }); + return response; - - } - - /** - * Search catalog. - * - * @param searchWords the search words - * @param requestHandler the request handler - */ - public void searchCatalog(String searchWords, HttpRequestHandler requestHandler){ - + + } + + /** + * Search catalog. + * + * @param searchWords + * the search words + * @param requestHandler + * the request handler + */ + public void searchCatalog(String searchWords, + HttpRequestHandler requestHandler) { + Method method = new Method(METHOD_SLIM_RETRIVE); - - method.addParam(searchWords); + + method.addParam(searchWords); // sync test HttpRequest req = new GatewayRequest(conn, SERVICE, method).send(); req.sendAsync(requestHandler); - } - - - public Object getCopyStatuses() { - - List ccs_list = (List)Utils.doRequestSimple(conn, SERVICE, METHOD_COPY_STATUS_ALL, new Object[]{}); - - CopyInformation.availableOrgStatuses = new LinkedHashMap(); - - if(ccs_list != null){ - for(int i=0;i list = (List)Utils.doRequestSimple(conn, SERVICE, METHOD_COPY_LOCATION_COUNTS, new Object[]{recordID, orgID, orgDepth}); - return list; - - } - - - public ArrayList getRecordsInfo(ArrayList ids){ - - ArrayList recordInfoArray = new ArrayList(); - - for(int i=0;i getCopyCount(Integer recordID, Integer orgID){ - - List list = (List)Utils.doRequestSimple(conn, SERVICE, METHOD_GET_COPY_COUNT, new Object[]{orgID, recordID, ""}); - - ArrayList copyInfoList = new ArrayList(); - - if(list == null) - return copyInfoList; - - for(int i=0;i ccs_list = (List) Utils.doRequestSimple( + conn, SERVICE, METHOD_COPY_STATUS_ALL, new Object[] {}); + + CopyInformation.availableOrgStatuses = new LinkedHashMap(); + + if (ccs_list != null) { + for (int i = 0; i < ccs_list.size(); i++) { + OSRFObject ccs_obj = ccs_list.get(i); + if (ccs_obj.getString("opac_visible").equals("t")) { + + CopyInformation.availableOrgStatuses.put( + ccs_obj.getInt("id") + "", + ccs_obj.getString("name")); + System.out.println("Add status " + + ccs_obj.getString("name")); + + } + } + } + return ccs_list; + } + + public Object getLocationCount(Integer recordID, Integer orgID, + Integer orgDepth) { + + List list = (List) Utils.doRequestSimple(conn, SERVICE, + METHOD_COPY_LOCATION_COUNTS, new Object[] { recordID, orgID, + orgDepth }); + return list; + + } + + public ArrayList getRecordsInfo(ArrayList ids) { + + ArrayList recordInfoArray = new ArrayList(); + + for (int i = 0; i < ids.size(); i++) { + RecordInfo recordInfo = new RecordInfo(getItemShortInfo(ids.get(i))); + recordInfoArray.add(recordInfo); + } + + return recordInfoArray; + } + + /** + * Select organisation. + * + * @param org + * the organization on witch the searches will be made + */ + public void selectOrganisation(Organisation org) { + + Log.d(TAG, "Select search organisation " + (org.level - 1) + " " + + org.id); + this.selectedOrganization = org; + + } + + public ArrayList getCopyCount(Integer recordID, + Integer orgID) { + + List list = (List) Utils.doRequestSimple(conn, SERVICE, + METHOD_GET_COPY_COUNT, new Object[] { orgID, recordID, "" }); + + ArrayList copyInfoList = new ArrayList(); + + if (list == null) + return copyInfoList; + + for (int i = 0; i < list.size(); i++) { + + CopyCountInformation copyInfo = new CopyCountInformation( + list.get(i)); + copyInfoList.add(copyInfo); + } + + return copyInfoList; + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalogListView.java b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalogListView.java index 7f98883fcf..37d1771a7b 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalogListView.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/searchCatalog/SearchCatalogListView.java @@ -55,760 +55,767 @@ import android.widget.Toast; public class SearchCatalogListView extends Activity { - private String TAG = "SearchCatalogListView"; + private String TAG = "SearchCatalogListView"; - private ArrayList recordList; + private ArrayList recordList; - private EditText searchText; + private EditText searchText; - private ImageButton searchButton; + private ImageButton searchButton; - private SearchCatalog search; + private SearchCatalog search; - private ListView lv; + private ListView lv; - private SearchArrayAdapter adapter; + private SearchArrayAdapter adapter; - private Context context; + private Context context; - private ProgressDialog progressDialog; + private ProgressDialog progressDialog; - private ArrayList searchResults; + private ArrayList searchResults; - private Spinner choseOrganisation; + private Spinner choseOrganisation; - private GlobalConfigs globalConfigs; + private GlobalConfigs globalConfigs; - private static final int PLACE_HOLD = 0; + private static final int PLACE_HOLD = 0; - private static final int DETAILS = 1; + private static final int DETAILS = 1; - private static final int BOOK_BAG = 2; + private static final int BOOK_BAG = 2; - private TextView searchResultsNumber; + private TextView searchResultsNumber; - private ArrayList bookBags; + private ArrayList bookBags; - private Integer bookbag_selected = -1; + private Integer bookbag_selected = -1; - private final ImageDownloader imageDownloader = new ImageDownloader(); + private final ImageDownloader imageDownloader = new ImageDownloader(); - private Runnable searchForResultsRunnable = null; + private Runnable searchForResultsRunnable = null; - private View searchOptionsMenu = null; + private View searchOptionsMenu = null; - private Button advancedSearchButton = null; + private Button advancedSearchButton = null; - private Button libraryHoursButton = null; + private Button libraryHoursButton = null; - private Button preferenceButton = null; + private Button preferenceButton = null; - private Button barcodeScanButton = null; + private Button barcodeScanButton = null; - private Button homeButton = null; + private Button homeButton = null; - private Button myAccountButton = null; + private Button myAccountButton = null; - private String advancedSearchString = null; + private String advancedSearchString = null; - // marks when the fetching record thread is started - private boolean loadingElements = false; + // marks when the fetching record thread is started + private boolean loadingElements = false; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.search_result_list); - setTitle("Browse catalog"); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.search_result_list); + setTitle("Browse catalog"); - myAccountButton = (Button) findViewById(R.id.my_account_button); + myAccountButton = (Button) findViewById(R.id.my_account_button); - myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(), - AccountScreenDashboard.class); - startActivity(intent); - } - }); + myAccountButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + AccountScreenDashboard.class); + startActivity(intent); + } + }); - homeButton = (Button) findViewById(R.id.library_logo); + homeButton = (Button) findViewById(R.id.library_logo); - homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - searchOptionsMenu.setVisibility(View.VISIBLE); - searchResultsNumber.setVisibility(View.INVISIBLE); - } - }); - // end header portion actions + homeButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + searchOptionsMenu.setVisibility(View.VISIBLE); + searchResultsNumber.setVisibility(View.INVISIBLE); + } + }); + // end header portion actions - advancedSearchButton = (Button) findViewById(R.id.menu_advanced_search_button); + advancedSearchButton = (Button) findViewById(R.id.menu_advanced_search_button); - advancedSearchButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - // show advanced view dialog - Intent advancedSearch = new Intent(context, - AdvancedSearchActivity.class); - startActivityForResult(advancedSearch, 2); - } - }); - // get bookbags - AccountAccess ac = AccountAccess.getAccountAccess(); - bookBags = ac.bookBags; + advancedSearchButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + // show advanced view dialog + Intent advancedSearch = new Intent(context, + AdvancedSearchActivity.class); + startActivityForResult(advancedSearch, 2); + } + }); + // get bookbags + AccountAccess ac = AccountAccess.getAccountAccess(); + bookBags = ac.bookBags; - libraryHoursButton = (Button) findViewById(R.id.library_hours_button); - libraryHoursButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - // TODO Auto-generated method stub - } - }); + libraryHoursButton = (Button) findViewById(R.id.library_hours_button); + libraryHoursButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + // TODO Auto-generated method stub + } + }); - preferenceButton = (Button) findViewById(R.id.preference_button); - preferenceButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getApplicationContext(), - ApplicationPreferences.class); - startActivity(intent); - } - }); + preferenceButton = (Button) findViewById(R.id.preference_button); + preferenceButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(getApplicationContext(), + ApplicationPreferences.class); + startActivity(intent); + } + }); - barcodeScanButton = (Button) findViewById(R.id.barcode_scan_button); - barcodeScanButton.setOnClickListener(new OnClickListener() { + barcodeScanButton = (Button) findViewById(R.id.barcode_scan_button); + barcodeScanButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent barcodeScan = new Intent(getApplicationContext(), - CaptureActivity.class); - startActivityForResult(barcodeScan, 10); - } - }); - // singleton initialize necessary IDL and Org data - globalConfigs = GlobalConfigs.getGlobalConfigs(this); + @Override + public void onClick(View v) { + Intent barcodeScan = new Intent(getApplicationContext(), + CaptureActivity.class); + startActivityForResult(barcodeScan, 10); + } + }); + // singleton initialize necessary IDL and Org data + globalConfigs = GlobalConfigs.getGlobalConfigs(this); - context = this; - search = SearchCatalog - .getInstance((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)); + context = this; + search = SearchCatalog + .getInstance((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)); - recordList = new ArrayList(); + recordList = new ArrayList(); - // Create a customized ArrayAdapter - adapter = new SearchArrayAdapter(getApplicationContext(), - R.layout.search_result_item, recordList); + // Create a customized ArrayAdapter + adapter = new SearchArrayAdapter(getApplicationContext(), + R.layout.search_result_item, recordList); - searchResultsNumber = (TextView) findViewById(R.id.search_result_number); + searchResultsNumber = (TextView) findViewById(R.id.search_result_number); - // Get reference to ListView holder - lv = (ListView) this.findViewById(R.id.search_results_list); + // Get reference to ListView holder + lv = (ListView) this.findViewById(R.id.search_results_list); - searchOptionsMenu = findViewById(R.id.search_preference_options); + searchOptionsMenu = findViewById(R.id.search_preference_options); - progressDialog = new ProgressDialog(context); - - // Set the ListView adapter - lv.setAdapter(adapter); - - searchResults = new ArrayList(); - - registerForContextMenu(lv); - - searchForResultsRunnable = new Runnable() { - - @Override - public void run() { - - final String text = searchText.getText().toString(); - - if (text.length() < 1) - return; - - runOnUiThread(new Runnable() { - @Override - public void run() { - - InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0); + progressDialog = new ProgressDialog(context); - searchOptionsMenu.setVisibility(View.GONE); - searchResultsNumber.setVisibility(View.VISIBLE); - - progressDialog = ProgressDialog.show(context, - getResources().getText(R.string.dialog_please_wait), getResources().getText(R.string.dialog_fetching_data_message)); - } - }); - - try { - searchResults = search.getSearchResults(text, 0); - } catch (NoNetworkAccessException e) { - System.out.println("no network access in search"); - SearchCatalogListView.this.runOnUiThread(Utils - .showNetworkNotAvailableDialog(context)); - - } catch (NoAccessToServer e) { - SearchCatalogListView.this.runOnUiThread(Utils - .showServerNotAvailableDialog(context)); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - - recordList.clear(); - - if (searchResults.size() > 0) { - - for (int j = 0; j < searchResults.size(); j++) - recordList.add(searchResults.get(j)); - - // add extra record to display more option button - /* - * if (search.visible > recordList.size()) { - * recordList.add(new RecordInfo()); - * searchResultsNumber.setText(+recordList.size() - - * 1 + " out of " + search.visible); } else - */ - } - searchResultsNumber.setText(+recordList.size() - + " out of " + search.visible); - - adapter.notifyDataSetChanged(); - progressDialog.dismiss(); - - } - }); - - } - }; - - lv.setOnItemClickListener(new OnItemClickListener() { - - @Override - public void onItemClick(AdapterView arg0, View arg1, - int position, long arg3) { + // Set the ListView adapter + lv.setAdapter(adapter); + + searchResults = new ArrayList(); + + registerForContextMenu(lv); + + searchForResultsRunnable = new Runnable() { + + @Override + public void run() { + + final String text = searchText.getText().toString(); + + if (text.length() < 1) + return; + + runOnUiThread(new Runnable() { + @Override + public void run() { + + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow( + searchText.getWindowToken(), 0); + + searchOptionsMenu.setVisibility(View.GONE); + searchResultsNumber.setVisibility(View.VISIBLE); + + progressDialog = ProgressDialog.show( + context, + getResources().getText( + R.string.dialog_please_wait), + getResources().getText( + R.string.dialog_fetching_data_message)); + } + }); + + try { + searchResults = search.getSearchResults(text, 0); + } catch (NoNetworkAccessException e) { + System.out.println("no network access in search"); + SearchCatalogListView.this.runOnUiThread(Utils + .showNetworkNotAvailableDialog(context)); + + } catch (NoAccessToServer e) { + SearchCatalogListView.this.runOnUiThread(Utils + .showServerNotAvailableDialog(context)); + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + + recordList.clear(); + + if (searchResults.size() > 0) { + + for (int j = 0; j < searchResults.size(); j++) + recordList.add(searchResults.get(j)); + + // add extra record to display more option button + /* + * if (search.visible > recordList.size()) { + * recordList.add(new RecordInfo()); + * searchResultsNumber.setText(+recordList.size() - + * 1 + " out of " + search.visible); } else + */ + } + searchResultsNumber.setText(+recordList.size() + + " out of " + search.visible); + + adapter.notifyDataSetChanged(); + progressDialog.dismiss(); + + } + }); + + } + }; - RecordInfo info = (RecordInfo) lv.getItemAtPosition(position); + lv.setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(AdapterView arg0, View arg1, + int position, long arg3) { - if (info.dummy == true) { - // this is the more view item button - progressDialog = new ProgressDialog(context); + RecordInfo info = (RecordInfo) lv.getItemAtPosition(position); + + if (info.dummy == true) { + // this is the more view item button + progressDialog = new ProgressDialog(context); - progressDialog.setMessage("Fetching data"); - progressDialog.show(); - final String text = searchText.getText().toString(); - - Thread searchThreadwithOffset = new Thread(new Runnable() { - - @Override - public void run() { - - searchResults.clear(); - - try { - searchResults = search.getSearchResults(text, - recordList.size() - 1); - } catch (NoNetworkAccessException e) { - runOnUiThread(Utils - .showNetworkNotAvailableDialog(context)); - } catch (NoAccessToServer e) { - runOnUiThread(Utils - .showServerNotAvailableDialog(context)); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - - // don't clear record list - // recordList.clear(); - if (searchResults.size() > 0) { - - // remove previous more button - recordList.remove(recordList.size() - 1); - - for (int j = 0; j < searchResults - .size(); j++) - recordList.add(searchResults.get(j)); - - // add extra record to display more - // option button - if (search.visible > recordList.size()) { - recordList.add(new RecordInfo()); - searchResultsNumber.setText(adapter - .getCount() - - 1 - + " out of " - + search.visible); - } else - searchResultsNumber.setText(adapter - .getCount() - + " out of " - + search.visible); - } else { - searchResultsNumber.setText(adapter - .getCount() - + " out of " - + search.visible); - } - adapter.notifyDataSetChanged(); - progressDialog.dismiss(); - } - }); - - } - }); - - searchThreadwithOffset.start(); - } else { - // start activity with book details - - Intent intent = new Intent(getBaseContext(), - SampleUnderlinesNoFade.class); - // serialize object and pass it to next activity - intent.putExtra("recordInfo", info); - intent.putExtra("orgID", search.selectedOrganization.id); - intent.putExtra("depth", - (search.selectedOrganization.level - 1)); - - intent.putExtra("recordList", recordList); - intent.putExtra("recordPosition", position); - startActivity(intent); - } - } - }); - - lv.setOnScrollListener(new OnScrollListener() { - - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - // TODO Auto-generated method stub - - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, - int visibleItemCount, int totalItemCount) { - // TODO Auto-generated method stub - - if (!loadingElements) { - - Log.d(TAG, " Scroll adapter " + totalItemCount + " " - + visibleItemCount + " " + firstVisibleItem + " " - + adapter.getCount() + " " + search.visible); - if (totalItemCount > 0 - && (((totalItemCount - visibleItemCount) <= (firstVisibleItem)) && adapter - .getCount() < search.visible)) { - loadingElements = true; - Log.d(TAG, "Load more data"); - progressDialog = new ProgressDialog(context); - - progressDialog.setMessage(getResources().getText(R.string.dialog_load_more_message)); - progressDialog.show(); - - Thread searchThreadwithOffset = new Thread( - new Runnable() { - - @Override - public void run() { - - String text = searchText.getText() - .toString(); - searchResults.clear(); - - try { - searchResults = search - .getSearchResults( - text, - adapter.getCount()); - } catch (NoNetworkAccessException e) { - runOnUiThread(Utils - .showNetworkNotAvailableDialog(context)); - } catch (NoAccessToServer e) { - runOnUiThread(Utils - .showServerNotAvailableDialog(context)); - } - - runOnUiThread(new Runnable() { - - @Override - public void run() { - - // don't clear record list - // recordList.clear(); - System.out.println("Returned " + searchResults.size() + " elements from search"); - if (searchResults.size() > 0) { - - for (int j = 0; j < searchResults - .size(); j++) - recordList - .add(searchResults - .get(j)); - - } - - searchResultsNumber.setText(adapter - .getCount() - + " out of " - + search.visible); - - adapter.notifyDataSetChanged(); - progressDialog.dismiss(); - loadingElements = false; - } - }); - - } - }); - - searchThreadwithOffset.start(); - } - } - } - }); - - searchText = (EditText) findViewById(R.id.searchText); - - // enter key now is labeled "Search" on virtual keyboard - searchText.setImeActionLabel("Search", EditorInfo.IME_ACTION_SEARCH); - searchText.setImeOptions(EditorInfo.IME_ACTION_SEARCH); - - // enter key on virtual keyboard starts the search - searchText.setOnKeyListener(new OnKeyListener() { - public boolean onKey(View v, int keyCode, KeyEvent event) { - // If the event is a key-down event on the "enter" button - if ((event.getAction() == KeyEvent.ACTION_DOWN) - && ((keyCode == KeyEvent.KEYCODE_ENTER) || keyCode == EditorInfo.IME_ACTION_SEARCH)) { - // Perform action on key press - Thread searchThread = new Thread(searchForResultsRunnable); - searchThread.start(); - return true; - } - return false; - } - }); - - choseOrganisation = (Spinner) findViewById(R.id.chose_organisation); - - searchButton = (ImageButton) findViewById(R.id.searchButton); - - searchButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - Thread searchThread = new Thread(searchForResultsRunnable); - searchThread.start(); - } - }); - - int selectedPos = 0; - ArrayList list = new ArrayList(); - if (globalConfigs.organisations != null) { - for (int i = 0; i < globalConfigs.organisations.size(); i++) { - list.add(globalConfigs.organisations.get(i).padding - + globalConfigs.organisations.get(i).name); - - if (globalConfigs.organisations.get(i).level - 1 == 0) - selectedPos = i; - } - } - ArrayAdapter adapter = new ArrayAdapter(this, - layout.spinner_layout, list); - choseOrganisation.setAdapter(adapter); - - choseOrganisation.setSelection(selectedPos); - - choseOrganisation - .setOnItemSelectedListener(new OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView arg0, View arg1, - int ID, long arg3) { - // select the specific organization - search.selectOrganisation(globalConfigs.organisations - .get(ID)); - } - - @Override - public void onNothingSelected(AdapterView arg0) { - - } - - }); - - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater menuInflater = getMenuInflater(); - menuInflater.inflate(R.menu.search_menu, menu); - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show(); - break; - - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { - - Log.d(TAG, "context menu"); - if (v.getId() == R.id.search_results_list) { - - AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; - menu.setHeaderTitle("Options"); - - menu.add(Menu.NONE, DETAILS, 0, "Details"); - menu.add(Menu.NONE, PLACE_HOLD, 1, "Place Hold"); - menu.add(Menu.NONE, BOOK_BAG, 2, "Add to bookbag"); - - } - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - AdapterView.AdapterContextMenuInfo menuArrayItem = (AdapterView.AdapterContextMenuInfo) item - .getMenuInfo(); - int menuItemIndex = item.getItemId(); - - final RecordInfo info = (RecordInfo) lv - .getItemAtPosition(menuArrayItem.position); - // start activity with book details - - switch (item.getItemId()) { - - case DETAILS: { - - Intent intent = new Intent(getBaseContext(), - SampleUnderlinesNoFade.class); - // serialize object and pass it to next activity - intent.putExtra("recordInfo", info); - intent.putExtra("orgID", search.selectedOrganization.id); - intent.putExtra("depth", (search.selectedOrganization.level - 1)); - - intent.putExtra("recordList", recordList); - // TODO put total number - intent.putExtra("recordPosition", menuArrayItem.position); - startActivity(intent); - } - break; - case PLACE_HOLD: { - - Intent intent = new Intent(getBaseContext(), PlaceHold.class); - - intent.putExtra("recordInfo", info); - - startActivity(intent); - } - break; - case BOOK_BAG: { - - if (bookBags.size() > 0) { - String array_spinner[] = new String[bookBags.size()]; - - for (int i = 0; i < array_spinner.length; i++) - array_spinner[i] = bookBags.get(i).name; - - AlertDialog.Builder builder; - - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(LAYOUT_INFLATER_SERVICE); - View layout = inflater.inflate(R.layout.bookbag_spinner, null); - - Spinner s = (Spinner) layout.findViewById(R.id.bookbag_spinner); - - Button add = (Button) layout - .findViewById(R.id.add_to_bookbag_button); - ArrayAdapter adapter = new ArrayAdapter(context, - android.R.layout.simple_spinner_item, array_spinner); - - s.setAdapter(adapter); - builder = new AlertDialog.Builder(context); - builder.setView(layout); - final AlertDialog alertDialog = builder.create(); - - add.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - // TODO Auto-generated method stub - Thread addtoBookbag = new Thread(new Runnable() { - @Override - public void run() { - AccountAccess ac = AccountAccess - .getAccountAccess(); - try { - ac.addRecordToBookBag(info.doc_id, - bookBags.get(bookbag_selected).id); - } catch (SessionNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoAccessToServer e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoNetworkAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - alertDialog.dismiss(); - } - }); - - } - }); - progressDialog = ProgressDialog.show(context, - "Please wait", "Add to bookbag"); - addtoBookbag.start(); - - } - }); - alertDialog.show(); - - s.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView arg0, View arg1, - int position, long arg3) { - bookbag_selected = position; - } - - @Override - public void onNothingSelected(AdapterView arg0) { - } - - }); - } else - Toast.makeText(context, "No bookbags", Toast.LENGTH_SHORT) - .show(); - } - break; - } - - return super.onContextItemSelected(item); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - - switch (resultCode) { - - case AdvancedSearchActivity.RESULT_ADVANCED_SEARCH: { - Log.d(TAG, - "result text" + data.getStringExtra("advancedSearchText")); - searchText.setText(data.getStringExtra("advancedSearchText")); - Thread searchThread = new Thread(searchForResultsRunnable); - searchThread.start(); - } - break; - - case CaptureActivity.BARCODE_SEARCH: { - searchText.setText("identifier|isbn: " - + data.getStringExtra("barcodeValue")); - Thread searchThread = new Thread(searchForResultsRunnable); - searchThread.start(); - } - - } - } - - class SearchArrayAdapter extends ArrayAdapter { - - private static final String tag = "SearchArrayAdapter"; - private Context context; - private ImageView recordImage; - private TextView recordTitle; - private TextView recordAuthor; - private TextView recordPublisher; - - private List records = new ArrayList(); - - public SearchArrayAdapter(Context context, int textViewResourceId, - List objects) { - super(context, textViewResourceId, objects); - this.context = context; - this.records = objects; - } - - public int getCount() { - return this.records.size(); - } - - public RecordInfo getItem(int index) { - return this.records.get(index); - } - - public View getView(int position, View convertView, ViewGroup parent) { - View row = convertView; - - // Get item - RecordInfo record = getItem(position); - - if (record.dummy == true) { - Log.d(tag, "Starting XML view more infaltion ... "); - LayoutInflater inflater = (LayoutInflater) this.getContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.search_result_footer_view, - parent, false); - Log.d(tag, "Successfully completed XML view more Inflation!"); - - } else { - - // if it is the right type of view - if (row == null - || row.findViewById(R.id.search_record_title) == null) { - - Log.d(tag, "Starting XML Row Inflation ... "); - LayoutInflater inflater = (LayoutInflater) this - .getContext().getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - row = inflater.inflate(R.layout.search_result_item, parent, - false); - Log.d(tag, "Successfully completed XML Row Inflation!"); - - } - - Log.d(TAG, "reord image value " + recordImage); - // Get reference to ImageView - recordImage = (ImageView) row - .findViewById(R.id.search_record_img); - // TODO fix bugs + features - String imageHref = GlobalConfigs.httpAddress - + "/opac/extras/ac/jacket/small/" + record.isbn; - // start async download of image - imageDownloader.download(imageHref, recordImage); - // Get reference to TextView - title - recordTitle = (TextView) row - .findViewById(R.id.search_record_title); - - // Get reference to TextView - author - recordAuthor = (TextView) row - .findViewById(R.id.search_record_author); - - // Get referance to TextView - record Publisher date+publisher - recordPublisher = (TextView) row - .findViewById(R.id.search_record_publishing); - - // set text - recordTitle.setText(record.title); - recordAuthor.setText(record.author); - recordPublisher - .setText(record.pubdate + " " + record.publisher); - } - return row; - } - } + progressDialog.setMessage("Fetching data"); + progressDialog.show(); + final String text = searchText.getText().toString(); + + Thread searchThreadwithOffset = new Thread(new Runnable() { + + @Override + public void run() { + + searchResults.clear(); + + try { + searchResults = search.getSearchResults(text, + recordList.size() - 1); + } catch (NoNetworkAccessException e) { + runOnUiThread(Utils + .showNetworkNotAvailableDialog(context)); + } catch (NoAccessToServer e) { + runOnUiThread(Utils + .showServerNotAvailableDialog(context)); + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + + // don't clear record list + // recordList.clear(); + if (searchResults.size() > 0) { + + // remove previous more button + recordList.remove(recordList.size() - 1); + + for (int j = 0; j < searchResults + .size(); j++) + recordList.add(searchResults.get(j)); + + // add extra record to display more + // option button + if (search.visible > recordList.size()) { + recordList.add(new RecordInfo()); + searchResultsNumber.setText(adapter + .getCount() + - 1 + + " out of " + + search.visible); + } else + searchResultsNumber.setText(adapter + .getCount() + + " out of " + + search.visible); + } else { + searchResultsNumber.setText(adapter + .getCount() + + " out of " + + search.visible); + } + adapter.notifyDataSetChanged(); + progressDialog.dismiss(); + } + }); + + } + }); + + searchThreadwithOffset.start(); + } else { + // start activity with book details + + Intent intent = new Intent(getBaseContext(), + SampleUnderlinesNoFade.class); + // serialize object and pass it to next activity + intent.putExtra("recordInfo", info); + intent.putExtra("orgID", search.selectedOrganization.id); + intent.putExtra("depth", + (search.selectedOrganization.level - 1)); + + intent.putExtra("recordList", recordList); + intent.putExtra("recordPosition", position); + startActivity(intent); + } + } + }); + + lv.setOnScrollListener(new OnScrollListener() { + + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { + // TODO Auto-generated method stub + + } + + @Override + public void onScroll(AbsListView view, int firstVisibleItem, + int visibleItemCount, int totalItemCount) { + // TODO Auto-generated method stub + + if (!loadingElements) { + + Log.d(TAG, " Scroll adapter " + totalItemCount + " " + + visibleItemCount + " " + firstVisibleItem + " " + + adapter.getCount() + " " + search.visible); + if (totalItemCount > 0 + && (((totalItemCount - visibleItemCount) <= (firstVisibleItem)) && adapter + .getCount() < search.visible)) { + loadingElements = true; + Log.d(TAG, "Load more data"); + progressDialog = new ProgressDialog(context); + + progressDialog.setMessage(getResources().getText( + R.string.dialog_load_more_message)); + progressDialog.show(); + + Thread searchThreadwithOffset = new Thread( + new Runnable() { + + @Override + public void run() { + + String text = searchText.getText() + .toString(); + searchResults.clear(); + + try { + searchResults = search + .getSearchResults(text, + adapter.getCount()); + } catch (NoNetworkAccessException e) { + runOnUiThread(Utils + .showNetworkNotAvailableDialog(context)); + } catch (NoAccessToServer e) { + runOnUiThread(Utils + .showServerNotAvailableDialog(context)); + } + + runOnUiThread(new Runnable() { + + @Override + public void run() { + + // don't clear record list + // recordList.clear(); + System.out.println("Returned " + + searchResults.size() + + " elements from search"); + if (searchResults.size() > 0) { + + for (int j = 0; j < searchResults + .size(); j++) + recordList + .add(searchResults + .get(j)); + + } + + searchResultsNumber.setText(adapter + .getCount() + + " out of " + + search.visible); + + adapter.notifyDataSetChanged(); + progressDialog.dismiss(); + loadingElements = false; + } + }); + + } + }); + + searchThreadwithOffset.start(); + } + } + } + }); + + searchText = (EditText) findViewById(R.id.searchText); + + // enter key now is labeled "Search" on virtual keyboard + searchText.setImeActionLabel("Search", EditorInfo.IME_ACTION_SEARCH); + searchText.setImeOptions(EditorInfo.IME_ACTION_SEARCH); + + // enter key on virtual keyboard starts the search + searchText.setOnKeyListener(new OnKeyListener() { + public boolean onKey(View v, int keyCode, KeyEvent event) { + // If the event is a key-down event on the "enter" button + if ((event.getAction() == KeyEvent.ACTION_DOWN) + && ((keyCode == KeyEvent.KEYCODE_ENTER) || keyCode == EditorInfo.IME_ACTION_SEARCH)) { + // Perform action on key press + Thread searchThread = new Thread(searchForResultsRunnable); + searchThread.start(); + return true; + } + return false; + } + }); + + choseOrganisation = (Spinner) findViewById(R.id.chose_organisation); + + searchButton = (ImageButton) findViewById(R.id.searchButton); + + searchButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Thread searchThread = new Thread(searchForResultsRunnable); + searchThread.start(); + } + }); + + int selectedPos = 0; + ArrayList list = new ArrayList(); + if (globalConfigs.organisations != null) { + for (int i = 0; i < globalConfigs.organisations.size(); i++) { + list.add(globalConfigs.organisations.get(i).padding + + globalConfigs.organisations.get(i).name); + + if (globalConfigs.organisations.get(i).level - 1 == 0) + selectedPos = i; + } + } + ArrayAdapter adapter = new ArrayAdapter(this, + layout.spinner_layout, list); + choseOrganisation.setAdapter(adapter); + + choseOrganisation.setSelection(selectedPos); + + choseOrganisation + .setOnItemSelectedListener(new OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView arg0, View arg1, + int ID, long arg3) { + // select the specific organization + search.selectOrganisation(globalConfigs.organisations + .get(ID)); + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + + }); + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater menuInflater = getMenuInflater(); + menuInflater.inflate(R.menu.search_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show(); + break; + + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, + ContextMenuInfo menuInfo) { + + Log.d(TAG, "context menu"); + if (v.getId() == R.id.search_results_list) { + + AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; + menu.setHeaderTitle("Options"); + + menu.add(Menu.NONE, DETAILS, 0, "Details"); + menu.add(Menu.NONE, PLACE_HOLD, 1, "Place Hold"); + menu.add(Menu.NONE, BOOK_BAG, 2, "Add to bookbag"); + + } + } + + @Override + public boolean onContextItemSelected(MenuItem item) { + AdapterView.AdapterContextMenuInfo menuArrayItem = (AdapterView.AdapterContextMenuInfo) item + .getMenuInfo(); + int menuItemIndex = item.getItemId(); + + final RecordInfo info = (RecordInfo) lv + .getItemAtPosition(menuArrayItem.position); + // start activity with book details + + switch (item.getItemId()) { + + case DETAILS: { + + Intent intent = new Intent(getBaseContext(), + SampleUnderlinesNoFade.class); + // serialize object and pass it to next activity + intent.putExtra("recordInfo", info); + intent.putExtra("orgID", search.selectedOrganization.id); + intent.putExtra("depth", (search.selectedOrganization.level - 1)); + + intent.putExtra("recordList", recordList); + // TODO put total number + intent.putExtra("recordPosition", menuArrayItem.position); + startActivity(intent); + } + break; + case PLACE_HOLD: { + + Intent intent = new Intent(getBaseContext(), PlaceHold.class); + + intent.putExtra("recordInfo", info); + + startActivity(intent); + } + break; + case BOOK_BAG: { + + if (bookBags.size() > 0) { + String array_spinner[] = new String[bookBags.size()]; + + for (int i = 0; i < array_spinner.length; i++) + array_spinner[i] = bookBags.get(i).name; + + AlertDialog.Builder builder; + + LayoutInflater inflater = (LayoutInflater) context + .getSystemService(LAYOUT_INFLATER_SERVICE); + View layout = inflater.inflate(R.layout.bookbag_spinner, null); + + Spinner s = (Spinner) layout.findViewById(R.id.bookbag_spinner); + + Button add = (Button) layout + .findViewById(R.id.add_to_bookbag_button); + ArrayAdapter adapter = new ArrayAdapter(context, + android.R.layout.simple_spinner_item, array_spinner); + + s.setAdapter(adapter); + builder = new AlertDialog.Builder(context); + builder.setView(layout); + final AlertDialog alertDialog = builder.create(); + + add.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // TODO Auto-generated method stub + Thread addtoBookbag = new Thread(new Runnable() { + @Override + public void run() { + AccountAccess ac = AccountAccess + .getAccountAccess(); + try { + ac.addRecordToBookBag(info.doc_id, + bookBags.get(bookbag_selected).id); + } catch (SessionNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + alertDialog.dismiss(); + } + }); + + } + }); + progressDialog = ProgressDialog.show(context, + "Please wait", "Add to bookbag"); + addtoBookbag.start(); + + } + }); + alertDialog.show(); + + s.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView arg0, View arg1, + int position, long arg3) { + bookbag_selected = position; + } + + @Override + public void onNothingSelected(AdapterView arg0) { + } + + }); + } else + Toast.makeText(context, "No bookbags", Toast.LENGTH_SHORT) + .show(); + } + break; + } + + return super.onContextItemSelected(item); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + + switch (resultCode) { + + case AdvancedSearchActivity.RESULT_ADVANCED_SEARCH: { + Log.d(TAG, + "result text" + data.getStringExtra("advancedSearchText")); + searchText.setText(data.getStringExtra("advancedSearchText")); + Thread searchThread = new Thread(searchForResultsRunnable); + searchThread.start(); + } + break; + + case CaptureActivity.BARCODE_SEARCH: { + searchText.setText("identifier|isbn: " + + data.getStringExtra("barcodeValue")); + Thread searchThread = new Thread(searchForResultsRunnable); + searchThread.start(); + } + + } + } + + class SearchArrayAdapter extends ArrayAdapter { + + private static final String tag = "SearchArrayAdapter"; + private Context context; + private ImageView recordImage; + private TextView recordTitle; + private TextView recordAuthor; + private TextView recordPublisher; + + private List records = new ArrayList(); + + public SearchArrayAdapter(Context context, int textViewResourceId, + List objects) { + super(context, textViewResourceId, objects); + this.context = context; + this.records = objects; + } + + public int getCount() { + return this.records.size(); + } + + public RecordInfo getItem(int index) { + return this.records.get(index); + } + + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + + // Get item + RecordInfo record = getItem(position); + + if (record.dummy == true) { + Log.d(tag, "Starting XML view more infaltion ... "); + LayoutInflater inflater = (LayoutInflater) this.getContext() + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.search_result_footer_view, + parent, false); + Log.d(tag, "Successfully completed XML view more Inflation!"); + + } else { + + // if it is the right type of view + if (row == null + || row.findViewById(R.id.search_record_title) == null) { + + Log.d(tag, "Starting XML Row Inflation ... "); + LayoutInflater inflater = (LayoutInflater) this + .getContext().getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + row = inflater.inflate(R.layout.search_result_item, parent, + false); + Log.d(tag, "Successfully completed XML Row Inflation!"); + + } + + Log.d(TAG, "reord image value " + recordImage); + // Get reference to ImageView + recordImage = (ImageView) row + .findViewById(R.id.search_record_img); + // TODO fix bugs + features + String imageHref = GlobalConfigs.httpAddress + + "/opac/extras/ac/jacket/small/" + record.isbn; + // start async download of image + imageDownloader.download(imageHref, recordImage); + // Get reference to TextView - title + recordTitle = (TextView) row + .findViewById(R.id.search_record_title); + + // Get reference to TextView - author + recordAuthor = (TextView) row + .findViewById(R.id.search_record_author); + + // Get referance to TextView - record Publisher date+publisher + recordPublisher = (TextView) row + .findViewById(R.id.search_record_publishing); + + // set text + recordTitle.setText(record.title); + recordAuthor.setText(record.author); + recordPublisher + .setText(record.pubdate + " " + record.publisher); + } + return row; + } + } } \ No newline at end of file diff --git a/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationAlert.java b/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationAlert.java index 77c64e5d79..04b7ca198e 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationAlert.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationAlert.java @@ -8,40 +8,42 @@ import org.androwrapee.db.IdField; @DatabaseClass public class NotificationAlert { - - public static final String tableName = "notifications"; - - public static final int NOTIFICATION_INTENT = 123456; - - @IdField - public long id; - - @DatabaseField - public int intent_val; - - @DatabaseField - public Date triggerDate; - - @DatabaseField - public String message; - - //required constructor for DAO - public NotificationAlert(){ - - } - - public NotificationAlert(int id, int intent_val, Date triggerDate, String message ){ - - this.id = id; - this.intent_val = intent_val; - this.triggerDate = triggerDate; - this.message = message; - } - - - @Override - public String toString() { - - return " Notification:[ id: " + id+ "; intent_val: "+intent_val+"; triggerDate : "+triggerDate+"; message: "+message+"]"; - } + + public static final String tableName = "notifications"; + + public static final int NOTIFICATION_INTENT = 123456; + + @IdField + public long id; + + @DatabaseField + public int intent_val; + + @DatabaseField + public Date triggerDate; + + @DatabaseField + public String message; + + // required constructor for DAO + public NotificationAlert() { + + } + + public NotificationAlert(int id, int intent_val, Date triggerDate, + String message) { + + this.id = id; + this.intent_val = intent_val; + this.triggerDate = triggerDate; + this.message = message; + } + + @Override + public String toString() { + + return " Notification:[ id: " + id + "; intent_val: " + intent_val + + "; triggerDate : " + triggerDate + "; message: " + message + + "]"; + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationReceiver.java b/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationReceiver.java index af0c2210d7..d579c21ae6 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationReceiver.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/services/NotificationReceiver.java @@ -13,44 +13,43 @@ import android.util.Log; public class NotificationReceiver extends BroadcastReceiver { - private String TAG = "NotificationManager"; - public static final int NOTIFICATION_ID = 1; + private String TAG = "NotificationManager"; + public static final int NOTIFICATION_ID = 1; - @Override - public void onReceive(Context context, Intent intent) { + @Override + public void onReceive(Context context, Intent intent) { - String ns = Context.NOTIFICATION_SERVICE; - NotificationManager mNotificationManager = (NotificationManager) context - .getSystemService(ns); + String ns = Context.NOTIFICATION_SERVICE; + NotificationManager mNotificationManager = (NotificationManager) context + .getSystemService(ns); - - String checkoutMessage = intent.getStringExtra("checkoutMesage"); + String checkoutMessage = intent.getStringExtra("checkoutMesage"); - Log.d(TAG, "Message " + checkoutMessage); - // send notification + Log.d(TAG, "Message " + checkoutMessage); + // send notification - int icon = android.R.drawable.ic_dialog_alert; - CharSequence tickerText = "Checkout item due date"; - long when = System.currentTimeMillis(); + int icon = android.R.drawable.ic_dialog_alert; + CharSequence tickerText = "Checkout item due date"; + long when = System.currentTimeMillis(); - Notification notification = new Notification(icon, tickerText, when); + Notification notification = new Notification(icon, tickerText, when); - notification.defaults |= Notification.FLAG_AUTO_CANCEL; - - CharSequence contentTitle = "EG - checkout item due date"; - CharSequence contentText = checkoutMessage; - // start evergreen - Intent notificationIntent = new Intent(context, SplashActivity.class); - notificationIntent.putExtra("jump", "checkout_items"); + notification.defaults |= Notification.FLAG_AUTO_CANCEL; - PendingIntent contentIntent = PendingIntent.getActivity(context, 0, - notificationIntent, 0); + CharSequence contentTitle = "EG - checkout item due date"; + CharSequence contentText = checkoutMessage; + // start evergreen + Intent notificationIntent = new Intent(context, SplashActivity.class); + notificationIntent.putExtra("jump", "checkout_items"); - notification.setLatestEventInfo(context, contentTitle, contentText, - contentIntent); + PendingIntent contentIntent = PendingIntent.getActivity(context, 0, + notificationIntent, 0); - mNotificationManager.notify(NOTIFICATION_ID, notification); + notification.setLatestEventInfo(context, contentTitle, contentText, + contentIntent); - } + mNotificationManager.notify(NOTIFICATION_ID, notification); + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/services/PeriodicServiceBroadcastReceiver.java b/Open-ILS/src/Android/src/org/evergreen/android/services/PeriodicServiceBroadcastReceiver.java index a341342919..f1e87f1a82 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/services/PeriodicServiceBroadcastReceiver.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/services/PeriodicServiceBroadcastReceiver.java @@ -13,57 +13,55 @@ import android.util.Log; public class PeriodicServiceBroadcastReceiver extends BroadcastReceiver { - public static final int INTENT_ID = 123; + public static final int INTENT_ID = 123; - @Override - public void onReceive(Context context, Intent intent) { + @Override + public void onReceive(Context context, Intent intent) { - // do update logic - boolean mustDoUpdate = false; + // do update logic + boolean mustDoUpdate = false; - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(context); + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); - // determine if to use alerts or not - boolean use_notifications = prefs.getBoolean("notifications_enabled", - false); + // determine if to use alerts or not + boolean use_notifications = prefs.getBoolean("notifications_enabled", + false); - if (use_notifications) { - // if no updates have been made - Calendar current = Calendar.getInstance(); - Calendar lastUpdateTime = Calendar.getInstance(); - lastUpdateTime - .setTimeInMillis(prefs.getLong("lastUpdateTime", 0)); + if (use_notifications) { + // if no updates have been made + Calendar current = Calendar.getInstance(); + Calendar lastUpdateTime = Calendar.getInstance(); + lastUpdateTime.setTimeInMillis(prefs.getLong("lastUpdateTime", 0)); - lastUpdateTime.add(Calendar.DAY_OF_MONTH, - ScheduledIntentService.SCHEDULE_TIME_INTERVAL); + lastUpdateTime.add(Calendar.DAY_OF_MONTH, + ScheduledIntentService.SCHEDULE_TIME_INTERVAL); - // if the last update time + elapsed scheduled time < current - // time we must do an update - if (lastUpdateTime.compareTo(current) == -1) { - mustDoUpdate = true; - } + // if the last update time + elapsed scheduled time < current + // time we must do an update + if (lastUpdateTime.compareTo(current) == -1) { + mustDoUpdate = true; + } + Log.d("app", "Network connectivity change or alarm must do update " + + mustDoUpdate); - Log.d("app", "Network connectivity change or alarm must do update " - + mustDoUpdate); + ConnectivityManager connMgr = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); - ConnectivityManager connMgr = (ConnectivityManager) context - .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + // if internet available + if (networkInfo != null && networkInfo.isConnected()) { - NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); - // if internet available - if (networkInfo != null && networkInfo.isConnected()) { - - if (mustDoUpdate == true) { - Intent intentService = new Intent(context, - ScheduledIntentService.class); - context.startService(intentService); - } - } + if (mustDoUpdate == true) { + Intent intentService = new Intent(context, + ScheduledIntentService.class); + context.startService(intentService); + } + } - } + } - } + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/services/RebootReceiver.java b/Open-ILS/src/Android/src/org/evergreen/android/services/RebootReceiver.java index 70cbd88036..ad3bf976e5 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/services/RebootReceiver.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/services/RebootReceiver.java @@ -12,33 +12,40 @@ import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.widget.Toast; -public class RebootReceiver extends BroadcastReceiver{ - - @Override - public void onReceive(Context context, Intent arg1) { - //reinitialize notifications - - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); - - if(sharedPreferences.getBoolean("notifications_enabled", false)){ - - Toast.makeText(context, "Set up notification updates", Toast.LENGTH_SHORT).show(); - //if enabled register the update service to run once per day - // get a Calendar object with current time - Calendar cal = Calendar.getInstance(); - - Intent bRecvIntent = new Intent(context,PeriodicServiceBroadcastReceiver.class); - bRecvIntent.setAction(ScheduledIntentService.ACTION); - // update the current intent if it exists - PendingIntent sender = PendingIntent.getBroadcast(context, - NotificationAlert.NOTIFICATION_INTENT + PeriodicServiceBroadcastReceiver.INTENT_ID, bRecvIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - - // Get the AlarmManager service - AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE); - am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 10000 * ScheduledIntentService.SCHEDULE_TIME_INTERVAL, sender); - } - - } +public class RebootReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent arg1) { + // reinitialize notifications + + SharedPreferences sharedPreferences = PreferenceManager + .getDefaultSharedPreferences(context); + + if (sharedPreferences.getBoolean("notifications_enabled", false)) { + + Toast.makeText(context, "Set up notification updates", + Toast.LENGTH_SHORT).show(); + // if enabled register the update service to run once per day + // get a Calendar object with current time + Calendar cal = Calendar.getInstance(); + + Intent bRecvIntent = new Intent(context, + PeriodicServiceBroadcastReceiver.class); + bRecvIntent.setAction(ScheduledIntentService.ACTION); + // update the current intent if it exists + PendingIntent sender = PendingIntent.getBroadcast(context, + NotificationAlert.NOTIFICATION_INTENT + + PeriodicServiceBroadcastReceiver.INTENT_ID, + bRecvIntent, PendingIntent.FLAG_UPDATE_CURRENT); + + // Get the AlarmManager service + AlarmManager am = (AlarmManager) context + .getSystemService(Activity.ALARM_SERVICE); + am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), + 10000 * ScheduledIntentService.SCHEDULE_TIME_INTERVAL, + sender); + } + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/services/ScheduledIntentService.java b/Open-ILS/src/Android/src/org/evergreen/android/services/ScheduledIntentService.java index 471087a709..8215726bef 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/services/ScheduledIntentService.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/services/ScheduledIntentService.java @@ -26,156 +26,184 @@ import android.net.ConnectivityManager; import android.preference.PreferenceManager; import android.util.Log; -public class ScheduledIntentService extends IntentService{ - - public static Date lastUpdateServiceDate; - - public static String TAG = "ScheduledIntentService"; - - public static String ACTION = "org.evergreen.updateservice"; - - //fire up once a day - public static int SCHEDULE_TIME_INTERVAL = 1; - - public ScheduledIntentService(){ - super("EvergreenIntentService"); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - Log.d(TAG, "Start service"); - - return super.onStartCommand(intent, flags, startId); - } - - @Override - protected void onHandleIntent(Intent intent) { - - Date currentDate = new Date(System.currentTimeMillis()); - - Log.d(TAG, "Notifications service started"); - - /* Download the necessary IDL files for checkout items operations like au (for auth), circ, mvr and acp - */ - String idlFile = GlobalConfigs.IDL_FILE_FROM_ROOT + "?class=circ&class=au&class=mvr&class=acp"; - try{ - Log.d("debug","Read fm"); - InputStream in_IDL = Utils.getNetInputStream(GlobalConfigs.httpAddress + idlFile); - IDLParser parser = new IDLParser(in_IDL); - parser.parse(); - }catch(Exception e){ - System.err.println("Error in parsing IDL file " + idlFile + " " + e.getMessage()); - }; - - //login with the user credentials - AccountAccess accountAccess = AccountAccess.getAccountAccess(GlobalConfigs.httpAddress, (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE)); - boolean auth = true; - try { - accountAccess.authenticate(); - } catch (NoNetworkAccessException e) { - auth=false; - e.printStackTrace(); - } catch (NoAccessToServer e) { - auth = false; - e.printStackTrace(); - } - - //if we managed to authenticate we start - if(auth){ - - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - //int daysBeforeDueDate = sharedPreferences.getInt("notifications_days_before_expiration", 2); - //TODO - int daysBeforeDueDate = 2; - ArrayList circRecords = new ArrayList(); - - //get the circ records - try { - circRecords = accountAccess.getItemsCheckedOut(); - } catch (NoNetworkAccessException e) { - //not suppose to happen - } catch (NoAccessToServer e) { - //not suppose to happen - } catch (SessionNotFoundException e) { - //auth just earlier realized, not supose to happen - } - - DefaultDAO daoNotifications = DatabaseManager.getDAOInstance(this, NotificationAlert.class, NotificationAlert.tableName); - daoNotifications.open(); - - // Fetch all alarms from database - List alarms = daoNotifications.fetchAll(""); - - for(int i=0;i= 0) { - - // get a Calendar object with current time - Calendar cal = Calendar.getInstance(); - - cal.setTime(dueDate); - - //just for test - cal.add(Calendar.HOUR, 4); - cal.add(Calendar.MINUTE, 37); - - Log.d(TAG, "Set notification in " + cal.getTime()); - - NotificationAlert notifications = daoNotifications.fetch(checkoutRecord.circ_id); - NotificationAlert newNotificationInf = new NotificationAlert(checkoutRecord.circ_id, NotificationAlert.NOTIFICATION_INTENT - + checkoutRecord.circ_id, cal.getTime(), "Checkout " + checkoutRecord.getAuthor() + " expires on " + checkoutRecord.getDueDate()); - - if(notifications == null){ - daoNotifications.insert(newNotificationInf, false); - } - else{ - //update info in database - daoNotifications.update(newNotificationInf, checkoutRecord.circ_id); - } - - Intent intentNotification = new Intent(this, NotificationReceiver.class); - - Log.d(TAG, "Set due date alarm at" + cal.getTime() + " for " + newNotificationInf.id + " intent_val: "+ newNotificationInf.intent_val); - - intentNotification.putExtra("checkoutMessage", "The item " + checkoutRecord.getAuthor() + " is about to expire on " +checkoutRecord.getDueDate() ); - // update the current intent if it exists - PendingIntent sender = PendingIntent.getBroadcast(this, - NotificationAlert.NOTIFICATION_INTENT + checkoutRecord.circ_id, intentNotification, - PendingIntent.FLAG_UPDATE_CURRENT); - - // Get the AlarmManager service - AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); - am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); - } - } - daoNotifications.close(); - - - lastUpdateServiceDate = currentDate; - SharedPreferences.Editor editor = sharedPreferences.edit(); - editor.putLong("lastUpdateTime", lastUpdateServiceDate.getTime()); - editor.commit(); - - Log.d(TAG, "set last service update date " + lastUpdateServiceDate); - } - - } +public class ScheduledIntentService extends IntentService { + + public static Date lastUpdateServiceDate; + + public static String TAG = "ScheduledIntentService"; + + public static String ACTION = "org.evergreen.updateservice"; + + // fire up once a day + public static int SCHEDULE_TIME_INTERVAL = 1; + + public ScheduledIntentService() { + super("EvergreenIntentService"); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + Log.d(TAG, "Start service"); + + return super.onStartCommand(intent, flags, startId); + } + + @Override + protected void onHandleIntent(Intent intent) { + + Date currentDate = new Date(System.currentTimeMillis()); + + Log.d(TAG, "Notifications service started"); + + /* + * Download the necessary IDL files for checkout items operations like + * au (for auth), circ, mvr and acp + */ + String idlFile = GlobalConfigs.IDL_FILE_FROM_ROOT + + "?class=circ&class=au&class=mvr&class=acp"; + try { + Log.d("debug", "Read fm"); + InputStream in_IDL = Utils + .getNetInputStream(GlobalConfigs.httpAddress + idlFile); + IDLParser parser = new IDLParser(in_IDL); + parser.parse(); + } catch (Exception e) { + System.err.println("Error in parsing IDL file " + idlFile + " " + + e.getMessage()); + } + ; + + // login with the user credentials + AccountAccess accountAccess = AccountAccess.getAccountAccess( + GlobalConfigs.httpAddress, + (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)); + boolean auth = true; + try { + accountAccess.authenticate(); + } catch (NoNetworkAccessException e) { + auth = false; + e.printStackTrace(); + } catch (NoAccessToServer e) { + auth = false; + e.printStackTrace(); + } + + // if we managed to authenticate we start + if (auth) { + + SharedPreferences sharedPreferences = PreferenceManager + .getDefaultSharedPreferences(getApplicationContext()); + // int daysBeforeDueDate = + // sharedPreferences.getInt("notifications_days_before_expiration", + // 2); + // TODO + int daysBeforeDueDate = 2; + ArrayList circRecords = new ArrayList(); + + // get the circ records + try { + circRecords = accountAccess.getItemsCheckedOut(); + } catch (NoNetworkAccessException e) { + // not suppose to happen + } catch (NoAccessToServer e) { + // not suppose to happen + } catch (SessionNotFoundException e) { + // auth just earlier realized, not supose to happen + } + + DefaultDAO daoNotifications = DatabaseManager + .getDAOInstance(this, NotificationAlert.class, + NotificationAlert.tableName); + daoNotifications.open(); + + // Fetch all alarms from database + List alarms = daoNotifications.fetchAll(""); + + for (int i = 0; i < alarms.size(); i++) { + System.out.println("notification " + alarms.get(i)); + Log.d(TAG, "Notification " + alarms.get(i)); + } + for (int i = 0; i < circRecords.size(); i++) { + + CircRecord checkoutRecord = circRecords.get(i); + + Date dueDate = checkoutRecord.getDueDateObject(); + + Calendar notificationDate = Calendar.getInstance(); + notificationDate.setTime(dueDate); + + notificationDate.add(Calendar.DAY_OF_MONTH, -daysBeforeDueDate); + Log.d(TAG, + " notification time start " + + notificationDate.getTime() + " current date " + + currentDate + " date between " + currentDate); + + // if due date in the future + if (currentDate.compareTo(notificationDate.getTime()) >= 0) { + + // get a Calendar object with current time + Calendar cal = Calendar.getInstance(); + + cal.setTime(dueDate); + + // just for test + cal.add(Calendar.HOUR, 4); + cal.add(Calendar.MINUTE, 37); + + Log.d(TAG, "Set notification in " + cal.getTime()); + + NotificationAlert notifications = daoNotifications + .fetch(checkoutRecord.circ_id); + NotificationAlert newNotificationInf = new NotificationAlert( + checkoutRecord.circ_id, + NotificationAlert.NOTIFICATION_INTENT + + checkoutRecord.circ_id, cal.getTime(), + "Checkout " + checkoutRecord.getAuthor() + + " expires on " + + checkoutRecord.getDueDate()); + + if (notifications == null) { + daoNotifications.insert(newNotificationInf, false); + } else { + // update info in database + daoNotifications.update(newNotificationInf, + checkoutRecord.circ_id); + } + + Intent intentNotification = new Intent(this, + NotificationReceiver.class); + + Log.d(TAG, "Set due date alarm at" + cal.getTime() + + " for " + newNotificationInf.id + " intent_val: " + + newNotificationInf.intent_val); + + intentNotification.putExtra("checkoutMessage", + "The item " + checkoutRecord.getAuthor() + + " is about to expire on " + + checkoutRecord.getDueDate()); + // update the current intent if it exists + PendingIntent sender = PendingIntent.getBroadcast(this, + NotificationAlert.NOTIFICATION_INTENT + + checkoutRecord.circ_id, + intentNotification, + PendingIntent.FLAG_UPDATE_CURRENT); + + // Get the AlarmManager service + AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); + am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), + sender); + } + } + daoNotifications.close(); + + lastUpdateServiceDate = currentDate; + SharedPreferences.Editor editor = sharedPreferences.edit(); + editor.putLong("lastUpdateTime", lastUpdateServiceDate.getTime()); + editor.commit(); + + Log.d(TAG, "set last service update date " + lastUpdateServiceDate); + } + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BaseSampleActivity.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BaseSampleActivity.java index bc8a9c3dc1..783ea3fee7 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BaseSampleActivity.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BaseSampleActivity.java @@ -1,7 +1,5 @@ - package org.evergreen.android.utils.ui; - import java.util.Random; import org.evergreen.android.R; @@ -28,23 +26,23 @@ public abstract class BaseSampleActivity extends FragmentActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.random: - final int page = RANDOM.nextInt(mAdapter.getCount()); - Toast.makeText(this, "Changing to page " + page, Toast.LENGTH_SHORT); - mPager.setCurrentItem(page); - return true; - - case R.id.add_page: - if (mAdapter.getCount() < 10) { - mIndicator.notifyDataSetChanged(); - } - return true; - - case R.id.remove_page: - if (mAdapter.getCount() > 1) { - mIndicator.notifyDataSetChanged(); - } - return true; + case R.id.random: + final int page = RANDOM.nextInt(mAdapter.getCount()); + Toast.makeText(this, "Changing to page " + page, Toast.LENGTH_SHORT); + mPager.setCurrentItem(page); + return true; + + case R.id.add_page: + if (mAdapter.getCount() < 10) { + mIndicator.notifyDataSetChanged(); + } + return true; + + case R.id.remove_page: + if (mAdapter.getCount() > 1) { + mIndicator.notifyDataSetChanged(); + } + return true; } return super.onOptionsItemSelected(item); } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BasicDetailsFragment.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BasicDetailsFragment.java index c1c5006e59..66a09682d9 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BasicDetailsFragment.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/BasicDetailsFragment.java @@ -41,314 +41,342 @@ import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; -public class BasicDetailsFragment extends Fragment{ - - - private RecordInfo record; - private Integer position; - private Integer total; - - private TextView record_header; - - private TextView titleTextView; - private TextView authorTextView; - private TextView publisherTextView; - - private TextView seriesTextView; - private TextView subjectTextView; - private TextView synopsisTextView; - private TextView isbnTextView; - - private TextView copyCountTestView; - - private Button placeHoldButton; - - private Button addToBookbagButton; - - private LinearLayout showMore; - - private SearchCatalog search = null; - - private GlobalConfigs gl; - - private ProgressDialog progressDialog; - - private Integer bookbag_selected; - - private Dialog dialog; - - private ArrayList bookBags; - - private final ImageDownloader imageDownloader = new ImageDownloader(); - - private ImageView recordImage; - //max display info - private int list_size = 3; - - public static BasicDetailsFragment newInstance(RecordInfo record, Integer position, Integer total) { - BasicDetailsFragment fragment = new BasicDetailsFragment(record,position,total); - - return fragment; - } - - public BasicDetailsFragment(RecordInfo record, Integer position, Integer total){ - - this.record = record; - this.position = position; - this.total = total; - - search = SearchCatalog.getInstance(); - } - - public BasicDetailsFragment(){ - - search = SearchCatalog.getInstance(); - } - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if(savedInstanceState != null){ - record = (RecordInfo) savedInstanceState.getSerializable("recordInfo"); - this.position = savedInstanceState.getInt("position"); - this.total = savedInstanceState.getInt("total"); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - - - gl = GlobalConfigs.getGlobalConfigs(getActivity()); - - LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.record_details_basic_fragment,null); - - - record_header = (TextView) layout.findViewById(R.id.record_header_text); - copyCountTestView = (TextView) layout.findViewById(R.id.record_details_simple_copy_count); - showMore = (LinearLayout) layout.findViewById(R.id.record_details_show_more); - titleTextView = (TextView) layout.findViewById(R.id.record_details_simple_title); - authorTextView = (TextView) layout.findViewById(R.id.record_details_simple_author); - publisherTextView = (TextView) layout.findViewById(R.id.record_details_simple_publisher); - - seriesTextView = (TextView) layout.findViewById(R.id.record_details_simple_series); - subjectTextView = (TextView) layout.findViewById(R.id.record_details_simple_subject); - synopsisTextView = (TextView) layout.findViewById(R.id.record_details_simple_synopsis); - isbnTextView = (TextView) layout.findViewById(R.id.record_details_simple_isbn); - - recordImage = (ImageView) layout.findViewById(R.id.record_details_simple_image); - - placeHoldButton = (Button) layout.findViewById(R.id.simple_place_hold_button); - addToBookbagButton = (Button) layout.findViewById(R.id.simple_add_to_bookbag_button); - - placeHoldButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - Intent intent = new Intent(getActivity().getApplicationContext(),PlaceHold.class); - intent.putExtra("recordInfo",record); - startActivity(intent); - } - }); - - String imageHref = GlobalConfigs.httpAddress + "/opac/extras/ac/jacket/large/"+record.isbn; - - //start async download of image - imageDownloader.download(imageHref, recordImage); - - - AccountAccess ac = AccountAccess.getAccountAccess(); - - bookBags = ac.bookBags; - String array_spinner[] = new String[bookBags.size()]; - - for(int i=0;i arg0, View arg1, - int position, long arg3) { - bookbag_selected = position; - } - - @Override - public void onNothingSelected(AdapterView arg0) { - } - - }); - - - addToBookbagButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - - if(bookBags.size() > 0) - dialog.show(); - else - Toast.makeText(getActivity(), "No bookbags", Toast.LENGTH_SHORT).show(); - } - - }); - } - }); - - record_header.setText("Record " + position + "of " + total ); - - titleTextView.setText(record.title); - authorTextView.setText(record.author); - publisherTextView.setText(record.pubdate + " " + record.publisher); - - seriesTextView.setText(record.series); - subjectTextView.setText(record.subject); - synopsisTextView.setText(record.synopsis); - - isbnTextView.setText(record.isbn); - - - int current_org = 0; - if(search != null) - current_org = search.selectedOrganization.id; - - System.out.println("Size " + record.copyCountListInfo.size()); - - for(int i=0;i record.copyInformationList.size()) - list_size = record.copyInformationList.size(); - - // insert into main view - LinearLayout insertPoint = (LinearLayout) layout.findViewById(R.id.record_details_copy_information); - addCopyInfo(0, list_size, inflater, insertPoint); - - - - return layout; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - outState.putSerializable("recordInfo", record); - outState.putInt("position", this.position); - outState.putInt("total", this.total); - super.onSaveInstanceState(outState); - } - - - public void addCopyInfo(int start, int stop, LayoutInflater inflater, LinearLayout insertPoint){ - - for(int i=start;i> set = info.statusInformation.entrySet(); - - Iterator> it = set.iterator(); - - while(it.hasNext()){ - - Entry ent = it.next(); - TextView statusName = new TextView(getActivity()); - statusName.setText(ent.getKey() + " : " + ent.getValue()); - - copy_statuses.addView(statusName, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); - - } - - } - - } +public class BasicDetailsFragment extends Fragment { + + private RecordInfo record; + private Integer position; + private Integer total; + + private TextView record_header; + + private TextView titleTextView; + private TextView authorTextView; + private TextView publisherTextView; + + private TextView seriesTextView; + private TextView subjectTextView; + private TextView synopsisTextView; + private TextView isbnTextView; + + private TextView copyCountTestView; + + private Button placeHoldButton; + + private Button addToBookbagButton; + + private LinearLayout showMore; + + private SearchCatalog search = null; + + private GlobalConfigs gl; + + private ProgressDialog progressDialog; + + private Integer bookbag_selected; + + private Dialog dialog; + + private ArrayList bookBags; + + private final ImageDownloader imageDownloader = new ImageDownloader(); + + private ImageView recordImage; + // max display info + private int list_size = 3; + + public static BasicDetailsFragment newInstance(RecordInfo record, + Integer position, Integer total) { + BasicDetailsFragment fragment = new BasicDetailsFragment(record, + position, total); + + return fragment; + } + + public BasicDetailsFragment(RecordInfo record, Integer position, + Integer total) { + + this.record = record; + this.position = position; + this.total = total; + + search = SearchCatalog.getInstance(); + } + + public BasicDetailsFragment() { + + search = SearchCatalog.getInstance(); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (savedInstanceState != null) { + record = (RecordInfo) savedInstanceState + .getSerializable("recordInfo"); + this.position = savedInstanceState.getInt("position"); + this.total = savedInstanceState.getInt("total"); + } + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + + gl = GlobalConfigs.getGlobalConfigs(getActivity()); + + LinearLayout layout = (LinearLayout) inflater.inflate( + R.layout.record_details_basic_fragment, null); + + record_header = (TextView) layout.findViewById(R.id.record_header_text); + copyCountTestView = (TextView) layout + .findViewById(R.id.record_details_simple_copy_count); + showMore = (LinearLayout) layout + .findViewById(R.id.record_details_show_more); + titleTextView = (TextView) layout + .findViewById(R.id.record_details_simple_title); + authorTextView = (TextView) layout + .findViewById(R.id.record_details_simple_author); + publisherTextView = (TextView) layout + .findViewById(R.id.record_details_simple_publisher); + + seriesTextView = (TextView) layout + .findViewById(R.id.record_details_simple_series); + subjectTextView = (TextView) layout + .findViewById(R.id.record_details_simple_subject); + synopsisTextView = (TextView) layout + .findViewById(R.id.record_details_simple_synopsis); + isbnTextView = (TextView) layout + .findViewById(R.id.record_details_simple_isbn); + + recordImage = (ImageView) layout + .findViewById(R.id.record_details_simple_image); + + placeHoldButton = (Button) layout + .findViewById(R.id.simple_place_hold_button); + addToBookbagButton = (Button) layout + .findViewById(R.id.simple_add_to_bookbag_button); + + placeHoldButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Intent intent = new Intent(getActivity() + .getApplicationContext(), PlaceHold.class); + intent.putExtra("recordInfo", record); + startActivity(intent); + } + }); + + String imageHref = GlobalConfigs.httpAddress + + "/opac/extras/ac/jacket/large/" + record.isbn; + + // start async download of image + imageDownloader.download(imageHref, recordImage); + + AccountAccess ac = AccountAccess.getAccountAccess(); + + bookBags = ac.bookBags; + String array_spinner[] = new String[bookBags.size()]; + + for (int i = 0; i < array_spinner.length; i++) + array_spinner[i] = bookBags.get(i).name; + + dialog = new Dialog(getActivity()); + dialog.setContentView(R.layout.bookbag_spinner); + dialog.setTitle("Choose bookbag"); + Spinner s = (Spinner) dialog.findViewById(R.id.bookbag_spinner); + + Button add = (Button) dialog.findViewById(R.id.add_to_bookbag_button); + ArrayAdapter adapter = new ArrayAdapter(getActivity() + .getApplicationContext(), android.R.layout.simple_spinner_item, + array_spinner); + s.setAdapter(adapter); + + add.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // TODO Auto-generated method stub + Thread addtoBookbag = new Thread(new Runnable() { + @Override + public void run() { + AccountAccess ac = AccountAccess.getAccountAccess(); + try { + ac.addRecordToBookBag(record.doc_id, + ac.bookBags.get(bookbag_selected).id); + } catch (SessionNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + dialog.dismiss(); + } + }); + + } + }); + progressDialog = ProgressDialog.show(getActivity(), + "Please wait", "Add to bookbag"); + addtoBookbag.start(); + + } + }); + s.setOnItemSelectedListener(new OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView arg0, View arg1, + int position, long arg3) { + bookbag_selected = position; + } + + @Override + public void onNothingSelected(AdapterView arg0) { + } + + }); + + addToBookbagButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + + if (bookBags.size() > 0) + dialog.show(); + else + Toast.makeText(getActivity(), "No bookbags", + Toast.LENGTH_SHORT).show(); + } + + }); + } + }); + + record_header.setText("Record " + position + "of " + total); + + titleTextView.setText(record.title); + authorTextView.setText(record.author); + publisherTextView.setText(record.pubdate + " " + record.publisher); + + seriesTextView.setText(record.series); + subjectTextView.setText(record.subject); + synopsisTextView.setText(record.synopsis); + + isbnTextView.setText(record.isbn); + + int current_org = 0; + if (search != null) + current_org = search.selectedOrganization.id; + + System.out.println("Size " + record.copyCountListInfo.size()); + + for (int i = 0; i < record.copyCountListInfo.size(); i++) { + System.out.println(current_org + " " + + record.copyCountListInfo.get(i).org_id + " " + + record.copyCountListInfo.get(i).count); + if (record.copyCountListInfo.get(i).org_id == current_org) { + int total = record.copyCountListInfo.get(i).count; + int available = record.copyCountListInfo.get(i).available; + copyCountTestView.setText(available + " / " + total); + break; + } + } + + final LayoutInflater inf = inflater; + final LinearLayout lay = layout; + + // add more details + showMore.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // show more details + Intent intent = new Intent(getActivity() + .getApplicationContext(), MoreCopyInformation.class); + intent.putExtra("recordInfo", record); + startActivity(intent); + } + }); + + if (list_size > record.copyInformationList.size()) + list_size = record.copyInformationList.size(); + + // insert into main view + LinearLayout insertPoint = (LinearLayout) layout + .findViewById(R.id.record_details_copy_information); + addCopyInfo(0, list_size, inflater, insertPoint); + + return layout; + } + + @Override + public void onSaveInstanceState(Bundle outState) { + outState.putSerializable("recordInfo", record); + outState.putInt("position", this.position); + outState.putInt("total", this.total); + super.onSaveInstanceState(outState); + } + + public void addCopyInfo(int start, int stop, LayoutInflater inflater, + LinearLayout insertPoint) { + + for (int i = start; i < stop; i++) { + + View copy_info_view = inflater.inflate(R.layout.copy_information, + null); + + // fill in any details dynamically here + TextView library = (TextView) copy_info_view + .findViewById(R.id.copy_information_library); + TextView call_number = (TextView) copy_info_view + .findViewById(R.id.copy_information_call_number); + TextView copy_location = (TextView) copy_info_view + .findViewById(R.id.copy_information_copy_location); + + library.setText(gl.getOrganizationName(record.copyInformationList + .get(i).org_id) + " "); + call_number + .setText(record.copyInformationList.get(i).call_number_sufix); + copy_location + .setText(record.copyInformationList.get(i).copy_location); + + // insert into main view + insertPoint.addView(copy_info_view, new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT)); + + LinearLayout copy_statuses = (LinearLayout) copy_info_view + .findViewById(R.id.copy_information_statuses); + + CopyInformation info = record.copyInformationList.get(i); + + Set> set = info.statusInformation.entrySet(); + + Iterator> it = set.iterator(); + + while (it.hasNext()) { + + Entry ent = it.next(); + TextView statusName = new TextView(getActivity()); + statusName.setText(ent.getKey() + " : " + ent.getValue()); + + copy_statuses.addView(statusName, new LayoutParams( + LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + + } + + } + + } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/Dashboard.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/Dashboard.java index 126e827fc3..1380746e86 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/Dashboard.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/Dashboard.java @@ -6,8 +6,8 @@ import android.view.View; import android.view.ViewGroup; /** - * Custom layout that arranges children in a grid-like manner, optimizing for even horizontal and - * vertical whitespace. + * Custom layout that arranges children in a grid-like manner, optimizing for + * even horizontal and vertical whitespace. */ public class Dashboard extends ViewGroup { @@ -50,15 +50,16 @@ public class Dashboard extends ViewGroup { child.measure(childWidthMeasureSpec, childHeightMeasureSpec); mMaxChildWidth = Math.max(mMaxChildWidth, child.getMeasuredWidth()); - mMaxChildHeight = Math.max(mMaxChildHeight, child.getMeasuredHeight()); + mMaxChildHeight = Math.max(mMaxChildHeight, + child.getMeasuredHeight()); } // Measure again for each child to be exactly the same size. - childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( - mMaxChildWidth, MeasureSpec.EXACTLY); - childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( - mMaxChildHeight, MeasureSpec.EXACTLY); + childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxChildWidth, + MeasureSpec.EXACTLY); + childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxChildHeight, + MeasureSpec.EXACTLY); for (int i = 0; i < count; i++) { final View child = getChildAt(i); @@ -69,8 +70,7 @@ public class Dashboard extends ViewGroup { child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } - setMeasuredDimension( - resolveSize(mMaxChildWidth, widthMeasureSpec), + setMeasuredDimension(resolveSize(mMaxChildWidth, widthMeasureSpec), resolveSize(mMaxChildHeight, heightMeasureSpec)); } @@ -95,8 +95,10 @@ public class Dashboard extends ViewGroup { return; } - // Calculate what number of rows and columns will optimize for even horizontal and - // vertical whitespace between items. Start with a 1 x N grid, then try 2 x N, and so on. + // Calculate what number of rows and columns will optimize for even + // horizontal and + // vertical whitespace between items. Start with a 1 x N grid, then try + // 2 x N, and so on. int bestSpaceDifference = Integer.MAX_VALUE; int spaceDifference; @@ -122,13 +124,15 @@ public class Dashboard extends ViewGroup { // Found a better whitespace squareness/ratio bestSpaceDifference = spaceDifference; - // If we found a better whitespace squareness and there's only 1 row, this is + // If we found a better whitespace squareness and there's only 1 + // row, this is // the best we can do. if (rows == 1) { break; } } else { - // This is a worse whitespace ratio, use the previous value of cols and exit. + // This is a worse whitespace ratio, use the previous value of + // cols and exit. --cols; rows = (visibleCount - 1) / cols + 1; hSpace = ((width - mMaxChildWidth * cols) / (cols + 1)); @@ -139,9 +143,11 @@ public class Dashboard extends ViewGroup { ++cols; } - // Lay out children based on calculated best-fit number of rows and cols. + // Lay out children based on calculated best-fit number of rows and + // cols. - // If we chose a layout that has negative horizontal or vertical space, force it to zero. + // If we chose a layout that has negative horizontal or vertical space, + // force it to zero. hSpace = Math.max(0, hSpace); vSpace = Math.max(0, vSpace); @@ -164,11 +170,10 @@ public class Dashboard extends ViewGroup { left = hSpace * (col + 1) + width * col; top = vSpace * (row + 1) + height * row; - child.layout(left, top, - (hSpace == 0 && col == cols - 1) ? r : (left + width), - (vSpace == 0 && row == rows - 1) ? b : (top + height)); + child.layout(left, top, (hSpace == 0 && col == cols - 1) ? r + : (left + width), (vSpace == 0 && row == rows - 1) ? b + : (top + height)); ++visibleIndex; } } } - diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/PageIndicator.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/PageIndicator.java index 2622564f94..57046bda4d 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/PageIndicator.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/PageIndicator.java @@ -17,7 +17,6 @@ package org.evergreen.android.utils.ui; - import android.support.v4.view.ViewPager; /** @@ -27,32 +26,36 @@ import android.support.v4.view.ViewPager; public interface PageIndicator extends ViewPager.OnPageChangeListener { /** * Bind the indicator to a ViewPager. - * + * * @param view */ void setViewPager(ViewPager view); /** * Bind the indicator to a ViewPager. - * + * * @param view * @param initialPosition */ void setViewPager(ViewPager view, int initialPosition); /** - *

Set the current page of both the ViewPager and indicator.

- * - *

This must be used if you need to set the page before - * the views are drawn on screen (e.g., default start page).

- * + *

+ * Set the current page of both the ViewPager and indicator. + *

+ * + *

+ * This must be used if you need to set the page before the + * views are drawn on screen (e.g., default start page). + *

+ * * @param item */ void setCurrentItem(int item); /** * Set a page change listener which will receive forwarded events. - * + * * @param listener */ void setOnPageChangeListener(ViewPager.OnPageChangeListener listener); diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/RealViewSwitcher.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/RealViewSwitcher.java deleted file mode 100644 index 16f5e52016..0000000000 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/RealViewSwitcher.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2010 Marc Reichelt - * - * Work derived from Workspace.java of the Launcher application - * see http://android.git.kernel.org/?p=platform/packages/apps/Launcher.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.evergreen.android.utils.ui; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.view.VelocityTracker; -import android.view.View; -import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.widget.Scroller; - -/** - * RealViewSwitcher allows users to switch between multiple screens (layouts) in the same way as the Android home screen (Launcher application). - *

- * You can add and remove views using the normal methods {@link ViewGroup#addView(View)}, {@link ViewGroup#removeView(View)} etc. You may want to listen for updates by calling {@link RealViewSwitcher#setOnScreenSwitchListener(OnScreenSwitchListener)} - * in order to perform operations once a new screen has been selected. - * - * @author Marc Reichelt, http://www.marcreichelt.de/ - * @version 0.1.0 - */ -public class RealViewSwitcher extends ViewGroup { - - // TODO: This class does the basic stuff right now, but it would be cool to have certain things implemented, - // e.g. using an adapter for getting views instead of setting them directly, memory management and the - // possibility of scrolling vertically instead of horizontally. If you have ideas or patches, please visit - // my website and drop me a mail. :-) - - /** - * Listener for the event that the RealViewSwitcher switches to a new view. - */ - public static interface OnScreenSwitchListener { - - /** - * Notifies listeners about the new screen. Runs after the animation completed. - * - * @param screen The new screen index. - */ - void onScreenSwitched(int screen); - - } - - private static final int SNAP_VELOCITY = 1000; - private static final int INVALID_SCREEN = -1; - - private Scroller mScroller; - private VelocityTracker mVelocityTracker; - - private final static int TOUCH_STATE_REST = 0; - private final static int TOUCH_STATE_SCROLLING = 1; - - private int mTouchState = TOUCH_STATE_REST; - - private float mLastMotionX; - private int mTouchSlop; - private int mMaximumVelocity; - private int mCurrentScreen; - private int mNextScreen = INVALID_SCREEN; - - private boolean mFirstLayout = true; - - private OnScreenSwitchListener mOnScreenSwitchListener; - - public RealViewSwitcher(Context context) { - super(context); - init(); - } - - public RealViewSwitcher(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - private void init() { - mScroller = new Scroller(getContext()); - - final ViewConfiguration configuration = ViewConfiguration.get(getContext()); - mTouchSlop = configuration.getScaledTouchSlop(); - mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - final int width = MeasureSpec.getSize(widthMeasureSpec); - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - if (widthMode != MeasureSpec.EXACTLY) { - throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode."); - } - - final int heightMode = MeasureSpec.getMode(heightMeasureSpec); - if (heightMode != MeasureSpec.EXACTLY) { - throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode."); - } - - // The children are given the same width and height as the workspace - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); - } - - if (mFirstLayout) { - scrollTo(mCurrentScreen * width, 0); - mFirstLayout = false; - } - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - int childLeft = 0; - - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - if (child.getVisibility() != View.GONE) { - final int childWidth = child.getMeasuredWidth(); - child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight()); - childLeft += childWidth; - } - } - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - if (mVelocityTracker == null) { - mVelocityTracker = VelocityTracker.obtain(); - } - mVelocityTracker.addMovement(ev); - - final int action = ev.getAction(); - final float x = ev.getX(); - - switch (action) { - case MotionEvent.ACTION_DOWN: - /* - * If being flinged and user touches, stop the fling. isFinished will be false if being flinged. - */ - if (!mScroller.isFinished()) { - mScroller.abortAnimation(); - } - - // Remember where the motion event started - mLastMotionX = x; - - mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; - - break; - - case MotionEvent.ACTION_MOVE: - final int xDiff = (int) Math.abs(x - mLastMotionX); - - boolean xMoved = xDiff > mTouchSlop; - - if (xMoved) { - // Scroll if the user moved far enough along the X axis - mTouchState = TOUCH_STATE_SCROLLING; - } - - if (mTouchState == TOUCH_STATE_SCROLLING) { - // Scroll to follow the motion event - final int deltaX = (int) (mLastMotionX - x); - mLastMotionX = x; - - final int scrollX = getScrollX(); - if (deltaX < 0) { - if (scrollX > 0) { - scrollBy(Math.max(-scrollX, deltaX), 0); - } - } else if (deltaX > 0) { - final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - scrollX - getWidth(); - if (availableToScroll > 0) { - scrollBy(Math.min(availableToScroll, deltaX), 0); - } - } - } - break; - - case MotionEvent.ACTION_UP: - if (mTouchState == TOUCH_STATE_SCROLLING) { - final VelocityTracker velocityTracker = mVelocityTracker; - velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); - int velocityX = (int) velocityTracker.getXVelocity(); - - if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { - // Fling hard enough to move left - snapToScreen(mCurrentScreen - 1); - } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { - // Fling hard enough to move right - snapToScreen(mCurrentScreen + 1); - } else { - snapToDestination(); - } - - if (mVelocityTracker != null) { - mVelocityTracker.recycle(); - mVelocityTracker = null; - } - } - - mTouchState = TOUCH_STATE_REST; - - break; - case MotionEvent.ACTION_CANCEL: - mTouchState = TOUCH_STATE_REST; - } - - return true; - } - - private void snapToDestination() { - final int screenWidth = getWidth(); - final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth; - - snapToScreen(whichScreen); - } - - private void snapToScreen(int whichScreen) { - if (!mScroller.isFinished()) - return; - - whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1)); - - mNextScreen = whichScreen; - - final int newX = whichScreen * getWidth(); - final int delta = newX - getScrollX(); - mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2); - invalidate(); - } - - @Override - public void computeScroll() { - if (mScroller.computeScrollOffset()) { - scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); - postInvalidate(); - } else if (mNextScreen != INVALID_SCREEN) { - mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1)); - - // notify observer about screen change - if (mOnScreenSwitchListener != null) - mOnScreenSwitchListener.onScreenSwitched(mCurrentScreen); - - mNextScreen = INVALID_SCREEN; - } - } - - /** - * Returns the index of the currently displayed screen. - * - * @return The index of the currently displayed screen. - */ - public int getCurrentScreen() { - return mCurrentScreen; - } - - /** - * Sets the current screen. - * - * @param currentScreen The new screen. - */ - public void setCurrentScreen(int currentScreen) { - mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1)); - scrollTo(mCurrentScreen * getWidth(), 0); - invalidate(); - } - - /** - * Sets the {@link ViewSwitcher.OnScreenSwitchListener}. - * - * @param onScreenSwitchListener The listener for switch events. - */ - public void setOnScreenSwitchListener(OnScreenSwitchListener onScreenSwitchListener) { - mOnScreenSwitchListener = onScreenSwitchListener; - } - -} diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TabPageIndicator.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TabPageIndicator.java index a6dcc18048..69ac053885 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TabPageIndicator.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TabPageIndicator.java @@ -37,7 +37,8 @@ import android.widget.TextView; * This widget implements the dynamic action bar tab behavior that can change * across different configurations or circumstances. */ -public class TabPageIndicator extends HorizontalScrollView implements PageIndicator { +public class TabPageIndicator extends HorizontalScrollView implements + PageIndicator { /** Title text used when no title is provided by the adapter. */ private static final CharSequence EMPTY_TITLE = ""; @@ -47,8 +48,9 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica public interface OnTabReselectedListener { /** * Callback when the selected tab has been reselected. - * - * @param position Position of the current center item. + * + * @param position + * Position of the current center item. */ void onTabReselected(int position); } @@ -57,7 +59,7 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica private final OnClickListener mTabClickListener = new OnClickListener() { public void onClick(View view) { - TabView tabView = (TabView)view; + TabView tabView = (TabView) view; final int oldSelected = mViewPager.getCurrentItem(); final int newSelected = tabView.getIndex(); mViewPager.setCurrentItem(newSelected); @@ -85,7 +87,8 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica setHorizontalScrollBarEnabled(false); mTabLayout = new LinearLayout(getContext()); - addView(mTabLayout, new ViewGroup.LayoutParams(WRAP_CONTENT, FILL_PARENT)); + addView(mTabLayout, new ViewGroup.LayoutParams(WRAP_CONTENT, + FILL_PARENT)); } public void setOnTabReselectedListener(OnTabReselectedListener listener) { @@ -99,9 +102,10 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica setFillViewport(lockedExpanded); final int childCount = mTabLayout.getChildCount(); - if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { + if (childCount > 1 + && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { if (childCount > 2) { - mMaxTabWidth = (int)(MeasureSpec.getSize(widthMeasureSpec) * 0.4f); + mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f); } else { mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2; } @@ -126,7 +130,8 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica } mTabSelector = new Runnable() { public void run() { - final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2; + final int scrollPos = tabView.getLeft() + - (getWidth() - tabView.getWidth()) / 2; smoothScrollTo(scrollPos, 0); mTabSelector = null; } @@ -158,7 +163,8 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica tabView.setOnClickListener(mTabClickListener); tabView.setText(text); - mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0, FILL_PARENT, 1)); + mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0, + FILL_PARENT, 1)); } @Override @@ -193,7 +199,8 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica } final PagerAdapter adapter = view.getAdapter(); if (adapter == null) { - throw new IllegalStateException("ViewPager does not have adapter instance."); + throw new IllegalStateException( + "ViewPager does not have adapter instance."); } mViewPager = view; view.setOnPageChangeListener(this); @@ -261,8 +268,8 @@ public class TabPageIndicator extends HorizontalScrollView implements PageIndica // Re-measure if we went beyond our maximum size. if (mMaxTabWidth > 0 && getMeasuredWidth() > mMaxTabWidth) { - super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxTabWidth, MeasureSpec.EXACTLY), - heightMeasureSpec); + super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxTabWidth, + MeasureSpec.EXACTLY), heightMeasureSpec); } } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragment.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragment.java index f5d4f0a6a9..c4fee91840 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragment.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragment.java @@ -32,13 +32,15 @@ public final class TestFragment extends Fragment { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) { + if ((savedInstanceState != null) + && savedInstanceState.containsKey(KEY_CONTENT)) { mContent = savedInstanceState.getString(KEY_CONTENT); } } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { TextView text = new TextView(getActivity()); text.setGravity(Gravity.CENTER); text.setText(mContent); @@ -46,7 +48,8 @@ public final class TestFragment extends Fragment { text.setPadding(20, 20, 20, 20); LinearLayout layout = new LinearLayout(getActivity()); - layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); + layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, + LayoutParams.FILL_PARENT)); layout.setGravity(Gravity.CENTER); layout.addView(text); diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragmentAdapter.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragmentAdapter.java index ea62a40eb3..51ec29d20c 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragmentAdapter.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TestFragmentAdapter.java @@ -5,7 +5,8 @@ import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class TestFragmentAdapter extends FragmentPagerAdapter { - protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", }; + protected static final String[] CONTENT = new String[] { "This", "Is", "A", + "Test", }; private int mCount = CONTENT.length; diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TitlePageIndicator.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TitlePageIndicator.java index 5a0f7f69ab..a8b5fb86d5 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TitlePageIndicator.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/TitlePageIndicator.java @@ -43,8 +43,8 @@ import android.view.ViewConfiguration; /** * A TitlePageIndicator is a PageIndicator which displays the title of left view * (if exist), the title of the current select view (centered) and the title of - * the right view (if exist). When the user scrolls the ViewPager then titles are - * also scrolled. + * the right view (if exist). When the user scrolls the ViewPager then titles + * are also scrolled. */ public class TitlePageIndicator extends View implements PageIndicator { /** @@ -56,8 +56,8 @@ public class TitlePageIndicator extends View implements PageIndicator { /** * Percentage indicating what percentage of the screen width away from - * center should the selected text bold turn off. A value of 0.05 means - * that 10% between the center and an edge. + * center should the selected text bold turn off. A value of 0.05 means that + * 10% between the center and an edge. */ private static final float BOLD_FADE_PERCENTAGE = 0.05f; @@ -72,8 +72,9 @@ public class TitlePageIndicator extends View implements PageIndicator { public interface OnCenterItemClickListener { /** * Callback when the center item has been clicked. - * - * @param position Position of the current center item. + * + * @param position + * Position of the current center item. */ void onCenterItemClick(int position); } @@ -130,7 +131,6 @@ public class TitlePageIndicator extends View implements PageIndicator { private OnCenterItemClickListener mCenterItemClickListener; - public TitlePageIndicator(Context context) { this(context, null); } @@ -141,42 +141,79 @@ public class TitlePageIndicator extends View implements PageIndicator { public TitlePageIndicator(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - if (isInEditMode()) return; + if (isInEditMode()) + return; - //Load defaults from resources + // Load defaults from resources final Resources res = getResources(); - final int defaultFooterColor = res.getColor(R.color.default_title_indicator_footer_color); - final float defaultFooterLineHeight = res.getDimension(R.dimen.default_title_indicator_footer_line_height); - final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style); - final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height); - final float defaultFooterIndicatorUnderlinePadding = res.getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding); - final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding); - final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color); - final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold); - final int defaultTextColor = res.getColor(R.color.default_title_indicator_text_color); - final float defaultTextSize = res.getDimension(R.dimen.default_title_indicator_text_size); - final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding); - final float defaultClipPadding = res.getDimension(R.dimen.default_title_indicator_clip_padding); - final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding); - - //Retrieve styles attributes - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, 0); - - //Retrieve the colors to be used for this view and apply them. - mFooterLineHeight = a.getDimension(R.styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight); - mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle)); - mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight); - mFooterIndicatorUnderlinePadding = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding); - mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding); - mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, defaultTopPadding); - mTitlePadding = a.getDimension(R.styleable.TitlePageIndicator_titlePadding, defaultTitlePadding); - mClipPadding = a.getDimension(R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding); - mColorSelected = a.getColor(R.styleable.TitlePageIndicator_selectedColor, defaultSelectedColor); - mColorText = a.getColor(R.styleable.TitlePageIndicator_android_textColor, defaultTextColor); - mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold); - - final float textSize = a.getDimension(R.styleable.TitlePageIndicator_android_textSize, defaultTextSize); - final int footerColor = a.getColor(R.styleable.TitlePageIndicator_footerColor, defaultFooterColor); + final int defaultFooterColor = res + .getColor(R.color.default_title_indicator_footer_color); + final float defaultFooterLineHeight = res + .getDimension(R.dimen.default_title_indicator_footer_line_height); + final int defaultFooterIndicatorStyle = res + .getInteger(R.integer.default_title_indicator_footer_indicator_style); + final float defaultFooterIndicatorHeight = res + .getDimension(R.dimen.default_title_indicator_footer_indicator_height); + final float defaultFooterIndicatorUnderlinePadding = res + .getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding); + final float defaultFooterPadding = res + .getDimension(R.dimen.default_title_indicator_footer_padding); + final int defaultSelectedColor = res + .getColor(R.color.default_title_indicator_selected_color); + final boolean defaultSelectedBold = res + .getBoolean(R.bool.default_title_indicator_selected_bold); + final int defaultTextColor = res + .getColor(R.color.default_title_indicator_text_color); + final float defaultTextSize = res + .getDimension(R.dimen.default_title_indicator_text_size); + final float defaultTitlePadding = res + .getDimension(R.dimen.default_title_indicator_title_padding); + final float defaultClipPadding = res + .getDimension(R.dimen.default_title_indicator_clip_padding); + final float defaultTopPadding = res + .getDimension(R.dimen.default_title_indicator_top_padding); + + // Retrieve styles attributes + TypedArray a = context.obtainStyledAttributes(attrs, + R.styleable.TitlePageIndicator, defStyle, 0); + + // Retrieve the colors to be used for this view and apply them. + mFooterLineHeight = a.getDimension( + R.styleable.TitlePageIndicator_footerLineHeight, + defaultFooterLineHeight); + mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger( + R.styleable.TitlePageIndicator_footerIndicatorStyle, + defaultFooterIndicatorStyle)); + mFooterIndicatorHeight = a.getDimension( + R.styleable.TitlePageIndicator_footerIndicatorHeight, + defaultFooterIndicatorHeight); + mFooterIndicatorUnderlinePadding = a.getDimension( + R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, + defaultFooterIndicatorUnderlinePadding); + mFooterPadding = a.getDimension( + R.styleable.TitlePageIndicator_footerPadding, + defaultFooterPadding); + mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, + defaultTopPadding); + mTitlePadding = a.getDimension( + R.styleable.TitlePageIndicator_titlePadding, + defaultTitlePadding); + mClipPadding = a.getDimension( + R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding); + mColorSelected = a.getColor( + R.styleable.TitlePageIndicator_selectedColor, + defaultSelectedColor); + mColorText = a.getColor( + R.styleable.TitlePageIndicator_android_textColor, + defaultTextColor); + mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, + defaultSelectedBold); + + final float textSize = a.getDimension( + R.styleable.TitlePageIndicator_android_textSize, + defaultTextSize); + final int footerColor = a.getColor( + R.styleable.TitlePageIndicator_footerColor, defaultFooterColor); mPaintText.setTextSize(textSize); mPaintText.setAntiAlias(true); mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE); @@ -188,10 +225,10 @@ public class TitlePageIndicator extends View implements PageIndicator { a.recycle(); final ViewConfiguration configuration = ViewConfiguration.get(context); - mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); + mTouchSlop = ViewConfigurationCompat + .getScaledPagingTouchSlop(configuration); } - public int getFooterColor() { return mPaintFooterLine.getColor(); } @@ -314,7 +351,7 @@ public class TitlePageIndicator extends View implements PageIndicator { /* * (non-Javadoc) - * + * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override @@ -329,14 +366,16 @@ public class TitlePageIndicator extends View implements PageIndicator { return; } - // mCurrentPage is -1 on first start and after orientation changed. If so, retrieve the correct index from viewpager. - if(mCurrentPage == -1 && mViewPager != null) mCurrentPage = mViewPager.getCurrentItem(); + // mCurrentPage is -1 on first start and after orientation changed. If + // so, retrieve the correct index from viewpager. + if (mCurrentPage == -1 && mViewPager != null) + mCurrentPage = mViewPager.getCurrentItem(); - //Calculate views bounds + // Calculate views bounds ArrayList bounds = calculateAllBounds(mPaintText); final int boundsSize = bounds.size(); - //Make sure we're on a page that still exists + // Make sure we're on a page that still exists if (mCurrentPage >= boundsSize) { setCurrentItem(boundsSize - 1); return; @@ -361,32 +400,33 @@ public class TitlePageIndicator extends View implements PageIndicator { } final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE); final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE); - final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE; + final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) + / SELECTION_FADE_PERCENTAGE; - //Verify if the current view must be clipped to the screen + // Verify if the current view must be clipped to the screen Rect curPageBound = bounds.get(mCurrentPage); float curPageWidth = curPageBound.right - curPageBound.left; if (curPageBound.left < leftClip) { - //Try to clip to the screen (left side) + // Try to clip to the screen (left side) clipViewOnTheLeft(curPageBound, curPageWidth, left); } if (curPageBound.right > rightClip) { - //Try to clip to the screen (right side) + // Try to clip to the screen (right side) clipViewOnTheRight(curPageBound, curPageWidth, right); } - //Left views starting from the current position + // Left views starting from the current position if (mCurrentPage > 0) { for (int i = mCurrentPage - 1; i >= 0; i--) { Rect bound = bounds.get(i); - //Is left side is outside the screen + // Is left side is outside the screen if (bound.left < leftClip) { int w = bound.right - bound.left; - //Try to clip to the screen (left side) + // Try to clip to the screen (left side) clipViewOnTheLeft(bound, w, left); - //Except if there's an intersection with the right view + // Except if there's an intersection with the right view Rect rightBound = bounds.get(i + 1); - //Intersection + // Intersection if (bound.right + mTitlePadding > rightBound.left) { bound.left = (int) (rightBound.left - w - mTitlePadding); bound.right = bound.left + w; @@ -394,18 +434,18 @@ public class TitlePageIndicator extends View implements PageIndicator { } } } - //Right views starting from the current position + // Right views starting from the current position if (mCurrentPage < countMinusOne) { - for (int i = mCurrentPage + 1 ; i < count; i++) { + for (int i = mCurrentPage + 1; i < count; i++) { Rect bound = bounds.get(i); - //If right side is outside the screen + // If right side is outside the screen if (bound.right > rightClip) { int w = bound.right - bound.left; - //Try to clip to the screen (right side) + // Try to clip to the screen (right side) clipViewOnTheRight(bound, w, right); - //Except if there's an intersection with the left view + // Except if there's an intersection with the left view Rect leftBound = bounds.get(i - 1); - //Intersection + // Intersection if (bound.left - mTitlePadding < leftBound.right) { bound.left = (int) (leftBound.right + mTitlePadding); bound.right = bound.left + w; @@ -414,37 +454,44 @@ public class TitlePageIndicator extends View implements PageIndicator { } } - //Now draw views + // Now draw views int colorTextAlpha = mColorText >>> 24; for (int i = 0; i < count; i++) { - //Get the title + // Get the title Rect bound = bounds.get(i); - //Only if one side is visible - if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) { + // Only if one side is visible + if ((bound.left > left && bound.left < right) + || (bound.right > left && bound.right < right)) { final boolean currentPage = (i == page); final CharSequence pageTitle = getTitle(i); - //Only set bold if we are within bounds - mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText); + // Only set bold if we are within bounds + mPaintText.setFakeBoldText(currentPage && currentBold + && mBoldText); - //Draw text as unselected + // Draw text as unselected mPaintText.setColor(mColorText); - if(currentPage && currentSelected) { - //Fade out/in unselected text as the selected text fades in/out - mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent)); + if (currentPage && currentSelected) { + // Fade out/in unselected text as the selected text fades + // in/out + mPaintText.setAlpha(colorTextAlpha + - (int) (colorTextAlpha * selectedPercent)); } - canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText); + canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, + bound.bottom + mTopPadding, mPaintText); - //If we are within the selected bounds draw the selected text + // If we are within the selected bounds draw the selected text if (currentPage && currentSelected) { mPaintText.setColor(mColorSelected); - mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent)); - canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText); + mPaintText + .setAlpha((int) ((mColorSelected >>> 24) * selectedPercent)); + canvas.drawText(pageTitle, 0, pageTitle.length(), + bound.left, bound.bottom + mTopPadding, mPaintText); } } } - //Draw the footer line + // Draw the footer line mPath.reset(); mPath.moveTo(0, height - mFooterLineHeight / 2f); mPath.lineTo(width, height - mFooterLineHeight / 2f); @@ -452,32 +499,43 @@ public class TitlePageIndicator extends View implements PageIndicator { canvas.drawPath(mPath, mPaintFooterLine); switch (mFooterIndicatorStyle) { - case Triangle: - mPath.reset(); - mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight); - mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight); - mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight); - mPath.close(); - canvas.drawPath(mPath, mPaintFooterIndicator); + case Triangle: + mPath.reset(); + mPath.moveTo(halfWidth, height - mFooterLineHeight + - mFooterIndicatorHeight); + mPath.lineTo(halfWidth + mFooterIndicatorHeight, height + - mFooterLineHeight); + mPath.lineTo(halfWidth - mFooterIndicatorHeight, height + - mFooterLineHeight); + mPath.close(); + canvas.drawPath(mPath, mPaintFooterIndicator); + break; + + case Underline: + if (!currentSelected || page >= boundsSize) { break; + } - case Underline: - if (!currentSelected || page >= boundsSize) { - break; - } - - Rect underlineBounds = bounds.get(page); - mPath.reset(); - mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); - mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); - mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); - mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); - mPath.close(); - - mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent)); - canvas.drawPath(mPath, mPaintFooterIndicator); - mPaintFooterIndicator.setAlpha(0xFF); - break; + Rect underlineBounds = bounds.get(page); + mPath.reset(); + mPath.moveTo(underlineBounds.left + - mFooterIndicatorUnderlinePadding, height + - mFooterLineHeight); + mPath.lineTo(underlineBounds.right + + mFooterIndicatorUnderlinePadding, height + - mFooterLineHeight); + mPath.lineTo(underlineBounds.right + + mFooterIndicatorUnderlinePadding, height + - mFooterLineHeight - mFooterIndicatorHeight); + mPath.lineTo(underlineBounds.left + - mFooterIndicatorUnderlinePadding, height + - mFooterLineHeight - mFooterIndicatorHeight); + mPath.close(); + + mPaintFooterIndicator.setAlpha((int) (0xFF * selectedPercent)); + canvas.drawPath(mPath, mPaintFooterIndicator); + mPaintFooterIndicator.setAlpha(0xFF); + break; } } @@ -492,83 +550,89 @@ public class TitlePageIndicator extends View implements PageIndicator { final int action = ev.getAction(); switch (action & MotionEventCompat.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - mActivePointerId = MotionEventCompat.getPointerId(ev, 0); - mLastMotionX = ev.getX(); - break; - - case MotionEvent.ACTION_MOVE: { - final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); - final float x = MotionEventCompat.getX(ev, activePointerIndex); - final float deltaX = x - mLastMotionX; - - if (!mIsDragging) { - if (Math.abs(deltaX) > mTouchSlop) { - mIsDragging = true; - } + case MotionEvent.ACTION_DOWN: + mActivePointerId = MotionEventCompat.getPointerId(ev, 0); + mLastMotionX = ev.getX(); + break; + + case MotionEvent.ACTION_MOVE: { + final int activePointerIndex = MotionEventCompat.findPointerIndex( + ev, mActivePointerId); + final float x = MotionEventCompat.getX(ev, activePointerIndex); + final float deltaX = x - mLastMotionX; + + if (!mIsDragging) { + if (Math.abs(deltaX) > mTouchSlop) { + mIsDragging = true; } + } - if (mIsDragging) { - mLastMotionX = x; - if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { - mViewPager.fakeDragBy(deltaX); - } + if (mIsDragging) { + mLastMotionX = x; + if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { + mViewPager.fakeDragBy(deltaX); } - - break; } - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - if (!mIsDragging) { - final int count = mViewPager.getAdapter().getCount(); - final int width = getWidth(); - final float halfWidth = width / 2f; - final float sixthWidth = width / 6f; - final float leftThird = halfWidth - sixthWidth; - final float rightThird = halfWidth + sixthWidth; - final float eventX = ev.getX(); - - if (eventX < leftThird) { - if (mCurrentPage > 0) { - mViewPager.setCurrentItem(mCurrentPage - 1); - return true; - } - } else if (eventX > rightThird) { - if (mCurrentPage < count - 1) { - mViewPager.setCurrentItem(mCurrentPage + 1); - return true; - } - } else { - //Middle third - if (mCenterItemClickListener != null) { - mCenterItemClickListener.onCenterItemClick(mCurrentPage); - } + break; + } + + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + if (!mIsDragging) { + final int count = mViewPager.getAdapter().getCount(); + final int width = getWidth(); + final float halfWidth = width / 2f; + final float sixthWidth = width / 6f; + final float leftThird = halfWidth - sixthWidth; + final float rightThird = halfWidth + sixthWidth; + final float eventX = ev.getX(); + + if (eventX < leftThird) { + if (mCurrentPage > 0) { + mViewPager.setCurrentItem(mCurrentPage - 1); + return true; + } + } else if (eventX > rightThird) { + if (mCurrentPage < count - 1) { + mViewPager.setCurrentItem(mCurrentPage + 1); + return true; + } + } else { + // Middle third + if (mCenterItemClickListener != null) { + mCenterItemClickListener + .onCenterItemClick(mCurrentPage); } } + } - mIsDragging = false; - mActivePointerId = INVALID_POINTER; - if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag(); - break; + mIsDragging = false; + mActivePointerId = INVALID_POINTER; + if (mViewPager.isFakeDragging()) + mViewPager.endFakeDrag(); + break; + + case MotionEventCompat.ACTION_POINTER_DOWN: { + final int index = MotionEventCompat.getActionIndex(ev); + final float x = MotionEventCompat.getX(ev, index); + mLastMotionX = x; + mActivePointerId = MotionEventCompat.getPointerId(ev, index); + break; + } - case MotionEventCompat.ACTION_POINTER_DOWN: { - final int index = MotionEventCompat.getActionIndex(ev); - final float x = MotionEventCompat.getX(ev, index); - mLastMotionX = x; - mActivePointerId = MotionEventCompat.getPointerId(ev, index); - break; + case MotionEventCompat.ACTION_POINTER_UP: + final int pointerIndex = MotionEventCompat.getActionIndex(ev); + final int pointerId = MotionEventCompat.getPointerId(ev, + pointerIndex); + if (pointerId == mActivePointerId) { + final int newPointerIndex = pointerIndex == 0 ? 1 : 0; + mActivePointerId = MotionEventCompat.getPointerId(ev, + newPointerIndex); } - - case MotionEventCompat.ACTION_POINTER_UP: - final int pointerIndex = MotionEventCompat.getActionIndex(ev); - final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); - if (pointerId == mActivePointerId) { - final int newPointerIndex = pointerIndex == 0 ? 1 : 0; - mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); - } - mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); - break; + mLastMotionX = MotionEventCompat.getX(ev, + MotionEventCompat.findPointerIndex(ev, mActivePointerId)); + break; } return true; @@ -576,39 +640,41 @@ public class TitlePageIndicator extends View implements PageIndicator { /** * Set bounds for the right textView including clip padding. - * + * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ - private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, int right) { + private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, + int right) { curViewBound.right = (int) (right - mClipPadding); curViewBound.left = (int) (curViewBound.right - curViewWidth); } /** * Set bounds for the left textView including clip padding. - * + * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ - private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, int left) { + private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, + int left) { curViewBound.left = (int) (left + mClipPadding); curViewBound.right = (int) (mClipPadding + curViewWidth); } /** * Calculate views bounds and scroll them according to the current index - * + * * @param paint * @return */ private ArrayList calculateAllBounds(Paint paint) { ArrayList list = new ArrayList(); - //For each views (If no values then add a fake one) + // For each views (If no values then add a fake one) final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final int halfWidth = width / 2; @@ -616,7 +682,7 @@ public class TitlePageIndicator extends View implements PageIndicator { Rect bounds = calcBounds(i, paint); int w = bounds.right - bounds.left; int h = bounds.bottom - bounds.top; - bounds.left = (int)(halfWidth - (w / 2f) + ((i - mCurrentPage - mPageOffset) * width)); + bounds.left = (int) (halfWidth - (w / 2f) + ((i - mCurrentPage - mPageOffset) * width)); bounds.right = bounds.left + w; bounds.top = 0; bounds.bottom = h; @@ -628,13 +694,13 @@ public class TitlePageIndicator extends View implements PageIndicator { /** * Calculate the bounds for a view's title - * + * * @param index * @param paint * @return */ private Rect calcBounds(int index, Paint paint) { - //Calculate the text bounds + // Calculate the text bounds Rect bounds = new Rect(); CharSequence title = getTitle(index); bounds.right = (int) paint.measureText(title, 0, title.length()); @@ -652,7 +718,8 @@ public class TitlePageIndicator extends View implements PageIndicator { } mPagerAdapter = view.getAdapter(); if (mPagerAdapter == null) { - throw new IllegalStateException("ViewPager does not have adapter instance."); + throw new IllegalStateException( + "ViewPager does not have adapter instance."); } mViewPager = view; mViewPager.setOnPageChangeListener(this); @@ -672,8 +739,9 @@ public class TitlePageIndicator extends View implements PageIndicator { /** * Set a callback listener for the center item click. - * - * @param listener Callback instance. + * + * @param listener + * Callback instance. */ public void setOnCenterItemClickListener(OnCenterItemClickListener listener) { mCenterItemClickListener = listener; @@ -699,13 +767,15 @@ public class TitlePageIndicator extends View implements PageIndicator { } @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + public void onPageScrolled(int position, float positionOffset, + int positionOffsetPixels) { mCurrentPage = position; mPageOffset = positionOffset; invalidate(); if (mListener != null) { - mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); + mListener.onPageScrolled(position, positionOffset, + positionOffsetPixels); } } @@ -728,32 +798,33 @@ public class TitlePageIndicator extends View implements PageIndicator { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - //Measure our width in whatever mode specified + // Measure our width in whatever mode specified final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); - //Determine our height + // Determine our height float height = 0; final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); if (heightSpecMode == MeasureSpec.EXACTLY) { - //We were told how big to be + // We were told how big to be height = MeasureSpec.getSize(heightMeasureSpec); } else { - //Calculate the text bounds + // Calculate the text bounds mBounds.setEmpty(); mBounds.bottom = (int) (mPaintText.descent() - mPaintText.ascent()); - height = mBounds.bottom - mBounds.top + mFooterLineHeight + mFooterPadding + mTopPadding; + height = mBounds.bottom - mBounds.top + mFooterLineHeight + + mFooterPadding + mTopPadding; if (mFooterIndicatorStyle != IndicatorStyle.None) { height += mFooterIndicatorHeight; } } - final int measuredHeight = (int)height; + final int measuredHeight = (int) height; setMeasuredDimension(measuredWidth, measuredHeight); } @Override public void onRestoreInstanceState(Parcelable state) { - SavedState savedState = (SavedState)state; + SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; requestLayout(); diff --git a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/UnderlinePageIndicator.java b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/UnderlinePageIndicator.java index 4e1839f3af..bb2d4731e0 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/UnderlinePageIndicator.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/utils/ui/UnderlinePageIndicator.java @@ -18,8 +18,8 @@ import android.view.View; import android.view.ViewConfiguration; /** - * Draws a line for each page. The current page line is colored differently - * than the unselected page lines. + * Draws a line for each page. The current page line is colored differently than + * the unselected page lines. */ public class UnderlinePageIndicator extends View implements PageIndicator { private static final int INVALID_POINTER = -1; @@ -44,14 +44,15 @@ public class UnderlinePageIndicator extends View implements PageIndicator { private boolean mIsDragging; private final Runnable mFadeRunnable = new Runnable() { - @Override public void run() { - final int alpha = Math.max(mPaint.getAlpha() - mFadeBy, 0); - mPaint.setAlpha(alpha); - invalidate(); - if (alpha > 0) { - postDelayed(this, FADE_FRAME_MS); + @Override + public void run() { + final int alpha = Math.max(mPaint.getAlpha() - mFadeBy, 0); + mPaint.setAlpha(alpha); + invalidate(); + if (alpha > 0) { + postDelayed(this, FADE_FRAME_MS); + } } - } }; public UnderlinePageIndicator(Context context) { @@ -62,30 +63,44 @@ public class UnderlinePageIndicator extends View implements PageIndicator { this(context, attrs, R.attr.vpiUnderlinePageIndicatorStyle); } - public UnderlinePageIndicator(Context context, AttributeSet attrs, int defStyle) { + public UnderlinePageIndicator(Context context, AttributeSet attrs, + int defStyle) { super(context, attrs, defStyle); - if (isInEditMode()) return; + if (isInEditMode()) + return; final Resources res = getResources(); - //Load defaults from resources - final boolean defaultFades = res.getBoolean(R.bool.default_underline_indicator_fades); - final int defaultFadeDelay = res.getInteger(R.integer.default_underline_indicator_fade_delay); - final int defaultFadeLength = res.getInteger(R.integer.default_underline_indicator_fade_length); - final int defaultSelectedColor = res.getColor(R.color.default_underline_indicator_selected_color); - - //Retrieve styles attributes - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UnderlinePageIndicator, defStyle, 0); - - setFades(a.getBoolean(R.styleable.UnderlinePageIndicator_fades, defaultFades)); - setSelectedColor(a.getColor(R.styleable.UnderlinePageIndicator_selectedColor, defaultSelectedColor)); - setFadeDelay(a.getInteger(R.styleable.UnderlinePageIndicator_fadeDelay, defaultFadeDelay)); - setFadeLength(a.getInteger(R.styleable.UnderlinePageIndicator_fadeLength, defaultFadeLength)); + // Load defaults from resources + final boolean defaultFades = res + .getBoolean(R.bool.default_underline_indicator_fades); + final int defaultFadeDelay = res + .getInteger(R.integer.default_underline_indicator_fade_delay); + final int defaultFadeLength = res + .getInteger(R.integer.default_underline_indicator_fade_length); + final int defaultSelectedColor = res + .getColor(R.color.default_underline_indicator_selected_color); + + // Retrieve styles attributes + TypedArray a = context.obtainStyledAttributes(attrs, + R.styleable.UnderlinePageIndicator, defStyle, 0); + + setFades(a.getBoolean(R.styleable.UnderlinePageIndicator_fades, + defaultFades)); + setSelectedColor(a.getColor( + R.styleable.UnderlinePageIndicator_selectedColor, + defaultSelectedColor)); + setFadeDelay(a.getInteger(R.styleable.UnderlinePageIndicator_fadeDelay, + defaultFadeDelay)); + setFadeLength(a.getInteger( + R.styleable.UnderlinePageIndicator_fadeLength, + defaultFadeLength)); a.recycle(); final ViewConfiguration configuration = ViewConfiguration.get(context); - mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); + mTouchSlop = ViewConfigurationCompat + .getScaledPagingTouchSlop(configuration); } public boolean getFades() { @@ -149,8 +164,10 @@ public class UnderlinePageIndicator extends View implements PageIndicator { } final int paddingLeft = getPaddingLeft(); - final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) / (1f * count); - final float left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset); + final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) + / (1f * count); + final float left = paddingLeft + pageWidth + * (mCurrentPage + mPositionOffset); final float right = left + pageWidth; final float top = getPaddingTop(); final float bottom = getHeight() - getPaddingBottom(); @@ -168,71 +185,77 @@ public class UnderlinePageIndicator extends View implements PageIndicator { final int action = ev.getAction(); switch (action & MotionEventCompat.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - mActivePointerId = MotionEventCompat.getPointerId(ev, 0); - mLastMotionX = ev.getX(); - break; - - case MotionEvent.ACTION_MOVE: { - final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); - final float x = MotionEventCompat.getX(ev, activePointerIndex); - final float deltaX = x - mLastMotionX; - - if (!mIsDragging) { - if (Math.abs(deltaX) > mTouchSlop) { - mIsDragging = true; - } + case MotionEvent.ACTION_DOWN: + mActivePointerId = MotionEventCompat.getPointerId(ev, 0); + mLastMotionX = ev.getX(); + break; + + case MotionEvent.ACTION_MOVE: { + final int activePointerIndex = MotionEventCompat.findPointerIndex( + ev, mActivePointerId); + final float x = MotionEventCompat.getX(ev, activePointerIndex); + final float deltaX = x - mLastMotionX; + + if (!mIsDragging) { + if (Math.abs(deltaX) > mTouchSlop) { + mIsDragging = true; } + } - if (mIsDragging) { - mLastMotionX = x; - if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { - mViewPager.fakeDragBy(deltaX); - } + if (mIsDragging) { + mLastMotionX = x; + if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { + mViewPager.fakeDragBy(deltaX); } - - break; } - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - if (!mIsDragging) { - final int count = mViewPager.getAdapter().getCount(); - final int width = getWidth(); - final float halfWidth = width / 2f; - final float sixthWidth = width / 6f; - - if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) { - mViewPager.setCurrentItem(mCurrentPage - 1); - return true; - } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) { - mViewPager.setCurrentItem(mCurrentPage + 1); - return true; - } + break; + } + + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + if (!mIsDragging) { + final int count = mViewPager.getAdapter().getCount(); + final int width = getWidth(); + final float halfWidth = width / 2f; + final float sixthWidth = width / 6f; + + if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) { + mViewPager.setCurrentItem(mCurrentPage - 1); + return true; + } else if ((mCurrentPage < count - 1) + && (ev.getX() > halfWidth + sixthWidth)) { + mViewPager.setCurrentItem(mCurrentPage + 1); + return true; } + } - mIsDragging = false; - mActivePointerId = INVALID_POINTER; - if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag(); - break; + mIsDragging = false; + mActivePointerId = INVALID_POINTER; + if (mViewPager.isFakeDragging()) + mViewPager.endFakeDrag(); + break; + + case MotionEventCompat.ACTION_POINTER_DOWN: { + final int index = MotionEventCompat.getActionIndex(ev); + final float x = MotionEventCompat.getX(ev, index); + mLastMotionX = x; + mActivePointerId = MotionEventCompat.getPointerId(ev, index); + break; + } - case MotionEventCompat.ACTION_POINTER_DOWN: { - final int index = MotionEventCompat.getActionIndex(ev); - final float x = MotionEventCompat.getX(ev, index); - mLastMotionX = x; - mActivePointerId = MotionEventCompat.getPointerId(ev, index); - break; + case MotionEventCompat.ACTION_POINTER_UP: + final int pointerIndex = MotionEventCompat.getActionIndex(ev); + final int pointerId = MotionEventCompat.getPointerId(ev, + pointerIndex); + if (pointerId == mActivePointerId) { + final int newPointerIndex = pointerIndex == 0 ? 1 : 0; + mActivePointerId = MotionEventCompat.getPointerId(ev, + newPointerIndex); } - - case MotionEventCompat.ACTION_POINTER_UP: - final int pointerIndex = MotionEventCompat.getActionIndex(ev); - final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); - if (pointerId == mActivePointerId) { - final int newPointerIndex = pointerIndex == 0 ? 1 : 0; - mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); - } - mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); - break; + mLastMotionX = MotionEventCompat.getX(ev, + MotionEventCompat.findPointerIndex(ev, mActivePointerId)); + break; } return true; @@ -244,17 +267,19 @@ public class UnderlinePageIndicator extends View implements PageIndicator { return; } if (mViewPager != null) { - //Clear us from the old pager. + // Clear us from the old pager. mViewPager.setOnPageChangeListener(null); } if (viewPager.getAdapter() == null) { - throw new IllegalStateException("ViewPager does not have adapter instance."); + throw new IllegalStateException( + "ViewPager does not have adapter instance."); } mViewPager = viewPager; mViewPager.setOnPageChangeListener(this); invalidate(); post(new Runnable() { - @Override public void run() { + @Override + public void run() { if (mFades) { post(mFadeRunnable); } @@ -293,7 +318,8 @@ public class UnderlinePageIndicator extends View implements PageIndicator { } @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + public void onPageScrolled(int position, float positionOffset, + int positionOffsetPixels) { mCurrentPage = position; mPositionOffset = positionOffset; if (mFades) { @@ -307,7 +333,8 @@ public class UnderlinePageIndicator extends View implements PageIndicator { invalidate(); if (mListener != null) { - mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); + mListener.onPageScrolled(position, positionOffset, + positionOffsetPixels); } } @@ -331,7 +358,7 @@ public class UnderlinePageIndicator extends View implements PageIndicator { @Override public void onRestoreInstanceState(Parcelable state) { - SavedState savedState = (SavedState)state; + SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; requestLayout(); diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/AccountScreenDashboard.java b/Open-ILS/src/Android/src/org/evergreen/android/views/AccountScreenDashboard.java index 561f3ac633..87e8570b41 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/AccountScreenDashboard.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/AccountScreenDashboard.java @@ -1,4 +1,3 @@ - package org.evergreen.android.views; import org.evergreen.android.R; @@ -15,147 +14,150 @@ import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; - public class AccountScreenDashboard extends Activity { - /** - * onCreate - called when the activity is first created. - * - * Called when the activity is first created. This is where you should do - * all of your normal static set up: create views, bind data to lists, etc. - * This method also provides you with a Bundle containing the activity's - * previously frozen state, if there was one. - * - * Always followed by onStart(). - * - */ - - private Button homeButton = null; - - private Button myAccountButton = null; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.dashbord_account); - - myAccountButton = (Button) findViewById(R.id.my_account_button); - - myAccountButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - } - }); - - homeButton = (Button) findViewById(R.id.library_logo); - - homeButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - - Intent intent = new Intent(getApplicationContext(),SearchCatalogListView.class); - startActivity(intent); - } - }); - } - - /** - * onDestroy The final call you receive before your activity is destroyed. - * This can happen either because the activity is finishing (someone called - * finish() on it, or because the system is temporarily destroying this - * instance of the activity to save space. You can distinguish between these - * two scenarios with the isFinishing() method. - * - */ - - protected void onDestroy() { - super.onDestroy(); - } - - /** - * onPause Called when the system is about to start resuming a previous - * activity. This is typically used to commit unsaved changes to persistent - * data, stop animations and other things that may be consuming CPU, etc. - * Implementations of this method must be very quick because the next - * activity will not be resumed until this method returns. Followed by - * either onResume() if the activity returns back to the front, or onStop() - * if it becomes invisible to the user. - * - */ - - protected void onPause() { - super.onPause(); - } - - /** - * onRestart Called after your activity has been stopped, prior to it being - * started again. Always followed by onStart(). - * - */ - - protected void onRestart() { - super.onRestart(); - } - - /** - * onResume Called when the activity will start interacting with the user. - * At this point your activity is at the top of the activity stack, with - * user input going to it. Always followed by onPause(). - * - */ - - protected void onResume() { - super.onResume(); - } - - /** - * onStart Called when the activity is becoming visible to the user. - * Followed by onResume() if the activity comes to the foreground, or - * onStop() if it becomes hidden. - * - */ - - protected void onStart() { - super.onStart(); - } - - /** - * onStop Called when the activity is no longer visible to the user because - * another activity has been resumed and is covering this one. This may - * happen either because a new activity is being started, an existing one is - * being brought in front of this one, or this one is being destroyed. - * - * Followed by either onRestart() if this activity is coming back to - * interact with the user, or onDestroy() if this activity is going away. - */ - - protected void onStop() { - super.onStop(); - } - - public void onClickFeature (View v) - { - int id = v.getId (); - switch (id) { - - case R.id.account_btn_check_out : - startActivity (new Intent(getApplicationContext(),ItemsCheckOutListView.class)); - break; - case R.id.account_btn_holds: - startActivity (new Intent(getApplicationContext(), HoldsListView.class)); - break; - case R.id.account_btn_fines : - startActivity (new Intent(getApplicationContext(), FinesActivity.class)); - break; - case R.id.account_btn_book_bags : - startActivity (new Intent(getApplicationContext(), BookbagsListView.class)); - break; - default: - break; - - } - - } - -} + /** + * onCreate - called when the activity is first created. + * + * Called when the activity is first created. This is where you should do + * all of your normal static set up: create views, bind data to lists, etc. + * This method also provides you with a Bundle containing the activity's + * previously frozen state, if there was one. + * + * Always followed by onStart(). + * + */ + + private Button homeButton = null; + + private Button myAccountButton = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.dashbord_account); + + myAccountButton = (Button) findViewById(R.id.my_account_button); + + myAccountButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + } + }); + + homeButton = (Button) findViewById(R.id.library_logo); + + homeButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + + Intent intent = new Intent(getApplicationContext(), + SearchCatalogListView.class); + startActivity(intent); + } + }); + } + + /** + * onDestroy The final call you receive before your activity is destroyed. + * This can happen either because the activity is finishing (someone called + * finish() on it, or because the system is temporarily destroying this + * instance of the activity to save space. You can distinguish between these + * two scenarios with the isFinishing() method. + * + */ + + protected void onDestroy() { + super.onDestroy(); + } + + /** + * onPause Called when the system is about to start resuming a previous + * activity. This is typically used to commit unsaved changes to persistent + * data, stop animations and other things that may be consuming CPU, etc. + * Implementations of this method must be very quick because the next + * activity will not be resumed until this method returns. Followed by + * either onResume() if the activity returns back to the front, or onStop() + * if it becomes invisible to the user. + * + */ + + protected void onPause() { + super.onPause(); + } + + /** + * onRestart Called after your activity has been stopped, prior to it being + * started again. Always followed by onStart(). + * + */ + + protected void onRestart() { + super.onRestart(); + } + + /** + * onResume Called when the activity will start interacting with the user. + * At this point your activity is at the top of the activity stack, with + * user input going to it. Always followed by onPause(). + * + */ + + protected void onResume() { + super.onResume(); + } + + /** + * onStart Called when the activity is becoming visible to the user. + * Followed by onResume() if the activity comes to the foreground, or + * onStop() if it becomes hidden. + * + */ + + protected void onStart() { + super.onStart(); + } + + /** + * onStop Called when the activity is no longer visible to the user because + * another activity has been resumed and is covering this one. This may + * happen either because a new activity is being started, an existing one is + * being brought in front of this one, or this one is being destroyed. + * + * Followed by either onRestart() if this activity is coming back to + * interact with the user, or onDestroy() if this activity is going away. + */ + + protected void onStop() { + super.onStop(); + } + + public void onClickFeature(View v) { + int id = v.getId(); + switch (id) { + + case R.id.account_btn_check_out: + startActivity(new Intent(getApplicationContext(), + ItemsCheckOutListView.class)); + break; + case R.id.account_btn_holds: + startActivity(new Intent(getApplicationContext(), + HoldsListView.class)); + break; + case R.id.account_btn_fines: + startActivity(new Intent(getApplicationContext(), + FinesActivity.class)); + break; + case R.id.account_btn_book_bags: + startActivity(new Intent(getApplicationContext(), + BookbagsListView.class)); + break; + default: + break; + + } + + } + +} diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/ApplicationPreferences.java b/Open-ILS/src/Android/src/org/evergreen/android/views/ApplicationPreferences.java index 51220eaa85..6c1af45a0e 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/ApplicationPreferences.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/ApplicationPreferences.java @@ -30,262 +30,295 @@ import android.provider.Settings; import android.util.Log; import android.widget.Toast; -public class ApplicationPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{ - - - private ProgressDialog progressDialog; - - private ApplicationPreferences reference; - - private Context context; - - private String TAG = "ApplicationPreferences"; - - private Thread connectionThread = null; - - private Thread coreFilesDownload = null; - - @Override - protected void onCreate(Bundle savedInstanceState) { - - super.onCreate(savedInstanceState); - - addPreferencesFromResource(R.xml.application_preference_screen); - - context = this; - reference = this; - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - //register preference listener - prefs.registerOnSharedPreferenceChangeListener(this); - - } - - - @Override - protected void onResume() { - super.onResume(); - reference = this; - } - @Override - protected void onPause() { - super.onPause(); - reference = null; - } - - @Override - protected void onStop() { - super.onStop(); - reference = null; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - reference = null; - } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, - String key) { - - boolean httpAddressChange = false; - - connectionThread = new Thread(new Runnable() { - - @Override - public void run() { - - boolean routeToAddress = true; - AccountAccess account = AccountAccess.getAccountAccess(GlobalConfigs.httpAddress,(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)); - try{ - Utils.checkNetworkStatus((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)); - }catch(NoNetworkAccessException e){ - routeToAddress = false; - - Log.d(TAG," No network access"); - - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(reference != null){ - progressDialog.dismiss(); - AlertDialog.Builder builder = new AlertDialog.Builder(context); - builder.setMessage("There seams to be no network connectivity! Do you want to start network settings?").setPositiveButton("Yes", dialogClickListener) - .setNegativeButton("No", dialogClickListener).show(); - } - } - }); - - }catch(NoAccessToServer e){ - - Log.d(TAG, " no route to hoast"); - routeToAddress = false; - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(reference != null) - Toast.makeText(getApplicationContext(), "There is no route to host :" + GlobalConfigs.httpAddress, Toast.LENGTH_LONG).show(); - } - - }); - } - - - if(routeToAddress){ - - try{ - if(account.authenticate()){ - - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(reference != null){ - progressDialog.dismiss(); - Toast.makeText(context, "Autenthication successfully established :" + GlobalConfigs.httpAddress, Toast.LENGTH_LONG).show(); - } - } - }); - }else{ - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(reference != null){ - progressDialog.dismiss(); - Toast.makeText(context, "Please check username and password ", Toast.LENGTH_LONG).show(); - } - } - }); - } - - }catch(Exception e){} - - } - else - runOnUiThread(new Runnable() { - - @Override - public void run() { - if(reference != null) - progressDialog.dismiss(); - } - }); - } - }); - - boolean checkConnection = false; - - if(key.equals("username")){ - AccountAccess.userName = sharedPreferences.getString("username", ""); - checkConnection = true; - }else - if(key.equals("password")){ - AccountAccess.password = sharedPreferences.getString("password", ""); - checkConnection = true; - }else - if(key.equals("library_url")){ - checkConnection = true; - GlobalConfigs.httpAddress = sharedPreferences.getString("library_url", ""); - - httpAddressChange = true; - System.out.println("Show dialog"); - - progressDialog = ProgressDialog.show(context, "Core files", "Downloading FM_IDL and OrgTree"); - - coreFilesDownload = new Thread(new Runnable() { - - @Override - public void run() { - System.out.println("FM idl download"); - GlobalConfigs sg = GlobalConfigs.getGlobalConfigs(context); - sg.loadIDLFile(); - sg.getOrganisations(); - sg.getCopyStatusesAvailable((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)); - runOnUiThread(new Runnable() { - public void run() { - progressDialog.dismiss(); - } - }); - - connectionThread.start(); - } - }); - - coreFilesDownload.start(); - - //wait for execution - - } - if(key.equals("notifications_enabled")){ - - if(sharedPreferences.getBoolean("notifications_enabled", false)){ - - Toast.makeText(context, "Set up notification updates", Toast.LENGTH_SHORT).show(); - //if enabled register the update service to run once per day - // get a Calendar object with current time - Calendar cal = Calendar.getInstance(); - - Intent bRecvIntent = new Intent(this,PeriodicServiceBroadcastReceiver.class); - bRecvIntent.setAction(ScheduledIntentService.ACTION); - // update the current intent if it exists - PendingIntent sender = PendingIntent.getBroadcast(this, - NotificationAlert.NOTIFICATION_INTENT + PeriodicServiceBroadcastReceiver.INTENT_ID, bRecvIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - - // Get the AlarmManager service - AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); - am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 10000 * ScheduledIntentService.SCHEDULE_TIME_INTERVAL, sender); - } - else - { - Toast.makeText(context, "Disable notification updates", Toast.LENGTH_SHORT).show(); - //cancel the service - - Intent bRecvIntent = new Intent(this,PeriodicServiceBroadcastReceiver.class); - - // update the current intent if it exists - PendingIntent sender = PendingIntent.getBroadcast(this, - NotificationAlert.NOTIFICATION_INTENT + PeriodicServiceBroadcastReceiver.INTENT_ID, bRecvIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - - // Get the AlarmManager service - AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); - //cancel the service - am.cancel(sender); - } - //register the - - } - - //test connection - if(!isFinishing() && httpAddressChange == false && checkConnection == true){ - progressDialog = ProgressDialog.show(this, "Account login", "Please wait while we test the new user account information"); - - connectionThread.start(); - } - } -/* - * Dialog interface for starting the network settings - */ - DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (which){ - case DialogInterface.BUTTON_POSITIVE: - //Yes button clicked - - context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); - - break; - - case DialogInterface.BUTTON_NEGATIVE: - //No button clicked - - break; - } - } - }; - +public class ApplicationPreferences extends PreferenceActivity implements + OnSharedPreferenceChangeListener { + + private ProgressDialog progressDialog; + + private ApplicationPreferences reference; + + private Context context; + + private String TAG = "ApplicationPreferences"; + + private Thread connectionThread = null; + + private Thread coreFilesDownload = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + + super.onCreate(savedInstanceState); + + addPreferencesFromResource(R.xml.application_preference_screen); + + context = this; + reference = this; + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + // register preference listener + prefs.registerOnSharedPreferenceChangeListener(this); + + } + + @Override + protected void onResume() { + super.onResume(); + reference = this; + } + + @Override + protected void onPause() { + super.onPause(); + reference = null; + } + + @Override + protected void onStop() { + super.onStop(); + reference = null; + } + + @Override + protected void onDestroy() { + super.onDestroy(); + reference = null; + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, + String key) { + + boolean httpAddressChange = false; + + connectionThread = new Thread(new Runnable() { + + @Override + public void run() { + + boolean routeToAddress = true; + AccountAccess account = AccountAccess + .getAccountAccess( + GlobalConfigs.httpAddress, + (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)); + try { + Utils.checkNetworkStatus((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)); + } catch (NoNetworkAccessException e) { + routeToAddress = false; + + Log.d(TAG, " No network access"); + + runOnUiThread(new Runnable() { + + @Override + public void run() { + if (reference != null) { + progressDialog.dismiss(); + AlertDialog.Builder builder = new AlertDialog.Builder( + context); + builder.setMessage( + "There seams to be no network connectivity! Do you want to start network settings?") + .setPositiveButton("Yes", + dialogClickListener) + .setNegativeButton("No", + dialogClickListener).show(); + } + } + }); + + } catch (NoAccessToServer e) { + + Log.d(TAG, " no route to hoast"); + routeToAddress = false; + runOnUiThread(new Runnable() { + + @Override + public void run() { + if (reference != null) + Toast.makeText( + getApplicationContext(), + "There is no route to host :" + + GlobalConfigs.httpAddress, + Toast.LENGTH_LONG).show(); + } + + }); + } + + if (routeToAddress) { + + try { + if (account.authenticate()) { + + runOnUiThread(new Runnable() { + + @Override + public void run() { + if (reference != null) { + progressDialog.dismiss(); + Toast.makeText( + context, + "Autenthication successfully established :" + + GlobalConfigs.httpAddress, + Toast.LENGTH_LONG).show(); + } + } + }); + } else { + runOnUiThread(new Runnable() { + + @Override + public void run() { + if (reference != null) { + progressDialog.dismiss(); + Toast.makeText( + context, + "Please check username and password ", + Toast.LENGTH_LONG).show(); + } + } + }); + } + + } catch (Exception e) { + } + + } else + runOnUiThread(new Runnable() { + + @Override + public void run() { + if (reference != null) + progressDialog.dismiss(); + } + }); + } + }); + + boolean checkConnection = false; + + if (key.equals("username")) { + AccountAccess.userName = sharedPreferences + .getString("username", ""); + checkConnection = true; + } else if (key.equals("password")) { + AccountAccess.password = sharedPreferences + .getString("password", ""); + checkConnection = true; + } else if (key.equals("library_url")) { + checkConnection = true; + GlobalConfigs.httpAddress = sharedPreferences.getString( + "library_url", ""); + + httpAddressChange = true; + System.out.println("Show dialog"); + + progressDialog = ProgressDialog.show(context, "Core files", + "Downloading FM_IDL and OrgTree"); + + coreFilesDownload = new Thread(new Runnable() { + + @Override + public void run() { + System.out.println("FM idl download"); + GlobalConfigs sg = GlobalConfigs.getGlobalConfigs(context); + sg.loadIDLFile(); + sg.getOrganisations(); + sg.getCopyStatusesAvailable((ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE)); + runOnUiThread(new Runnable() { + public void run() { + progressDialog.dismiss(); + } + }); + + connectionThread.start(); + } + }); + + coreFilesDownload.start(); + + // wait for execution + + } + if (key.equals("notifications_enabled")) { + + if (sharedPreferences.getBoolean("notifications_enabled", false)) { + + Toast.makeText(context, "Set up notification updates", + Toast.LENGTH_SHORT).show(); + // if enabled register the update service to run once per day + // get a Calendar object with current time + Calendar cal = Calendar.getInstance(); + + Intent bRecvIntent = new Intent(this, + PeriodicServiceBroadcastReceiver.class); + bRecvIntent.setAction(ScheduledIntentService.ACTION); + // update the current intent if it exists + PendingIntent sender = PendingIntent.getBroadcast(this, + NotificationAlert.NOTIFICATION_INTENT + + PeriodicServiceBroadcastReceiver.INTENT_ID, + bRecvIntent, PendingIntent.FLAG_UPDATE_CURRENT); + + // Get the AlarmManager service + AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); + am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), + 10000 * ScheduledIntentService.SCHEDULE_TIME_INTERVAL, + sender); + } else { + Toast.makeText(context, "Disable notification updates", + Toast.LENGTH_SHORT).show(); + // cancel the service + + Intent bRecvIntent = new Intent(this, + PeriodicServiceBroadcastReceiver.class); + + // update the current intent if it exists + PendingIntent sender = PendingIntent.getBroadcast(this, + NotificationAlert.NOTIFICATION_INTENT + + PeriodicServiceBroadcastReceiver.INTENT_ID, + bRecvIntent, PendingIntent.FLAG_UPDATE_CURRENT); + + // Get the AlarmManager service + AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); + // cancel the service + am.cancel(sender); + } + // register the + + } + + // test connection + if (!isFinishing() && httpAddressChange == false + && checkConnection == true) { + progressDialog = ProgressDialog + .show(this, "Account login", + "Please wait while we test the new user account information"); + + connectionThread.start(); + } + } + + /* + * Dialog interface for starting the network settings + */ + DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + // Yes button clicked + + context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); + + break; + + case DialogInterface.BUTTON_NEGATIVE: + // No button clicked + + break; + } + } + }; + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/ConfigureApplicationActivity.java b/Open-ILS/src/Android/src/org/evergreen/android/views/ConfigureApplicationActivity.java index 0803c3e204..2f3d122c0a 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/ConfigureApplicationActivity.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/ConfigureApplicationActivity.java @@ -21,133 +21,136 @@ import android.widget.Button; import android.widget.EditText; import android.widget.Toast; -public class ConfigureApplicationActivity extends Activity{ - - private String TAG = "ConfigureApplicationActivity"; - - private ProgressDialog progressDialog = null; - - private EditText server_http; - - private EditText username; - - private EditText password; - - private Context context; - - - public static final int RESULT_CONFIGURE_SUCCESS = 10; - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - setContentView(R.layout.configure_application); - context = this; - server_http = (EditText) findViewById(R.id.server_http_adress); - username = (EditText) findViewById(R.id.username); - password = (EditText) findViewById(R.id.password); - - Button connect = (Button) findViewById(R.id.connect_button); - - - connect.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - - Thread checkConn = new Thread(new Runnable() { - @Override - public void run() { - - boolean server_address = false; - boolean auth = false; - - try { - server_address = Utils - .checkIfNetAddressIsReachable(server_http - .getText().toString()); - } catch (NoAccessToServer e) { - server_address = false; - } - - if (server_address == true) { - - SharedPreferences preferences = PreferenceManager - .getDefaultSharedPreferences(context); - SharedPreferences.Editor editor = preferences - .edit(); - //store into preference - editor.putString("library_url", server_http - .getText().toString()); - - - editor.putString("username", username.getText().toString()); - editor.putString("password", password.getText().toString()); - - editor.commit(); - GlobalConfigs.httpAddress = server_http.getText().toString(); - AccountAccess accountAccess = AccountAccess - .getAccountAccess(GlobalConfigs.httpAddress,(ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE)); - - AccountAccess.setAccountInfo(username.getText().toString(),password.getText().toString()); - - try { - auth = accountAccess.authenticate(); - Log.d(TAG, "Auth " + auth); - } catch (Exception e) { - System.out.println("Exception " + e.getMessage()); - } - - if (auth == true) { - - runOnUiThread(new Runnable() { - - @Override - public void run() { - progressDialog.dismiss(); - setResult(RESULT_CONFIGURE_SUCCESS); - finish(); - - } - }); - - - } else { - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - Toast.makeText(context, - "Bad user login information", - Toast.LENGTH_LONG).show(); - } - }); - } - - } else { - runOnUiThread(new Runnable() { - @Override - public void run() { - progressDialog.dismiss(); - Toast.makeText(context, - "Bad library server url", - Toast.LENGTH_LONG).show(); - } - }); - - } - - } - }); - - progressDialog = ProgressDialog.show(context, "Please wait", - "Checking server and credentials"); - checkConn.start(); - } - - }); - - } - - +public class ConfigureApplicationActivity extends Activity { + + private String TAG = "ConfigureApplicationActivity"; + + private ProgressDialog progressDialog = null; + + private EditText server_http; + + private EditText username; + + private EditText password; + + private Context context; + + public static final int RESULT_CONFIGURE_SUCCESS = 10; + + @Override + protected void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + setContentView(R.layout.configure_application); + context = this; + server_http = (EditText) findViewById(R.id.server_http_adress); + username = (EditText) findViewById(R.id.username); + password = (EditText) findViewById(R.id.password); + + Button connect = (Button) findViewById(R.id.connect_button); + + connect.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + Thread checkConn = new Thread(new Runnable() { + @Override + public void run() { + + boolean server_address = false; + boolean auth = false; + + try { + server_address = Utils + .checkIfNetAddressIsReachable(server_http + .getText().toString()); + } catch (NoAccessToServer e) { + server_address = false; + } + + if (server_address == true) { + + SharedPreferences preferences = PreferenceManager + .getDefaultSharedPreferences(context); + SharedPreferences.Editor editor = preferences + .edit(); + // store into preference + editor.putString("library_url", server_http + .getText().toString()); + + editor.putString("username", username.getText() + .toString()); + editor.putString("password", password.getText() + .toString()); + + editor.commit(); + GlobalConfigs.httpAddress = server_http.getText() + .toString(); + AccountAccess accountAccess = AccountAccess + .getAccountAccess( + GlobalConfigs.httpAddress, + (ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE)); + + AccountAccess.setAccountInfo(username.getText() + .toString(), password.getText().toString()); + + try { + auth = accountAccess.authenticate(); + Log.d(TAG, "Auth " + auth); + } catch (Exception e) { + System.out.println("Exception " + + e.getMessage()); + } + + if (auth == true) { + + runOnUiThread(new Runnable() { + + @Override + public void run() { + progressDialog.dismiss(); + setResult(RESULT_CONFIGURE_SUCCESS); + finish(); + + } + }); + + } else { + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + Toast.makeText(context, + "Bad user login information", + Toast.LENGTH_LONG).show(); + } + }); + } + + } else { + runOnUiThread(new Runnable() { + @Override + public void run() { + progressDialog.dismiss(); + Toast.makeText(context, + "Bad library server url", + Toast.LENGTH_LONG).show(); + } + }); + + } + + } + }); + + progressDialog = ProgressDialog.show(context, "Please wait", + "Checking server and credentials"); + checkConn.start(); + } + + }); + + } + } diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/MainScreenDashboard.java b/Open-ILS/src/Android/src/org/evergreen/android/views/MainScreenDashboard.java index 8f89e5161d..730c9a833c 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/MainScreenDashboard.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/MainScreenDashboard.java @@ -1,4 +1,3 @@ - package org.evergreen.android.views; import org.evergreen.android.R; @@ -10,125 +9,126 @@ import android.content.Intent; import android.os.Bundle; import android.view.View; - public class MainScreenDashboard extends Activity { - /** - * onCreate - called when the activity is first created. - * - * Called when the activity is first created. This is where you should do - * all of your normal static set up: create views, bind data to lists, etc. - * This method also provides you with a Bundle containing the activity's - * previously frozen state, if there was one. - * - * Always followed by onStart(). - * - */ - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.dashbord_main); - - //init here globals, - //TODO in future do a splash screen (loading data) - - } - - /** - * onDestroy The final call you receive before your activity is destroyed. - * This can happen either because the activity is finishing (someone called - * finish() on it, or because the system is temporarily destroying this - * instance of the activity to save space. You can distinguish between these - * two scenarios with the isFinishing() method. - * - */ - - protected void onDestroy() { - super.onDestroy(); - } - - /** - * onPause Called when the system is about to start resuming a previous - * activity. This is typically used to commit unsaved changes to persistent - * data, stop animations and other things that may be consuming CPU, etc. - * Implementations of this method must be very quick because the next - * activity will not be resumed until this method returns. Followed by - * either onResume() if the activity returns back to the front, or onStop() - * if it becomes invisible to the user. - * - */ - - protected void onPause() { - super.onPause(); - } - - /** - * onRestart Called after your activity has been stopped, prior to it being - * started again. Always followed by onStart(). - * - */ - - protected void onRestart() { - super.onRestart(); - } - - /** - * onResume Called when the activity will start interacting with the user. - * At this point your activity is at the top of the activity stack, with - * user input going to it. Always followed by onPause(). - * - */ - - protected void onResume() { - super.onResume(); - } - - /** - * onStart Called when the activity is becoming visible to the user. - * Followed by onResume() if the activity comes to the foreground, or - * onStop() if it becomes hidden. - * - */ - - protected void onStart() { - super.onStart(); - } - - /** - * onStop Called when the activity is no longer visible to the user because - * another activity has been resumed and is covering this one. This may - * happen either because a new activity is being started, an existing one is - * being brought in front of this one, or this one is being destroyed. - * - * Followed by either onRestart() if this activity is coming back to - * interact with the user, or onDestroy() if this activity is going away. - */ - - protected void onStop() { - super.onStop(); - } - - public void onClickFeature (View v) - { - int id = v.getId (); - switch (id) { - - case R.id.main_btn_search : - startActivity (new Intent(getApplicationContext(), SearchCatalogListView.class)); - break; - case R.id.main_btn_account: - startActivity (new Intent(getApplicationContext(), AccountScreenDashboard.class)); - break; - case R.id.main_btn_app_settings : - startActivity(new Intent(getApplicationContext(),ApplicationPreferences.class)); - break; - - default: - break; - - } - - } - -} + /** + * onCreate - called when the activity is first created. + * + * Called when the activity is first created. This is where you should do + * all of your normal static set up: create views, bind data to lists, etc. + * This method also provides you with a Bundle containing the activity's + * previously frozen state, if there was one. + * + * Always followed by onStart(). + * + */ + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.dashbord_main); + + // init here globals, + // TODO in future do a splash screen (loading data) + + } + + /** + * onDestroy The final call you receive before your activity is destroyed. + * This can happen either because the activity is finishing (someone called + * finish() on it, or because the system is temporarily destroying this + * instance of the activity to save space. You can distinguish between these + * two scenarios with the isFinishing() method. + * + */ + + protected void onDestroy() { + super.onDestroy(); + } + + /** + * onPause Called when the system is about to start resuming a previous + * activity. This is typically used to commit unsaved changes to persistent + * data, stop animations and other things that may be consuming CPU, etc. + * Implementations of this method must be very quick because the next + * activity will not be resumed until this method returns. Followed by + * either onResume() if the activity returns back to the front, or onStop() + * if it becomes invisible to the user. + * + */ + + protected void onPause() { + super.onPause(); + } + + /** + * onRestart Called after your activity has been stopped, prior to it being + * started again. Always followed by onStart(). + * + */ + + protected void onRestart() { + super.onRestart(); + } + + /** + * onResume Called when the activity will start interacting with the user. + * At this point your activity is at the top of the activity stack, with + * user input going to it. Always followed by onPause(). + * + */ + + protected void onResume() { + super.onResume(); + } + + /** + * onStart Called when the activity is becoming visible to the user. + * Followed by onResume() if the activity comes to the foreground, or + * onStop() if it becomes hidden. + * + */ + + protected void onStart() { + super.onStart(); + } + + /** + * onStop Called when the activity is no longer visible to the user because + * another activity has been resumed and is covering this one. This may + * happen either because a new activity is being started, an existing one is + * being brought in front of this one, or this one is being destroyed. + * + * Followed by either onRestart() if this activity is coming back to + * interact with the user, or onDestroy() if this activity is going away. + */ + + protected void onStop() { + super.onStop(); + } + + public void onClickFeature(View v) { + int id = v.getId(); + switch (id) { + + case R.id.main_btn_search: + startActivity(new Intent(getApplicationContext(), + SearchCatalogListView.class)); + break; + case R.id.main_btn_account: + startActivity(new Intent(getApplicationContext(), + AccountScreenDashboard.class)); + break; + case R.id.main_btn_app_settings: + startActivity(new Intent(getApplicationContext(), + ApplicationPreferences.class)); + break; + + default: + break; + + } + + } + +} diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/LoadingTask.java b/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/LoadingTask.java index cb825b20e9..c7dcab6ba6 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/LoadingTask.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/LoadingTask.java @@ -16,95 +16,112 @@ import android.widget.TextView; public class LoadingTask extends AsyncTask { - public interface LoadingTaskFinishedListener { - void onTaskFinished(); // If you want to pass something back to the listener add a param to this method - } - - // This is the progress bar you want to update while the task is in progress - private final ProgressBar progressBar; - // This is the listener that will be told when this task is finished - private final LoadingTaskFinishedListener finishedListener; - - private Context context; - - private TextView progressText; - - private Activity callingActivity; - - private String text; - /** - * A Loading task that will load some resources that are necessary for the app to start - * @param progressBar - the progress bar you want to update while the task is in progress - * @param finishedListener - the listener that will be told when this task is finished - */ - public LoadingTask(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener, Context context, TextView progressText, Activity callingActivity) { - this.progressBar = progressBar; - this.finishedListener = finishedListener; - this.context = context; - this.progressText = progressText; - this.callingActivity = callingActivity; - } - - @Override - protected Integer doInBackground(String... params) { - Log.i("Start download", "Starting task with url: "+params[0]); - if(resourcesDontAlreadyExist()){ - downloadResources(); - } - // Perhaps you want to return something to your post execute - return 1234; - } - - private boolean resourcesDontAlreadyExist() { - // Here you would query your app's internal state to see if this download had been performed before - // Perhaps once checked save this in a shared preference for speed of access next time - return true; // returning true so we show the splash every time - } - - - private void downloadResources() { - // We are just imitating some process thats takes a bit of time (loading of resources / downloading) - int count = 10; - text = "download files"; - publishProgress(50); - - GlobalConfigs gl = GlobalConfigs.getGlobalConfigs(context); - text = "authenticate user"; - publishProgress(70); - - AccountAccess ac = AccountAccess.getAccountAccess(GlobalConfigs.httpAddress,(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)); - try{ - ac.authenticate(); - }catch(Exception e){} - text = "get user bookbags"; - publishProgress(90); - - try { - ac.bookBags = ac.getBookbags(); - } catch (SessionNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoNetworkAccessException e) { - e.printStackTrace(); - } catch (NoAccessToServer e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - text = "loading application"; - publishProgress(100); - - } - - @Override - protected void onProgressUpdate(Integer... values) { - super.onProgressUpdate(values); - progressBar.setProgress(values[0]); // This is ran on the UI thread so it is ok to update our progress bar ( a UI view ) here - progressText.setText(text); - } - - @Override - protected void onPostExecute(Integer result) { - super.onPostExecute(result); - finishedListener.onTaskFinished(); // Tell whoever was listening we have finished - } + public interface LoadingTaskFinishedListener { + void onTaskFinished(); // If you want to pass something back to the + // listener add a param to this method + } + + // This is the progress bar you want to update while the task is in progress + private final ProgressBar progressBar; + // This is the listener that will be told when this task is finished + private final LoadingTaskFinishedListener finishedListener; + + private Context context; + + private TextView progressText; + + private Activity callingActivity; + + private String text; + + /** + * A Loading task that will load some resources that are necessary for the + * app to start + * + * @param progressBar + * - the progress bar you want to update while the task is in + * progress + * @param finishedListener + * - the listener that will be told when this task is finished + */ + public LoadingTask(ProgressBar progressBar, + LoadingTaskFinishedListener finishedListener, Context context, + TextView progressText, Activity callingActivity) { + this.progressBar = progressBar; + this.finishedListener = finishedListener; + this.context = context; + this.progressText = progressText; + this.callingActivity = callingActivity; + } + + @Override + protected Integer doInBackground(String... params) { + Log.i("Start download", "Starting task with url: " + params[0]); + if (resourcesDontAlreadyExist()) { + downloadResources(); + } + // Perhaps you want to return something to your post execute + return 1234; + } + + private boolean resourcesDontAlreadyExist() { + // Here you would query your app's internal state to see if this + // download had been performed before + // Perhaps once checked save this in a shared preference for speed of + // access next time + return true; // returning true so we show the splash every time + } + + private void downloadResources() { + // We are just imitating some process thats takes a bit of time (loading + // of resources / downloading) + int count = 10; + text = "download files"; + publishProgress(50); + + GlobalConfigs gl = GlobalConfigs.getGlobalConfigs(context); + text = "authenticate user"; + publishProgress(70); + + AccountAccess ac = AccountAccess.getAccountAccess( + GlobalConfigs.httpAddress, (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE)); + try { + ac.authenticate(); + } catch (Exception e) { + } + text = "get user bookbags"; + publishProgress(90); + + try { + ac.bookBags = ac.getBookbags(); + } catch (SessionNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoNetworkAccessException e) { + e.printStackTrace(); + } catch (NoAccessToServer e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + text = "loading application"; + publishProgress(100); + + } + + @Override + protected void onProgressUpdate(Integer... values) { + super.onProgressUpdate(values); + progressBar.setProgress(values[0]); // This is ran on the UI thread so + // it is ok to update our progress + // bar ( a UI view ) here + progressText.setText(text); + } + + @Override + protected void onPostExecute(Integer result) { + super.onPostExecute(result); + finishedListener.onTaskFinished(); // Tell whoever was listening we have + // finished + } } \ No newline at end of file diff --git a/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/SplashActivity.java b/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/SplashActivity.java index 182e5b1f72..c71a8573d6 100644 --- a/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/SplashActivity.java +++ b/Open-ILS/src/Android/src/org/evergreen/android/views/splashscreen/SplashActivity.java @@ -31,87 +31,89 @@ import android.widget.TextView; import android.widget.Toast; public class SplashActivity extends Activity implements - LoadingTaskFinishedListener { - - private TextView progressText; - - private Context context; - - private ProgressBar progressBar; - - private String TAG = "SplashActivity"; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - this.context = this; - // Show the splash screen - setContentView(R.layout.activity_splash); - - - progressText = (TextView) findViewById(R.id.action_in_progress); - - // Find the progress bar - progressBar = (ProgressBar) findViewById(R.id.activity_splash_progress_bar); - - boolean abort = false; - - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - GlobalConfigs.httpAddress = prefs.getString("library_url", ""); - String username = prefs.getString("username", "username"); - String password = prefs.getString("password", "pas"); - AccountAccess.setAccountInfo(username, password); - try { - - Utils.checkNetworkStatus((ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE)); - } catch (NoNetworkAccessException e) { - abort = true; - e.printStackTrace(); - } catch (NoAccessToServer e) { - abort = true; - - //dialog.show(); - Intent configureIntent = new Intent(this,ConfigureApplicationActivity.class); - startActivityForResult(configureIntent,0); - - } - - if (abort != true) { - // Start your loading - new LoadingTask(progressBar, this, this, progressText, this) - .execute("download"); // Pass in whatever you need a url is - // just an example we don't use it - // in this tutorial - } - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - switch(resultCode){ - case ConfigureApplicationActivity.RESULT_CONFIGURE_SUCCESS : { - new LoadingTask(progressBar, this, this, progressText, this).execute("download"); - - } break; - - } - } - - // This is the callback for when your async task has finished - @Override - public void onTaskFinished() { - completeSplash(); - } - - private void completeSplash() { - startApp(); - finish(); // Don't forget to finish this Splash Activity so the user - // can't return to it! - } - - private void startApp() { - Intent intent = new Intent(SplashActivity.this, - SearchCatalogListView.class); - startActivity(intent); - } + LoadingTaskFinishedListener { + + private TextView progressText; + + private Context context; + + private ProgressBar progressBar; + + private String TAG = "SplashActivity"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.context = this; + // Show the splash screen + setContentView(R.layout.activity_splash); + + progressText = (TextView) findViewById(R.id.action_in_progress); + + // Find the progress bar + progressBar = (ProgressBar) findViewById(R.id.activity_splash_progress_bar); + + boolean abort = false; + + SharedPreferences prefs = PreferenceManager + .getDefaultSharedPreferences(context); + GlobalConfigs.httpAddress = prefs.getString("library_url", ""); + String username = prefs.getString("username", "username"); + String password = prefs.getString("password", "pas"); + AccountAccess.setAccountInfo(username, password); + try { + + Utils.checkNetworkStatus((ConnectivityManager) getSystemService(Service.CONNECTIVITY_SERVICE)); + } catch (NoNetworkAccessException e) { + abort = true; + e.printStackTrace(); + } catch (NoAccessToServer e) { + abort = true; + + // dialog.show(); + Intent configureIntent = new Intent(this, + ConfigureApplicationActivity.class); + startActivityForResult(configureIntent, 0); + + } + + if (abort != true) { + // Start your loading + new LoadingTask(progressBar, this, this, progressText, this) + .execute("download"); // Pass in whatever you need a url is + // just an example we don't use it + // in this tutorial + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (resultCode) { + case ConfigureApplicationActivity.RESULT_CONFIGURE_SUCCESS: { + new LoadingTask(progressBar, this, this, progressText, this) + .execute("download"); + + } + break; + + } + } + + // This is the callback for when your async task has finished + @Override + public void onTaskFinished() { + completeSplash(); + } + + private void completeSplash() { + startApp(); + finish(); // Don't forget to finish this Splash Activity so the user + // can't return to it! + } + + private void startApp() { + Intent intent = new Intent(SplashActivity.this, + SearchCatalogListView.class); + startActivity(intent); + } } \ No newline at end of file