List of usage examples for java.util ArrayList clear
public void clear()
From source file:edu.wpi.khufnagle.lighthousenavigator.PhotographsActivity.java
/** * Display the UI defined in activity_photographs.xml upon activity start. *///w ww.ja va 2 s .co m @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_photographs); /* * Add "up" button functionality in the left of application icon in * top-left corner, allowing user to return to "welcome" screen */ final ActionBar ab = this.getSupportActionBar(); ab.setDisplayHomeAsUpEnabled(true); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); /* * Create "navigation spinner" in activity action bar that allows user to * view a different content screen */ final ArrayAdapter<CharSequence> navDropDownAdapter = ArrayAdapter.createFromResource(this, R.array.ab_content_activities_names, R.layout.ab_navigation_dropdown_item); ab.setListNavigationCallbacks(navDropDownAdapter, this); ab.setSelectedNavigationItem(ContentActivity.PHOTOGRAPHS.getABDropDownListIndex()); // Retrieve name of lighthouse that user is viewing final Bundle extras = this.getIntent().getExtras(); final String lighthouseNameSelected = extras.getString("lighthousename"); // Lighthouse data guaranteed to exist ("Welcome" activity performs data // existence validation) final LighthouseDataParser lighthouseInformationParser = new LighthouseDataParser( this.getApplicationContext(), lighthouseNameSelected); lighthouseInformationParser.parseLighthouseData(); this.currentLighthouse = lighthouseInformationParser.getLighthouse(); /* * Complete Flickr downloading task only if a network connection exists * _and_ the cache is empty or contains information about a lighthouse * other than the "desired" one */ this.userConnectedToInternet = this.networkConnectionExists(); FlickrDownloadHandler downloadHandler = null; if (this.userConnectedToInternet) { if (!this.photoCacheExists()) { if (!PhotographsActivity.downloadingThreadStarted) { Log.d("LIGHTNAVDEBUG", "Creating dialog..."); // Display dialog informing user about download progress final ProgressDialog flickrPhotoDownloadDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); flickrPhotoDownloadDialog.setTitle("Downloading Flickr photos"); flickrPhotoDownloadDialog.setMessage("Downloading photographs from Flickr..."); flickrPhotoDownloadDialog.setCancelable(true); flickrPhotoDownloadDialog.show(); final HashSet<Photograph> flickrPhotos = new HashSet<Photograph>(); /* * Start background thread that will complete actual downloading * process */ PhotographsActivity.downloadingThreadStarted = true; downloadHandler = new FlickrDownloadHandler(this, this.currentLighthouse, flickrPhotos, flickrPhotoDownloadDialog); final FlickrPhotoDownloadThread downloadThread = new FlickrPhotoDownloadThread( this.getApplicationContext(), this.currentLighthouse, downloadHandler, PhotographsActivity.XML_DOWNLOAD_COMPLETE, PhotographsActivity.INTERRUPT); Log.d("LIGHTNAVDEBUG", "Flickr download XML thread started"); downloadThread.start(); /* * Interrupt (stop) currently-running thread if user cancels * downloading operation explicitly */ flickrPhotoDownloadDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface di) { if (downloadThread.isAlive()) { downloadThread.interrupt(); } else if (PhotographsActivity.this.parseOutputThread != null && PhotographsActivity.this.parseOutputThread.isAlive()) { PhotographsActivity.this.parseOutputThread.interrupt(); } else { // Do nothing } } }); } } else { final ArrayList<Photograph> lighthousePhotos = this.currentLighthouse.getAlbum() .get(ActivityVisible.PHOTOGRAPHS); lighthousePhotos.clear(); final File downloadCacheDir = new File(this.getFilesDir() + "/download-cache/"); final File[] downloadCacheDirContents = downloadCacheDir.listFiles(); for (int i = 0; i < downloadCacheDirContents.length; i++) { final String downloadCacheDirContentName = downloadCacheDirContents[i].getName(); final String[] downloadCacheDirContentPieces = downloadCacheDirContentName.split("_"); final Long photoID = Long.parseLong(downloadCacheDirContentPieces[2]); final String ownerName = downloadCacheDirContentPieces[3].replace("~", " "); final String creativeCommonsLicenseIDString = downloadCacheDirContentPieces[4].substring(0, 1); final int creativeCommonsLicenseID = Integer.parseInt(creativeCommonsLicenseIDString); final CreativeCommonsLicenseType licenseType = CreativeCommonsLicenseType .convertToLicenseEnum(creativeCommonsLicenseID); lighthousePhotos.add(new Photograph(photoID, ownerName, licenseType, "/download-cache/" + downloadCacheDirContentName)); } this.currentLighthouse.getAlbum().put(ActivityVisible.PHOTOGRAPHS, lighthousePhotos); } } if (!this.userConnectedToInternet || this.userConnectedToInternet && this.photoCacheExists() || downloadHandler != null && downloadHandler.getFlickrOperationsComplete()) { // Display first photograph as "selected" photograph in top-left corner // by default final ArrayList<Photograph> photoSet = this.currentLighthouse.getAlbum() .get(ActivityVisible.PHOTOGRAPHS); final Photograph currentPhotoOnLeftSide = photoSet.get(0); final ImageView currentPhotoView = (ImageView) this.findViewById(R.id.iv_photographs_current_image); if (this.userConnectedToInternet) { currentPhotoView.setImageDrawable(Drawable.createFromPath( PhotographsActivity.this.getFilesDir() + currentPhotoOnLeftSide.getInternalStorageLoc())); } else { currentPhotoView.setImageResource(currentPhotoOnLeftSide.getResID()); } // Add credits for "default" main photograph final TextView owner = (TextView) this.findViewById(R.id.tv_photographs_photographer); final TextView licenseType = (TextView) this.findViewById(R.id.tv_photographs_license); owner.setText("Uploaded by: " + currentPhotoOnLeftSide.getOwner()); licenseType.setText("License: " + currentPhotoOnLeftSide.getLicenseTypeAbbreviation()); /* * Display Google Map as a SupportMapFragment (instead of MapFragment * for compatibility with Android 2.x) */ /* * BIG thanks to http://www.truiton.com/2013/05/ * android-supportmapfragment-example/ for getting this part of the app * working */ final FragmentManager fm = this.getSupportFragmentManager(); final Fragment mapFragment = fm.findFragmentById(R.id.frag_photographs_map); final SupportMapFragment smf = (SupportMapFragment) mapFragment; smf.getMap(); final GoogleMap supportMap = smf.getMap(); /* * Center map at lighthouse location, at a zoom level of 12 with no * tilt, facing due north */ final LatLng lighthouseLocation = new LatLng(this.currentLighthouse.getCoordinates().getLatitude(), this.currentLighthouse.getCoordinates().getLongitude()); final float zoomLevel = 12.0f; final float tiltAngle = 0.0f; final float bearing = 0.0f; final CameraPosition cameraPos = new CameraPosition(lighthouseLocation, zoomLevel, tiltAngle, bearing); supportMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos)); /* * Allows user to open a maps application (such as Google Maps) upon * selecting the map fragment */ /* * Courtesy of: * http://stackoverflow.com/questions/6205827/how-to-open-standard * -google-map-application-from-my-application */ supportMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng lighthouseCoordinates) { final String uri = String.format(Locale.US, "geo:%f,%f", lighthouseCoordinates.latitude, lighthouseCoordinates.longitude); final Intent googleMapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); PhotographsActivity.this.startActivity(googleMapsIntent); } }); this.gv = (GridView) this.findViewById(R.id.gv_photographs_thumbnails); /* * Photographs in the "current lighthouse album" are from Flickr if the * album is empty or if the first (or _any_) of the elements in the * album do not have a "proper" static resource ID */ this.photosFromFlickr = this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS).isEmpty() || this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS).iterator().next() .getResID() == 0; final LighthouseImageAdapter thumbnailAdapter = new LighthouseImageAdapter(this, this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS), this.photosFromFlickr); this.gv.setAdapter(thumbnailAdapter); this.gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // Determine which photograph from the list was selected... final Photograph photoClicked = (Photograph) thumbnailAdapter.getItem(position); final int photoClickedResID = photoClicked.getResID(); // ...and change the information in the top-left corner // accordingly if (PhotographsActivity.this.userConnectedToInternet) { currentPhotoView.setImageDrawable(Drawable.createFromPath( PhotographsActivity.this.getFilesDir() + photoClicked.getInternalStorageLoc())); } else { currentPhotoView.setImageResource(photoClickedResID); } owner.setText("Uploaded by: " + photoClicked.getOwner()); licenseType.setText("License: " + photoClicked.getLicenseTypeAbbreviation()); } }); } }
From source file:com.data.pack.ViewVideo.java
public void removeDuplicates(ArrayList<String> list) { HashSet<String> set = new HashSet<String>(list); list.clear(); list.addAll(set);// w w w.j a v a 2 s . c o m }
From source file:com.microsoft.live.sample.skydrive.SkyDriveActivity.java
private void loadFolder(String folderId) { assert folderId != null; mCurrentFolderId = folderId;/* www. j a va2 s.c o m*/ final ProgressDialog progressDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true); mClient.getAsync(folderId + "/files", new LiveOperationListener() { @Override public void onComplete(LiveOperation operation) { progressDialog.dismiss(); JSONObject result = operation.getResult(); if (result.has(JsonKeys.ERROR)) { JSONObject error = result.optJSONObject(JsonKeys.ERROR); String message = error.optString(JsonKeys.MESSAGE); String code = error.optString(JsonKeys.CODE); showToast(code + ": " + message); return; } ArrayList<SkyDriveObject> skyDriveObjs = mPhotoAdapter.getSkyDriveObjs(); skyDriveObjs.clear(); JSONArray data = result.optJSONArray(JsonKeys.DATA); for (int i = 0; i < data.length(); i++) { SkyDriveObject skyDriveObj = SkyDriveObject.create(data.optJSONObject(i)); if (skyDriveObj != null) { skyDriveObjs.add(skyDriveObj); } } mPhotoAdapter.notifyDataSetChanged(); } @Override public void onError(LiveOperationException exception, LiveOperation operation) { progressDialog.dismiss(); showToast(exception.getMessage()); } }); }
From source file:gdsc.smlm.results.match.MatchCalculator.java
/** * Calculate the match results for the given actual and predicted points. * Points that are within the distance threshold are identified as a match. * The number of true positives, false positives and false negatives are calculated. * // www . j av a 2 s . com * @param actualPoints * @param predictedPoints * @param dThreshold * The distance threshold * @param TP * True Positives * @param FP * False Positives * @param FN * False Negatives * @param matches * The matched true positives (point1 = actual, point2 = predicted) * @return The match results */ public static MatchResult analyseResults2D(Coordinate[] actualPoints, Coordinate[] predictedPoints, double dThreshold, List<Coordinate> TP, List<Coordinate> FP, List<Coordinate> FN, List<PointPair> matches) { dThreshold *= dThreshold; // We will use the squared distance final int predictedPointsLength = (predictedPoints != null) ? predictedPoints.length : 0; final int actualPointsLength = (actualPoints != null) ? actualPoints.length : 0; int tp = 0; // true positives (actual with matched predicted point) int fp = predictedPointsLength; // false positives (actual with no matched predicted point) int fn = actualPointsLength; // false negatives (predicted point with no actual point) double rmsd = 0; if (predictedPointsLength == 0 || actualPointsLength == 0) { if (FP != null) FP.addAll(asList(predictedPoints)); if (FN != null) FN.addAll(asList(actualPoints)); return new MatchResult(tp, fp, fn, rmsd); } // loop over the two arrays assigning the closest unassigned pair boolean[] resultAssignment = new boolean[predictedPointsLength]; boolean[] roiAssignment = new boolean[fn]; ArrayList<Assignment> assignments = new ArrayList<Assignment>(predictedPointsLength); int[] falsePositives = null, falseNegatives = null; if (FP != null) { falsePositives = ascendingArray(predictedPointsLength); } if (FN != null) { falseNegatives = ascendingArray(actualPointsLength); } // Pre-calculate all-vs-all distance matrix if it can fit in memory int size = predictedPointsLength * actualPointsLength; float[][] dMatrix = null; if (size < 200 * 200) { dMatrix = new float[predictedPointsLength][actualPointsLength]; for (int predictedId = predictedPointsLength; predictedId-- > 0;) { final float x = predictedPoints[predictedId].getX(); final float y = predictedPoints[predictedId].getY(); for (int actualId = actualPointsLength; actualId-- > 0;) { dMatrix[predictedId][actualId] = (float) actualPoints[actualId].distance2(x, y); } } } do { assignments.clear(); // Process each result for (int predictedId = predictedPointsLength; predictedId-- > 0;) { if (resultAssignment[predictedId]) continue; // Already assigned final float x = predictedPoints[predictedId].getX(); final float y = predictedPoints[predictedId].getY(); // Find closest ROI point float d2Min = (float) dThreshold; //Float.MAX_VALUE; int targetId = -1; for (int actualId = actualPointsLength; actualId-- > 0;) { if (roiAssignment[actualId]) continue; // Already assigned if (dMatrix != null) { if (dMatrix[predictedId][actualId] <= d2Min) { d2Min = dMatrix[predictedId][actualId]; targetId = actualId; } } else { Coordinate actualPoint = actualPoints[actualId]; // Calculate in steps for increased speed (allows early exit) float dx = actualPoint.getX() - x; dx *= dx; if (dx <= d2Min) { float dy = actualPoint.getY() - y; dy *= dy; if (dy <= d2Min) { final float d2 = dx + dy; if (d2 <= d2Min) { d2Min = d2; targetId = actualId; } } } } } // Store closest ROI point if (targetId > -1) { assignments.add(new Assignment(targetId, predictedId, d2Min)); } } // If there are assignments if (!assignments.isEmpty()) { // Pick the closest pair to be assigned Collections.sort(assignments); // Process in order for (Assignment closest : assignments) { // Skip those that have already been assigned since this will be a lower score. // Note at least one assignment should be processed as potential assignments are made // using only unassigned points. if (resultAssignment[closest.getPredictedId()] || roiAssignment[closest.getTargetId()]) continue; resultAssignment[closest.getPredictedId()] = true; roiAssignment[closest.getTargetId()] = true; // If within accuracy then classify as a match if (closest.getDistance() <= dThreshold) { tp++; fn--; fp--; rmsd += closest.getDistance(); // Already a squared distance if (TP != null) { TP.add(predictedPoints[closest.getPredictedId()]); } if (FP != null) { falsePositives[closest.getPredictedId()] = -1; } if (FN != null) { falseNegatives[closest.getTargetId()] = -1; } if (matches != null) matches.add(new PointPair(actualPoints[closest.getTargetId()], predictedPoints[closest.getPredictedId()])); } else { // No more assignments within the distance threshold break; } } } } while (!assignments.isEmpty()); // Add to lists if (FP != null) { for (int i = 0; i < predictedPointsLength; i++) { if (falsePositives[i] >= 0) FP.add(predictedPoints[i]); } } if (FN != null) { for (int i = 0; i < actualPointsLength; i++) { if (falseNegatives[i] >= 0) FN.add(actualPoints[i]); } } if (tp > 0) rmsd = Math.sqrt(rmsd / tp); return new MatchResult(tp, fp, fn, rmsd); }
From source file:knowledgeMiner.mining.SentenceParserHeuristic.java
/** * Pairs the nouns and adjectives together to produce a number of result * text fragments to be resolved to concepts. * * @param parse/*from w w w. j a v a 2 s . co m*/ * The parse to process and pair. * @param anchors * The anchor map. * @param existingAnchorTrees * The anchor trees already added to the results (for reuse and * subtree-ing) * @return A collection of possible mappable entities composed of at least * one noun and possible adjectives (with sub-adjectives). */ private Collection<Tree<String>> pairNounAdjs(Parse parse, SortedMap<String, String> anchors, Map<String, Tree<String>> existingAnchorTrees) { Collection<Tree<String>> results = new ArrayList<>(); boolean createNewNounSet = false; ArrayList<String> nounPhrases = new ArrayList<>(); Parse[] children = parse.getChildren(); for (int i = children.length - 1; i >= 0; i--) { String childType = children[i].getType(); String childText = children[i].getCoveredText(); if (childType.startsWith("NN") || childType.equals("NP")) { // Note the noun, adding it to the front of the existing NP. if (createNewNounSet) nounPhrases.clear(); String existingNounPhrase = ""; if (!nounPhrases.isEmpty()) existingNounPhrase = nounPhrases.get(nounPhrases.size() - 1); String np = (childText + " " + existingNounPhrase).trim(); nounPhrases.add(np); // Add to the tree (if not a pure anchor) if (!anchors.containsKey(np)) results.add(new Tree<String>(reAnchorString(np, anchors))); } else if (childType.startsWith("JJ") || childType.equals("ADJP")) { // Only process if we have an NP if (!nounPhrases.isEmpty()) { // For every nounPhrase StringBuilder adjective = new StringBuilder(); for (int j = i; children[j].getType().startsWith("JJ") || children[j].getType().equals("ADJP"); j++) { // Build adjective combinations if (adjective.length() != 0) adjective.append(" "); adjective.append(children[j].getCoveredText()); for (String np : nounPhrases) { // Create the tree (with sub adjective tree) String adjNP = adjective + " " + np; Tree<String> adjP = null; // Check for an existing anchor tree if (existingAnchorTrees.containsKey(adjNP)) adjP = existingAnchorTrees.get(adjNP); else adjP = new Tree<String>(reAnchorString(adjNP, anchors)); if (!anchors.containsKey(adjective.toString())) adjP.addSubValue(reAnchorString(adjective.toString(), anchors)); // Add to the tree results.add(adjP); } } } createNewNounSet = true; } else { createNewNounSet = true; } } return results; }
From source file:org.apache.hadoop.hbase.ChoreService.java
private void cancelAllChores(final boolean mayInterruptIfRunning) { ArrayList<ScheduledChore> choresToCancel = new ArrayList<ScheduledChore>(); // Build list of chores to cancel so we can iterate through a set that won't change // as chores are cancelled. If we tried to cancel each chore while iterating through // keySet the results would be undefined because the keySet would be changing for (ScheduledChore chore : scheduledChores.keySet()) { choresToCancel.add(chore);// www .j av a2 s .c o m } for (ScheduledChore chore : choresToCancel) { cancelChore(chore, mayInterruptIfRunning); } choresToCancel.clear(); }
From source file:com.joshlong.activiti.coordinator.CoordinatorGatewayClient.java
public Message<?> processMessage(Message<?> message) throws MessagingException { try {// w w w . ja va 2 s .co m MessageHeaders headers = message.getHeaders(); String procName = (String) headers.get(CoordinatorConstants.PROCESS_NAME); String stateName = (String) headers.get(CoordinatorConstants.STATE_NAME); ActivitiStateHandlerRegistration registration = registry.findRegistrationForProcessAndState(procName, stateName); Object bean = applicationContext.getBean(registration.getBeanName()); Method method = registration.getHandlerMethod(); // int size = method.getParameterTypes().length; ArrayList<Object> argsList = new ArrayList<Object>(); Map<Integer, String> processVariablesMap = registration.getProcessVariablesExpected(); // already has which indexes get which process variables Map<Integer, Object> variables = new HashMap<Integer, Object>(); for (Integer i : processVariablesMap.keySet()) variables.put(i, headers.get(processVariablesMap.get(i))); if (registration.requiresProcessId()) { variables.put(registration.getProcessIdIndex(), headers.get(CoordinatorConstants.PROC_ID)); } // System.out.println(variables.toString()); List<Integer> indices = new ArrayList<Integer>(variables.keySet()); Collections.sort(indices); argsList.clear(); for (Integer idx : indices) argsList.add(variables.get(idx)); Object[] args = argsList.toArray(new Object[argsList.size()]); Object result = (args.length == 0) ? method.invoke(bean) : method.invoke(bean, args); MessageBuilder builder = MessageBuilder.withPayload(message.getPayload()) .copyHeaders(message.getHeaders()); if (result instanceof Map) { // then we update the BPM // by including them in the reply message builder.copyHeadersIfAbsent((Map) result); } return builder.build(); } catch (Throwable e) { throw new RuntimeException(e); } }
From source file:org.mousephenotype.dcc.exportlibrary.exportworker.ExportWorker.java
private void processSpecimens(EntityManager rawEM, CentreContainer downloadInstructions) { XMLGenerator g = new XMLGenerator(); TypedQuery<Mouse> mouseQuery = rawEM.createQuery("Select s from Mouse s where s.hjid=:hjid", Mouse.class); TypedQuery<Embryo> embryoQuery = rawEM.createQuery("Select s from Embryo s where s.hjid=:hjid", Embryo.class); CentreSpecimenSet css = new CentreSpecimenSet(); CentreSpecimen cs = new CentreSpecimen(); cs.setCentreID(downloadInstructions.getCentreILAR()); // This is just faff ArrayList<CentreSpecimen> csl = new ArrayList<CentreSpecimen>(); csl.add(cs);//from ww w .j a v a 2s . c o m css.setCentre(csl); int count = 1; int filecount = 1; ArrayList<Specimen> specimenList = new ArrayList<Specimen>(); logger.info("There are {} specimens", downloadInstructions.getSpecimenReference().size()); for (SpecimenReference sp : downloadInstructions.getSpecimenReference()) { if (count % MAX_OBJECTS == 0 || count == downloadInstructions.getDataReference().size()) { cs.setMouseOrEmbryo(specimenList); writeSpecimenSet(css, cs, g, filecount, downloadInstructions); filecount++; cs.unsetMouseOrEmbryo(); // empty list specimenList.clear(); } if (sp.isIsMouse()) { Mouse s = mouseQuery.setParameter("hjid", sp.getSpecimenID()).getSingleResult(); specimenList.add(s); } else { Embryo s = embryoQuery.setParameter("hjid", sp.getSpecimenID()).getSingleResult(); specimenList.add(s); } count++; } // Write the remaining specimen to file. logger.info("There are {} specimens exported", count); cs.setMouseOrEmbryo(specimenList); writeSpecimenSet(css, cs, g, filecount, downloadInstructions); }
From source file:com.spoiledmilk.ibikecph.util.DB.java
public ArrayList<FavoritesData> getFavorites(ArrayList<FavoritesData> ret) { if (ret == null) { ret = new ArrayList<FavoritesData>(); } else {/*www. j a v a 2 s .c om*/ ret.clear(); } SQLiteDatabase db = getReadableDatabase(); if (db == null) { return null; } String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_SOURCE, KEY_SUBSOURCE, KEY_LAT, KEY_LONG, KEY_API_ID }; Cursor cursor = db.query(TABLE_FAVORITES, columns, null, null, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { while (cursor != null && !cursor.isAfterLast()) { int colId = cursor.getColumnIndex(KEY_ID); int colName = cursor.getColumnIndex(KEY_NAME); int colAddress = cursor.getColumnIndex(KEY_ADDRESS); int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE); int colLat = cursor.getColumnIndex(KEY_LAT); int colLong = cursor.getColumnIndex(KEY_LONG); int colApiId = cursor.getColumnIndex(KEY_API_ID); FavoritesData fd = new FavoritesData(cursor.getInt(colId), cursor.getString(colName), cursor.getString(colAddress), cursor.getString(colSubSource), cursor.getDouble(colLat), cursor.getDouble(colLong), cursor.getInt(colApiId)); ret.add(fd); cursor.moveToNext(); } } if (cursor != null) { cursor.close(); } db.close(); LOG.d("favourites count from DB = " + ret.size()); return ret; }
From source file:com.spoiledmilk.ibikecph.util.DB.java
public ArrayList<FavoritesData> getFavoritesFromServer(Context context, ArrayList<FavoritesData> ret) { if (ret == null) { ret = new ArrayList<FavoritesData>(); } else {//from ww w. j a v a 2 s.c om ret.clear(); } if (IbikeApplication.isUserLogedIn()) { String authToken = IbikeApplication.getAuthToken(); try { JsonNode getObject = HttpUtils .getFromServer(Config.serverUrl + "/favourites?auth_token=" + authToken); if (getObject != null && getObject.has("data")) { SQLiteDatabase db = this.getWritableDatabase(); if (db != null) { db.delete(TABLE_FAVORITES, null, null); } IbikeApplication.setFavoritesFetched(true); JsonNode favoritesList = getObject.get("data"); for (int i = 0; i < favoritesList.size(); i++) { JsonNode data = favoritesList.get(i); FavoritesData fd = new FavoritesData(data.get("name").asText(), data.get("address").asText(), data.get("sub_source").asText(), data.get("lattitude").asDouble(), data.get("longitude").asDouble(), data.get("id").asInt()); saveFavorite(fd, null, false); // ret.add(fd); } LOG.d("favorites fetched = " + ret); } } catch (Exception e) { if (e != null && e.getLocalizedMessage() != null) { LOG.e(e.getLocalizedMessage()); } } } getFavorites(ret); return ret; }