@Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_CANCEL_DOWNLOAD)) { String url = intent.getStringExtra(EXTRA_DOWNLOAD_URL); if (url == null) { throw new IllegalArgumentException( "ACTION_CANCEL_DOWNLOAD intent needs download url extra"); } if (AppConfig.DEBUG) Log.d(TAG, "Cancelling download with url " + url); Downloader d = getDownloader(url); if (d != null) { d.cancel(); } else { Log.e(TAG, "Could not cancel download with url " + url); } } else if (intent.getAction().equals(ACTION_CANCEL_ALL_DOWNLOADS)) { for (Downloader d : downloads) { d.cancel(); if (AppConfig.DEBUG) Log.d(TAG, "Cancelled all downloads"); } sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED)); } queryDownloads(); }
/** * デバイスの利用開始。 * * @return null=正常、null以外=エラーメッセージ */ public String onStart(UsbDevice device) { Log.d(TAG, "onStart:" + device); if (!device.equals(usbDevice)) { return "No device attach."; } if (!usbManager.hasPermission(usbDevice)) { return "No device permission."; } usbConnection = usbManager.openDevice(usbDevice); // TODO:インターフェースの検出は端折ってます。 UsbInterface usbIf = usbDevice.getInterface(INTERFACE_INDEX); // EndPointの検索。分かってる場合は直接取り出しても良い。 for (int i = 0; i < usbIf.getEndpointCount(); i++) { UsbEndpoint ep = usbIf.getEndpoint(i); Log.d(TAG, "tye=" + ep.getType()); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) { if (ep.getDirection() == UsbConstants.USB_DIR_IN) { endpointIn = ep; } else if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { endpointOut = ep; } } } if (endpointIn == null || endpointOut == null) { Log.e(TAG, "Device has not IN/OUT Endpoint."); return "Device has not IN/OUT Endpoint."; } // デバイスの確保 usbConnection.claimInterface(usbIf, true); isReady = true; return null; }
@Override public void onReceive(Context context, Intent intent) { Log.d(this.getClass().toString(), "alarm received"); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(context, HourlyreminderActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( context, REQUESTCODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder builder = new Notification.Builder(context); builder .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.alarm_icon) .setTicker(context.getString(R.string.notification_status_bar_text)) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setContentTitle(context.getString(R.string.notification_title)) .setContentText(context.getString(R.string.notification_message)); Notification notification = builder.getNotification(); // TODO: text updaten bij meerdere notificationManager.notify(1, notification); Log.d(this.getClass().toString(), "notification send"); }
private void decodeAudioSample() { int output = mAudioCodec.dequeueOutputBuffer(mAudioInfo, mTimeOutUs); if (output >= 0) { // http://bigflake.com/mediacodec/#q11 ByteBuffer outputData = mAudioCodecOutputBuffers[output]; if (mAudioInfo.size != 0) { outputData.position(mAudioInfo.offset); outputData.limit(mAudioInfo.offset + mAudioInfo.size); // Log.d(TAG, "raw audio data bytes: " + mVideoInfo.size); } mAudioPlayback.write(outputData, mAudioInfo.presentationTimeUs); mAudioCodec.releaseOutputBuffer(output, false); if ((mAudioInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { mAudioOutputEos = true; Log.d(TAG, "EOS audio output"); } } else if (output == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { Log.d(TAG, "audio output buffers have changed."); mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers(); } else if (output == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat format = mAudioCodec.getOutputFormat(); Log.d(TAG, "audio output format has changed to " + format); mAudioPlayback.init(format); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case FILE_SELECT_CODE: if (resultCode == Activity.RESULT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); Log.d(LOG_TAG, "File Uri: " + uri.toString()); try { filePath = FileUtils.getPath(getActivity(), uri); fileChoosen = new File(filePath); if (fileChoosen != null) { tv_choose_file.setText(fileChoosen.getName()); } else { break; } bt_upload.setEnabled(true); } catch (URISyntaxException e) { Log.d(LOG_TAG, e.getLocalizedMessage()); } } break; } super.onActivityResult(requestCode, resultCode, data); }
private void copyWaveFile(String inFilename, String outFilename) { FileInputStream in = null; FileOutputStream out = null; long totalAudioLen = 0; long totalDataLen = totalAudioLen + 36; long longSampleRate = RECORDER_SAMPLERATE; int channels = 2; long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8; byte[] data = new byte[bufferSize]; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); totalAudioLen = in.getChannel().size(); totalDataLen = totalAudioLen + 36; // AppLog.logString("File size: " + totalDataLen); WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate); while (in.read(data) != -1) { out.write(data); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.d("SAN", e.getMessage()); } catch (IOException e) { Log.d("SAN", e.getMessage()); } }
public synchronized int fetchStatusUpdates() { Log.d(TAG, "Fetching status updates"); Twitter twitter = this.getTwitter(); if (twitter == null) { Log.d(TAG, "Twitter connection info not initialized"); return 0; } try { List<Status> statusUpdates = twitter.getFriendsTimeline(); long latestStatusCreatedAtTime = this.getStatusData().getLatestStatusCreatedAtTime(); int count = 0; ContentValues contentValues = new ContentValues(); for (Status status : statusUpdates) { contentValues.put(StatusData.C_ID, status.getId()); long createdAt = status.getCreatedAt().getTime(); contentValues.put(StatusData.C_CREATED_AT, createdAt); contentValues.put(StatusData.C_TEXT, status.getText()); contentValues.put(StatusData.C_USER, status.getUser().getName()); Log.d(TAG, "Got update with id " + status.getId() + ". Saving"); this.getStatusData().insertOrIgnore(contentValues); if (latestStatusCreatedAtTime < createdAt) { count++; } } Log.d(TAG, count > 0 ? "Got" + count + " status updates" : "No new staus updates"); return count; } catch (RuntimeException e) { Log.e(TAG, "Failed to fetch status updates", e); return 0; } }
@Override public Fragment getItem(int position) { switch (position) { case 0: if (getSource() == SOURCE_YELP) { Log.d("InvitePagerAdapter", "Source is YELP"); return currentPlace == null ? new PickYelpPlaceInviteFragment() : PickYelpPlaceInviteFragment.newInstance(currentPlace); } else if (getSource() == SOURCE_GOOGLE) { Log.d("InvitePagerAdapter", "Source is GOOGLE"); return currentPlace == null ? new PickGooglePlaceInviteFragment() : PickGooglePlaceInviteFragment.newInstance(currentPlace); } case 1: return new FriendsInviteFragment(); case 2: return new DetailsInviteFragment(); case 3: return isUpdateMode ? new UpdateInviteFragment() : new SendInviteFragment(); default: return null; } }
/** * Edits a video file, saving the contents to a new file. This involves decoding and re-encoding, * not to mention conversions between YUV and RGB, and so may be lossy. * * <p>If we recognize the decoded format we can do this in Java code using the ByteBuffer[] * output, but it's not practical to support all OEM formats. By using a SurfaceTexture for output * and a Surface for input, we can avoid issues with obscure formats and can use a fragment shader * to do transformations. */ private VideoChunks editVideoFile(VideoChunks inputData) { if (VERBOSE) Log.d(TAG, "editVideoFile " + mWidth + "x" + mHeight); VideoChunks outputData = new VideoChunks(); MediaCodec decoder = null; MediaCodec encoder = null; InputSurface inputSurface = null; OutputSurface outputSurface = null; try { MediaFormat inputFormat = inputData.getMediaFormat(); // Create an encoder format that matches the input format. (Might be able to just // re-use the format used to generate the video, since we want it to be the same.) MediaFormat outputFormat = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight); outputFormat.setInteger( MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); outputFormat.setInteger( MediaFormat.KEY_BIT_RATE, inputFormat.getInteger(MediaFormat.KEY_BIT_RATE)); outputFormat.setInteger( MediaFormat.KEY_FRAME_RATE, inputFormat.getInteger(MediaFormat.KEY_FRAME_RATE)); outputFormat.setInteger( MediaFormat.KEY_I_FRAME_INTERVAL, inputFormat.getInteger(MediaFormat.KEY_I_FRAME_INTERVAL)); outputData.setMediaFormat(outputFormat); encoder = MediaCodec.createEncoderByType(MIME_TYPE); encoder.configure(outputFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); inputSurface = new InputSurface(encoder.createInputSurface()); inputSurface.makeCurrent(); encoder.start(); // OutputSurface uses the EGL context created by InputSurface. decoder = MediaCodec.createDecoderByType(MIME_TYPE); outputSurface = new OutputSurface(); outputSurface.changeFragmentShader(FRAGMENT_SHADER); decoder.configure(inputFormat, outputSurface.getSurface(), null, 0); decoder.start(); editVideoData(inputData, decoder, outputSurface, inputSurface, encoder, outputData); } finally { if (VERBOSE) Log.d(TAG, "shutting down encoder, decoder"); if (outputSurface != null) { outputSurface.release(); } if (inputSurface != null) { inputSurface.release(); } if (encoder != null) { encoder.stop(); encoder.release(); } if (decoder != null) { decoder.stop(); decoder.release(); } } return outputData; }
@Override public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] android.view.Menu: " + menu); if (mActionMode != null) { return false; } mMenuIsPrepared = false; if (!preparePanel()) { return false; } if (isReservingOverflow()) { return false; } if (mNativeItemMap == null) { mNativeItemMap = new HashMap<android.view.MenuItem, MenuItemImpl>(); } else { mNativeItemMap.clear(); } if (mMenu == null) { return false; } boolean result = mMenu.bindNativeOverflow(menu, this, mNativeItemMap); if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); return result; }
/* (non-Javadoc) * @see uk.ac.swan.digitaltrails.fragments.SearchListFragment.OnWalkSelectedListener#onWalkSelected(uk.ac.swan.digitaltrails.components.Walk) */ @Override public void onWalkSelected(Walk walk) { Log.d(TAG, "Trying to choose a walk"); SearchDetailsFragment detailsFrag = (SearchDetailsFragment) getSupportFragmentManager().findFragmentById(R.id.search_details_fragment); mWalk = walk; if (detailsFrag != null) { Log.d(TAG, "In 2 pane view"); // if available and we are in 2-pane view. detailsFrag.updateDetailsView(walk); } else { Log.d(TAG, "In 1 pane view"); // if in 1 pane view SearchDetailsFragment newDetailsFragment = new SearchDetailsFragment(); Bundle args = new Bundle(); args.putParcelable(SearchDetailsFragment.ARG_POSITION, walk); newDetailsFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, newDetailsFragment); transaction.addToBackStack(null); transaction.commit(); } }
// [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); String extra = data.getString("extra"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { // normal downstream message. } // [START_EXCLUDE] /** * Production applications would usually process the message here. Eg: - Syncing with server. - * Store message in local database. - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user that a message * was received. */ sendNotification(message, extra); // [END_EXCLUDE] }
@Override protected void onPostExecute(String response) { super.onPostExecute(response); Log.d(TAG, "Response : " + response); if (response != null) { try { JSONObject jsonObject = new JSONObject(response); boolean isSuccess = jsonObject.getBoolean(Keys.KEY_SUCCESS); if (isSuccess) { Log.d(TAG, "Profile information Updated"); Snackbar.make(profileImgView, "Profile information Updated", Snackbar.LENGTH_LONG) .setAction("Action", null) .show(); } else { Snackbar.make(profileImgView, "Profile information not Updated", Snackbar.LENGTH_LONG) .setAction("Action", null) .show(); Log.d(TAG, "Profile information not Updated"); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.d(TAG, "Update response is NULL"); } }
/** * Create and returns the Bitmap image from local storage optimized by size * * @param imageID - filename of the image * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image * can't be loaded used in ArticleViewAdapter.getView() */ public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) { Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize); Bitmap result = null; // construct full file name String fileName = imageID + JPEG_SUFFIX; File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName); // if image file exists trying to load, optimize and decode if (imageFile.exists()) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); // Calculate inSampleSize bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize); // Decode bitmap with inSampleSize set from file with given options bmOptions.inJustDecodeBounds = false; bmOptions.inPurgeable = true; result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); } // if can't be loaded and decoded, load default image from local storage instead if (result == null) { Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath()); File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME); result = BitmapFactory.decodeFile(file.getAbsolutePath()); } return result; }
private void performDecode(DecodeTask currentDecodeTask) throws IOException { if (isTaskDead(currentDecodeTask)) { Log.d(DECODE_SERVICE, "Skipping decode task for page " + currentDecodeTask.pageNumber); return; } Log.d(DECODE_SERVICE, "Starting decode of page: " + currentDecodeTask.pageNumber); CodecPage vuPage = getPage(currentDecodeTask.pageNumber); preloadNextPage(currentDecodeTask.pageNumber); if (isTaskDead(currentDecodeTask)) { return; } Log.d(DECODE_SERVICE, "Start converting map to bitmap"); float scale = calculateScale(vuPage) * currentDecodeTask.zoom; final Bitmap bitmap = vuPage.renderBitmap( getScaledWidth(currentDecodeTask, vuPage, scale), getScaledHeight(currentDecodeTask, vuPage, scale), currentDecodeTask.pageSliceBounds); Log.d(DECODE_SERVICE, "Converting map to bitmap finished"); if (isTaskDead(currentDecodeTask)) { bitmap.recycle(); return; } finishDecoding(currentDecodeTask, bitmap); }
@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_stories_view, container, false); getActivity().setTitle(getResources().getString(R.string.title_activity_news_home_screen)); swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout); swipeLayout.setOnRefreshListener(this); TextView noTopicsText = (TextView) rootView.findViewById(R.id.no_topics_textview); user = ValuesAndUtil.getInstance().loadUserData(getActivity().getApplicationContext()); boolean hasTopics = false; try { hasTopics = user.has("topics") && user.getJSONArray("topics").length() > 0; } catch (JSONException e) { e.printStackTrace(); } Log.d("SVF", "Has topics = " + hasTopics); if (!hasTopics) { noTopicsText.setText(getString(R.string.no_topics_available)); swipeLayout.setVisibility(View.INVISIBLE); } else { Log.d("SVF", "Topics were not null"); swipeLayout.setVisibility(View.VISIBLE); try { topics = user.getJSONArray("topics"); setUpList(rootView, topics); } catch (JSONException e) { e.printStackTrace(); } } return rootView; }
@Override protected void onResume() { Log.d("", "resume activity tab"); if (AppMain.isphone) { if (AppMain.isGotoshelf) { Log.d("", "Go to shelf"); if (AppMain.isphone) { mTabHost.setCurrentTabByTag("Tab5"); AppMain.isGotoshelf = false; } else { mTabHost.setCurrentTabByTag("Tab5"); AppMain.isGotoshelf = false; } } } else { if (AppMain.isGotoshelf) { Log.d("", "Go to shelf"); if (AppMain.isphone) { mTabHost.setCurrentTabByTag("Tab4"); AppMain.isGotoshelf = false; } else { mTabHost.setCurrentTabByTag("Tab4"); AppMain.isGotoshelf = false; } } } super.onResume(); }
@Override public void onChange(boolean selfChange) { Log.d("C3PO", "Received settings change!"); super.onChange(selfChange); Log.d("C3PO", "Settings change detected"); int vol = audioManager.getStreamVolume(AudioManager.STREAM_RING); int max_vol = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING); if (vol == oldVolume) { return; } oldVolume = vol; SimplMessageAndroid msg_out = new SimplMessageAndroid(); try { msg_out.addParam(Param.MSGID, -1); msg_out.addParam(Param.CURRENT_VOLUME, vol); msg_out.addParam(Param.MAX_VOLUME, max_vol); } catch (JSONException e) { e.printStackTrace(); } try { Socket s = new Socket( context.getString(R.string.comm_relay_ip), Integer.parseInt(context.getString(R.string.comm_relay_outbound))); SecureChannel channel = new SecureChannelAndroid(new RSAUtilImpl(context)); channel.serialize(msg_out, s); Log.d("C3PO", "Sent notification of change"); } catch (Exception e) { e.printStackTrace(); } }
@Override public Void doInBackground(String... params) { HttpsURLConnection connection = null; try { URL url = new URL(SEARCH_URL + params[0]); Log.d("****URL:", url.toString()); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Host", "api.twitter.com"); connection.setRequestProperty("User-Agent", "JustDoIt"); connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN); connection.setUseCaches(false); JSONObject obj = new JSONObject(ReadResponse.readResponse(connection)); buildTweets(obj); Log.d("***GetTweets:", obj.toString()); } catch (MalformedURLException e) { Log.e("***GetTweets", "Invalid endpoint URL specified.", e); } catch (IOException e) { Log.e("***GetTweets", "IOException: ", e); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } lock.release(); } return null; }
public void onComplete(Bundle values) { // Handle a successful login String token = this.fba.facebook.getAccessToken(); long token_expires = this.fba.facebook.getAccessExpires(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.fba.ctx); prefs.edit().putLong("access_expires", token_expires).commit(); prefs.edit().putString("access_token", token).commit(); Log.d("FB", "authorized"); Log.d("PhoneGapLog", values.toString()); try { JSONObject o = new JSONObject(this.fba.facebook.request("/me")); this.fba.userId = o.getString("id"); this.fba.success(getResponse(), this.fba.callbackId); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override protected String doInBackground(String... urls) { Log.d("DEBUG", "Inside dwp"); String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; Log.d("DEBUG", s); } } catch (Exception e) { e.printStackTrace(); Log.d("DEBUG", "Exception"); } } Log.d("DEBUG", "Done dwp"); return response; }
// Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as a InputStream, which it returns as // a string. private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); Log.d(TAG, "The string is: " + contentAsString); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } catch (Exception e) { Log.d(TAG, "Something happened" + e.getMessage()); } finally { if (is != null) { is.close(); } } return null; }
private void writeAudioDataToFile() { byte data[] = new byte[bufferSize]; String filename = getTempFilename(); FileOutputStream os = null; try { os = new FileOutputStream(filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.d("SAN", e.getMessage()); } int read = 0; if (null != os) { while (isRecording) { read = recorder.read(data, 0, bufferSize); if (AudioRecord.ERROR_INVALID_OPERATION != read) { try { os.write(data); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } } try { os.close(); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } }
public String p2pGetDeviceAddress() { Log.d(TAG, "p2pGetDeviceAddress"); String status = null; /* Explicitly calling the API without IFNAME= prefix to take care of the devices that don't have p2p0 interface. Supplicant seems to be returning the correct address anyway. */ synchronized (mLock) { status = doStringCommandNative("STATUS"); } String result = ""; if (status != null) { String[] tokens = status.split("\n"); for (String token : tokens) { if (token.startsWith("p2p_device_address=")) { String[] nameValue = token.split("="); if (nameValue.length != 2) break; result = nameValue[1]; } } } Log.d(TAG, "p2pGetDeviceAddress returning " + result); return result; }
public void stop() { Log.d("MandelbrotView", "stoping..."); if (fractalRequest != null) { fractalRequest.cancel(); } Log.d("MandelbrotView", "stoped..."); }
/** * Manipulates the map once available. This callback is triggered when the map is ready to be * used. This is where we can add markers or lines, add listeners or move the camera. In this * case, we just add a marker near Sydney, Australia. If Google Play services is not installed on * the device, the user will be prompted to install it inside the SupportMapFragment. This method * will only be triggered once the user has installed Google Play services and returned to the * app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mClusterManager = new ClusterManager<>(this, mMap); mClusterManager.setRenderer(new CaseRenderer()); mClusterManager.setOnClusterClickListener(this); mClusterManager.setOnClusterItemInfoWindowClickListener(this); // mClusterManager.getClusterMarkerCollection().setOnInfoWindowAdapter(new // MyCustomAdapterForClusters()); // mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager()); mMap.setOnCameraChangeListener(mClusterManager); mMap.setOnMarkerClickListener(mClusterManager); mMap.setOnInfoWindowClickListener(mClusterManager); mMap.setOnCameraChangeListener(mClusterManager); try { cases = readMapData(); Log.d("Heath", "cases size:" + cases.size()); float average_unit_price = getAverageUnitPrice(cases); average_unit_price_90p = average_unit_price * 0.9f; average_unit_price_110p = average_unit_price * 1.1f; } catch (JSONException e) { e.printStackTrace(); } Log.d("CAC", "cases count:" + cases.size()); mClusterManager.addItems(cases); LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Case _case : cases) { builder.include(_case.getPosition()); } LatLngBounds bounds = builder.build(); mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 480, 800, 50)); }
private List<Article> loadNewsFromFile(Context context) { startedLoadingNews = true; List<Article> articles = new ArrayList<>(); if (newsFile == null) newsFile = new File(context.getFilesDir(), NEWS_FILE_NAME); if (newsFile.exists()) { try { BufferedReader reader = new BufferedReader(new FileReader(newsFile)); String currentLine = reader.readLine(); if (currentLine != null) { String[] split = currentLine.split("-"); if (split.length > 1) { for (int i = 0; i < Integer.parseInt(split[1]); i++) { // TODO figure out why all lines, after i = 18, are null. currentLine = reader.readLine(); Article a = readArticle(reader); articles.add(a); Log.d("q32", "" + i + "line: " + currentLine); } } else { updateNews(context); } // if we didn't find the number of articles, the file must be corrupt. Update the file. } else updateNews(context); } catch (IOException e) { Log.d("Unit5Calendar", e.getMessage(), e); } Collections.sort(newsArticles, Utils.articlePubDateSorter); newsReady = true; } return articles; }
public void addNewArticleToUser(String data, int articleId) { Log.d("SVF", "Modifying topic " + articleId); try { JSONObject article = new JSONObject(data); boolean found = article.getBoolean("found"); if (found) { // update topic with new article; don't do anything if not found if (!ValuesAndUtil.getInstance().articleAlreadyExists(article, topics, articleId)) { article.remove("found"); article.put("thumbsUp", false); article.put("thumbsDown", false); JSONObject topic = topics.getJSONObject(articleId); JSONArray timeline = topic.getJSONArray("timeline"); timeline = ValuesAndUtil.getInstance().addToExistingJSON(timeline, 0, article); topic.put("timeline", timeline); topic.put("lastTimeStamp", article.getLong("date")); topic.put("lastSignature", article.getString("signature")); topic.put("lastUpdated", System.currentTimeMillis()); Log.d("SVF", topic.toString(2)); topics.put(articleId, topic); user.put("topics", topics); ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext()); mAdapter.notifyItemChanged(articleId); numUpdated++; } } } catch (JSONException e) { e.printStackTrace(); } }
public void doAfterPostSuccess(String s, int articleId) { if (s.equals("IOException")) { Toast.makeText( getActivity().getApplicationContext(), "Server not available, please contact application owner", Toast.LENGTH_SHORT) .show(); mAdapter.notifyDataSetChanged(); swipeLayout.setRefreshing(false); return; } addNewArticleToUser(s, articleId); done++; Log.d("SVF", "Done " + done + " out of " + topics.length()); if (done == topics.length()) { swipeLayout.setRefreshing(false); ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext()); try { JSONArray sortedTopics = ValuesAndUtil.getInstance().sortTopicsArray(user.getJSONArray("topics")); user.put("topics", sortedTopics); ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext()); mAdapter = new StoriesViewAdapter(sortedTopics); if (numUpdated == 0) { Toast.makeText(getActivity(), "No updates found for any stories", Toast.LENGTH_SHORT) .show(); } } catch (JSONException e) { e.printStackTrace(); } mRecyclerView.setAdapter(mAdapter); Log.d("SVF", "Finished updating all articles"); } }
public void apply(View v) { // read raw values from the input widgets master_switch = switch_master_switch.isChecked(); left_margin = Integer.parseInt(ET_left_margin.getText().toString()); right_margin = Integer.parseInt(ET_right_margin.getText().toString()); top_margin = Integer.parseInt(ET_top_margin.getText().toString()); bottom_margin = Integer.parseInt(ET_bottom_margin.getText().toString()); // save the values Editor editor = pref.edit(); editor.putBoolean(Keys.MASTER_SWITCH, master_switch); editor.putInt(Keys.LEFT_MARGIN, left_margin); editor.putInt(Keys.RIGHT_MARGIN, right_margin); editor.putInt(Keys.TOP_MARGIN, top_margin); editor.putInt(Keys.BOTTOM_MARGIN, bottom_margin); editor.apply(); int viewH = (screen_height - top_margin - bottom_margin); Log.d("VIEW H", Integer.toString(viewH)); int viewW = screen_width - left_margin - right_margin; Log.d("VIEW W", Integer.toString(viewW)); Toast.makeText(this, "Changes applied!", Toast.LENGTH_SHORT).show(); if (viewW < screen_width * 0.5 || viewH < screen_height * 0.5) Toast.makeText(this, "Warning, the view area may be too small!", Toast.LENGTH_LONG).show(); if (left_margin > screen_width || top_margin > screen_height || right_margin < 0 || bottom_margin < 0) Toast.makeText(this, "Your view area goes off the screen!", Toast.LENGTH_LONG).show(); finish(); }