List of usage examples for android.graphics Bitmap createScaledBitmap
public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter)
From source file:com.example.product.GcmIntentService.java
private void sendNotification(Bundle extras) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); //largeicon ?? ? Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.mylogo_whitebackground); Resources res = getResources(); int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height); int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width); largeIcon = Bitmap.createScaledBitmap(largeIcon, width, height, false); //? ?? ? /*from www . jav a 2s . c o m*/ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.mylogo_whitebackground).setLargeIcon(largeIcon) .setTicker(extras.getString("stock_name") + " - " + extras.getString("signal_name")) .setContentTitle(extras.getString("stock_name")) //.setStyle(new NotificationCompat.BigTextStyle() // BigTextStyle? . //.bigText(msg)) //.setWhen() //? ? ?? ?. // ? ? ? ? 5? ?. .setNumber(5).setDefaults(Notification.DEFAULT_VIBRATE).setAutoCancel(true) .setContentText(extras.getString("signal_name")); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); }
From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java
protected void extractCover(File f, Format format, String publicationID) { String destinationName = publicationID + "." + format.getName() + ".png"; String entryName = format.getMetadatum("internalPathCover"); if ((entryName == null) || (entryName.equals(""))) { format.addMetadatum("relativePathThumbnail", ""); return;/*from w ww . j a v a2 s . c o m*/ } try { ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ); ZipEntry entry = zipFile.getEntry(entryName); File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName); String destinationPath = destFile.getAbsolutePath(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int numberOfBytesRead; byte data[] = new byte[BUFFER_SIZE]; FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) { dest.write(data, 0, numberOfBytesRead); } dest.flush(); dest.close(); is.close(); fos.close(); // create thumbnail FileInputStream fis = new FileInputStream(destinationPath); Bitmap imageBitmap = BitmapFactory.decodeStream(fis); imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] imageData = baos.toByteArray(); // write thumbnail to file File destFile2 = new File(this.thumbnailDirectoryPath, destinationName); String destinationPath2 = destFile2.getAbsolutePath(); FileOutputStream fos2 = new FileOutputStream(destFile2); fos2.write(imageData, 0, imageData.length); fos2.flush(); fos2.close(); baos.close(); // close ZIP zipFile.close(); // delete original cover destFile.delete(); // set relativePathThumbnail format.addMetadatum("relativePathThumbnail", destinationName); } catch (Exception e) { // nop } }
From source file:de.uulm.graphicalpasswords.openmiba.MIBALoginActivity.java
private void setViews() { tableLayout = (TableLayout) findViewById(R.id.tableLayout); btnBack = (Button) findViewById(R.id.miba_btnBack); btnBack.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { back();/* w w w . j av a2 s . com*/ } }); tvRound = (TextView) this.findViewById(R.id.tvRound); tvRound.setText(getString(R.string.label_round) + " 1"); linlGrid = new LinearLayout[2][4]; linlGrid[0][0] = (LinearLayout) this.findViewById(R.id.square1); linlGrid[1][0] = (LinearLayout) this.findViewById(R.id.square2); linlGrid[0][1] = (LinearLayout) this.findViewById(R.id.square3); linlGrid[1][1] = (LinearLayout) this.findViewById(R.id.square4); linlGrid[0][2] = (LinearLayout) this.findViewById(R.id.square5); linlGrid[1][2] = (LinearLayout) this.findViewById(R.id.square6); linlGrid[0][3] = (LinearLayout) this.findViewById(R.id.square7); linlGrid[1][3] = (LinearLayout) this.findViewById(R.id.square8); for (int y = 0; y < 4; y++) { for (int x = 0; x < 2; x++) { linlGrid[x][y].setBackgroundColor(colors_off[x][y]); } } // get width and height from mainpanel // can not use display width/height because of notification bar ViewTreeObserver vto = tableLayout.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // get values of portrait mode Display display = getWindowManager().getDefaultDisplay(); if (display.getRotation() == Surface.ROTATION_0) { width = tableLayout.getWidth(); height = tableLayout.getHeight(); } else { height = tableLayout.getWidth(); width = tableLayout.getHeight(); } Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ccp000); bmp = Bitmap.createScaledBitmap(bmp, width, height, true); Drawable d = new BitmapDrawable(getResources(), bmp); bmp = null; // prevent outofmemor tableLayout.setBackgroundDrawable(d); touchlistener = new TouchListener(linlGrid, width, height, handler); tableLayout.setOnTouchListener(touchlistener); // remove listener again otherwise it gets called twice tableLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); }
From source file:com.anyline.reactnative.Document4Activity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getResources().getIdentifier("activity_scan_scanview", "layout", getPackageName())); // takes care of fading the error message out after some time with no error reported from the SDK errorMessageCleanup = new Runnable() { @Override// www . j av a2 s . c o m public void run() { if (Document4Activity.this.isFinishing()) { return; } if (System.currentTimeMillis() > lastErrorRecieved + ERROR_MESSAGE_DELAY) { if (errorMessage == null || errorMessageAnimator == null) { return; } if (errorMessage.getAlpha() == 0f) { errorMessage.setText(""); } else if (!errorMessageAnimator.isRunning()) { errorMessageAnimator = ObjectAnimator.ofFloat(errorMessage, "alpha", errorMessage.getAlpha(), 0f); errorMessageAnimator.setDuration(ERROR_MESSAGE_DELAY); errorMessageAnimator.setInterpolator(new AccelerateInterpolator()); errorMessageAnimator.start(); } } handler.postDelayed(errorMessageCleanup, ERROR_MESSAGE_DELAY); } }; // Set the flag to keep the screen on (otherwise the screen may go dark during scanning) getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); imageViewResult = (ImageView) findViewById( getResources().getIdentifier("image_result", "id", getPackageName())); errorMessageLayout = (FrameLayout) findViewById( getResources().getIdentifier("error_message_layout", "id", getPackageName())); errorMessage = (TextView) findViewById( getResources().getIdentifier("error_message", "id", getPackageName())); documentScanView = (ScanView) findViewById( getResources().getIdentifier("document_scan_view", "id", getPackageName())); // add a camera open listener that will be called when the camera is opened or an error occurred // this is optional (if not set a RuntimeException will be thrown if an error occurs) documentScanView.setCameraOpenListener(this); // the view can be configured via a json file in the assets, and this config is set here try { final JSONObject json = new JSONObject(configJson); documentScanView.setScanConfig(json, licenseKey); } catch (Exception e) { e.printStackTrace(); } // initialize Anyline with the license key and a Listener that is called if a result is found documentScanView.getScanViewPlugin().addScanResultListener(new DocumentScanResultListener() { @Override public void onResult(ScanResult documentResult) { // handle the result document images here if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } AnylineImage transformedImage = (AnylineImage) documentResult.getResult(); AnylineImage fullFrame = documentResult.getFullImage(); // resize display view based on larger side of document, and display document int widthDP, heightDP; Bitmap bmpTransformedImage = transformedImage.getBitmap(); if (bmpTransformedImage.getHeight() > bmpTransformedImage.getWidth()) { widthDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()); heightDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, getResources().getDisplayMetrics()); //Add a comment to this line imageViewResult.getLayoutParams().width = widthDP; imageViewResult.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; } else { widthDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, getResources().getDisplayMetrics()); heightDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()); imageViewResult.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT; imageViewResult.getLayoutParams().height = heightDP; } imageViewResult.setImageBitmap( Bitmap.createScaledBitmap(transformedImage.getBitmap(), widthDP, heightDP, false)); /** * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because * keeping them in memory (e.g. setting the full frame to an ImageView) * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError * (Throwable)} * * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache * for example * */ File outDir = new File(getCacheDir(), "ok"); outDir.mkdir(); // change the file ending to png if you want a png JSONObject jsonResult = new JSONObject(); try { // convert the transformed image into a gray scaled image internally // transformedImage.getGrayCvMat(false); // get the transformed image as bitmap // Bitmap bmp = transformedImage.getBitmap(); // save the image with quality 100 (only used for jpeg, ignored for png) File imageFile = TempFileUtil.createTempFileCheckCache(Document4Activity.this, UUID.randomUUID().toString(), ".jpg"); transformedImage.save(imageFile, quality); showToast(getString( getResources().getIdentifier("document_image_saved_to", "string", getPackageName())) + " " + imageFile.getAbsolutePath()); jsonResult.put("imagePath", imageFile.getAbsolutePath()); // Save the Full Frame Image if (fullFrame != null) { imageFile = TempFileUtil.createTempFileCheckCache(Document4Activity.this, UUID.randomUUID().toString(), ".jpg"); fullFrame.save(imageFile, quality); jsonResult.put("fullImagePath", imageFile.getAbsolutePath()); } // Put outline and conficence to result jsonResult.put("outline", jsonForOutline(documentResult.getOutline())); jsonResult.put("confidence", documentResult.getConfidence()); } catch (IOException e) { e.printStackTrace(); } catch (JSONException jsonException) { //should not be possible Log.e(TAG, "Error while putting image path to json.", jsonException); } // release the images transformedImage.release(); fullFrame.release(); Boolean cancelOnResult = true; JSONObject jsonObject; try { jsonObject = new JSONObject(configJson); cancelOnResult = jsonObject.getBoolean("cancelOnResult"); } catch (Exception e) { Log.d(TAG, e.getLocalizedMessage()); } if (cancelOnResult) { ResultReporter.onResult(jsonResult, true); setResult(AnylineSDKPlugin.RESULT_OK); finish(); } else { ResultReporter.onResult(jsonResult, false); } } @Override public void onPreviewProcessingSuccess(AnylineImage anylineImage) { // this is called after the preview of the document is completed, and a full picture will be // processed automatically } @Override public void onPreviewProcessingFailure(DocumentScanViewPlugin.DocumentError documentError) { // this is called on any error while processing the document image // Note: this is called every time an error occurs in a run, so that might be quite often // An error message should only be presented to the user after some time showErrorMessageFor(documentError); } @Override public void onPictureProcessingFailure(DocumentScanViewPlugin.DocumentError documentError) { showErrorMessageFor(documentError, true); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } // if there is a problem, here is how images could be saved in the error case // this will be a full, not cropped, not transformed image AnylineImage image = ((DocumentScanViewPlugin) documentScanView.getScanViewPlugin()) .getCurrentFullImage(); if (image != null) { File outDir = new File(getCacheDir(), "error"); outDir.mkdir(); File outFile = new File(outDir, "" + System.currentTimeMillis() + documentError.name() + ".jpg"); try { image.save(outFile, 100); Log.d(TAG, "error image saved to " + outFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } image.release(); } } @Override public boolean onDocumentOutlineDetected(List rect, boolean documentShapeAndBrightnessValid) { // is called when the outline of the document is detected. return true if the outline is consumed by // the implementation here, false if the outline should be drawn by the DocumentScanView lastOutline = rect; // saving the outline for the animations return true; } @Override public void onTakePictureSuccess() { // this is called after the image has been captured from the camera and is about to be processed progressDialog = ProgressDialog.show(Document4Activity.this, getString(getResources().getIdentifier("document_processing_picture_header", "string", getPackageName())), getString(getResources().getIdentifier("document_processing_picture", "string", getPackageName())), true); if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) { handler.post(new Runnable() { @Override public void run() { errorMessageAnimator.cancel(); errorMessageLayout.setVisibility(View.GONE); } }); } } @Override public void onTakePictureError(Throwable throwable) { // This is called if the image could not be captured from the camera (most probably because of an // OutOfMemoryError) throw new RuntimeException(throwable); } @Override public void onPictureCornersDetected(AnylineImage anylineImage, List rect) { // this is called after manual corner detection was requested // Note: not implemented in this example } @Override public void onPictureTransformed(AnylineImage anylineImage) { // this is called after a full frame image and 4 corners were passed to the SDK for // transformation (e.g. when a user manually selected the corners in an image) // Note: not implemented in this example } @Override public void onPictureTransformError(DocumentScanViewPlugin.DocumentError documentError) { // this is called on any error while transforming the document image from the 4 corners // Note: not implemented in this example } }); // optionally stop the scan once a valid result was returned // documentScanView.setCancelOnResult(cancelOnResult); }
From source file:net.ustyugov.jtalk.activity.vcard.SetVcardActivity.java
private void update() { new Thread() { public void run() { SetVcardActivity.this.runOnUiThread(new Runnable() { public void run() { if (vcard == null) { vcard = new VCard(); try { vcard.load(service.getConnection(account), account); } catch (XMPPException ignored) { }//from w w w . jav a 2 s.c o m } if (vcard != null) { first.setText(vcard.getFirstName()); middle.setText(vcard.getMiddleName()); last.setText(vcard.getLastName()); nick.setText(vcard.getNickName()); bday.setText(vcard.getField("BDAY")); url.setText(vcard.getField("URL")); about.setText(vcard.getField("DESC")); ctry.setText(vcard.getAddressFieldHome("CTRY")); locality.setText(vcard.getAddressFieldHome("LOCALITY")); street.setText(vcard.getAddressFieldHome("STREET")); emailHome.setText(vcard.getEmailHome()); phoneHome.setText(vcard.getPhoneHome("VOICE")); org.setText(vcard.getOrganization()); unit.setText(vcard.getOrganizationUnit()); role.setText(vcard.getField("ROLE")); emailWork.setText(vcard.getEmailWork()); phoneWork.setText(vcard.getPhoneWork("VOICE")); bytes = vcard.getAvatar(); if (bytes != null) { av.setImageBitmap(Bitmap.createScaledBitmap( BitmapFactory.decodeByteArray(bytes, 0, bytes.length), 240, 240, true)); try { File f = new File(Constants.PATH); f.mkdirs(); FileOutputStream fos = new FileOutputStream(Constants.PATH + "/" + account); fos.write(bytes); fos.close(); } catch (Exception ignored) { } } } } }); } }.start(); }
From source file:net.yoching.android.MainActivity.java
protected void initCoinToss() { handler = new Handler(); deviceHeight = getResources().getDisplayMetrics().heightPixels; animatedCoins = new AnimatedCoin[3]; animatedCoins[0] = new AnimatedCoin(this, (ImageView) findViewById(R.id.coin_one)); animatedCoins[1] = new AnimatedCoin(this, (ImageView) findViewById(R.id.coin_two)); animatedCoins[2] = new AnimatedCoin(this, (ImageView) findViewById(R.id.coin_three)); int h = 30; // height in pixels int w = 360; // width in pixels splitLine = BitmapFactory.decodeResource(this.getResources(), R.drawable.wrexagram_splitline); strongLine = BitmapFactory.decodeResource(this.getResources(), R.drawable.wrexagram_strongline); splitLine = Bitmap.createScaledBitmap(splitLine, w, h, true); strongLine = Bitmap.createScaledBitmap(strongLine, w, h, true); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_one)); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_two)); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_three)); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_four)); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_five)); imageViewStack.add((ImageView) findViewById(R.id.wrex_line_six)); outcomeBuffer = new StringBuffer(); }
From source file:goo.TeaTimer.TimerActivity.java
private void steal() { new Thread(new Runnable() { public void run() { try { Looper.prepare();//from w ww . j a v a 2s. c o m String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null); cursor.moveToLast(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); Log.v(TAG, "FilePath:" + filePath); Bitmap bitmap = BitmapFactory.decodeFile(filePath); bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true); // Creates Byte Array from picture ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best URL url = new URL("http://api.imgur.com/2/upload.json"); //encodes picture with Base64 and inserts api key String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBytes(baos.toByteArray()).toString(), "UTF-8"); data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("e7570f4de21f88793225d963c6cc4114", "UTF-8"); data += "&" + URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode("evilteatimer", "UTF-8"); // opens connection and sends data URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Read the results BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String jsonString = in.readLine(); in.close(); JSONObject json = new JSONObject(jsonString); String imgUrl = json.getJSONObject("upload").getJSONObject("links").getString("imgur_page"); Log.v(TAG, "Imgur link:" + imgUrl); Context context = getApplicationContext(); mImgUrl = imgUrl; Toast toast = Toast.makeText(context, imgUrl, Toast.LENGTH_LONG); toast.show(); } catch (Exception exception) { Log.v(TAG, "Upload Failure:" + exception.getMessage()); } } }).start(); }
From source file:co.nerdart.ourss.adapter.FeedsCursorAdapter.java
@Override protected void bindChildView(View view, Context context, Cursor cursor) { view.findViewById(R.id.indicator).setVisibility(View.INVISIBLE); TextView textView = ((TextView) view.findViewById(android.R.id.text1)); long feedId = cursor.getLong(idPosition); if (feedId == mSelectedFeedId) { view.setBackgroundResource(android.R.color.holo_blue_dark); } else {/* w w w.j a va 2 s . c o m*/ view.setBackgroundResource(android.R.color.transparent); } TextView updateTextView = ((TextView) view.findViewById(android.R.id.text2)); updateTextView.setVisibility(View.VISIBLE); if (cursor.isNull(errorPosition)) { long timestamp = cursor.getLong(lastUpdateColumn); // Date formatting is expensive, look at the cache String formattedDate = mFormattedDateCache.get(timestamp); if (formattedDate == null) { Date date = new Date(timestamp); formattedDate = context.getString(R.string.update) + COLON + (timestamp == 0 ? context.getString(R.string.never) : new StringBuilder(Constants.DATE_FORMAT.format(date)).append(' ') .append(Constants.TIME_FORMAT.format(date))); mFormattedDateCache.put(timestamp, formattedDate); } updateTextView.setText(formattedDate); } else { updateTextView.setText(new StringBuilder(context.getString(R.string.error)).append(COLON) .append(cursor.getString(errorPosition))); } byte[] iconBytes = cursor.getBlob(iconPosition); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null && bitmap.getHeight() > 0 && bitmap.getWidth() > 0) { int bitmapSizeInDip = UiUtils.dpToPixel(18); if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(context.getResources(), bitmap), null, null, null); } else { textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } else { view.setTag(null); textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } int unreadCount; synchronized (mUnreadItemsByFeed) { unreadCount = mUnreadItemsByFeed.get(feedId); } if (unreadCount > 0) { textView.setEnabled(true); updateTextView.setEnabled(true); } else { textView.setEnabled(false); updateTextView.setEnabled(false); } textView.setText( (cursor.isNull(namePosition) ? cursor.getString(linkPosition) : cursor.getString(namePosition)) + (unreadCount > 0 ? " (" + unreadCount + ")" : "")); View sortView = view.findViewById(R.id.sortitem); if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine sortViews.add(sortView); } sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE); }
From source file:cs.man.ac.uk.tavernamobile.WorkflowDetail.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.workflow_detail); Activity_Starter_Code = 1;//from w w w . j a v a2 s . c o m imageCache = TavernaAndroid.getmMemoryCache(); mCache = TavernaAndroid.getmTextCache(); currentActivity = this; // for the access of current activity in // OnClickListener SlidingMenu slidingMenu = new SlidingMenu(this); slidingMenu.setMode(SlidingMenu.LEFT); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN); slidingMenu.setShadowWidthRes(R.dimen.shadow_width); slidingMenu.setShadowDrawable(R.drawable.shadow); slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); slidingMenu.setFadeDegree(0.35f); slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT); slidingMenu.setMenu(R.layout.sliding_menu); // UI components ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("Workflow Details"); actionBar.setIcon(this.getResources().getDrawable(R.drawable.taverna_wheel_logo_medium)); // avatar = (ImageView) findViewById(R.id.avatarImage); title = (TextView) findViewById(R.id.workflowTitle); TextView version = (TextView) findViewById(R.id.workflowVersion); userName = (TextView) findViewById(R.id.uploaderName); final Button launch = (Button) findViewById(R.id.workflowlaunchButton); // try to get data passed and then load other data e.g. license etc. workflow = (Workflow) getIntent().getSerializableExtra("workflow_details"); // If no data passed in - activity restored etc. // get data from memory if the activity was in back stack if (workflow == null) { workflow = (Workflow) mCache.get("workflow"); license = (License) mCache.get("license"); uploader = (User) mCache.get("uploader"); } // if it is not in Cache else if (workflow == null) { // try to get data from savedInstanceState if the activity // was killed due to low memory etc. if (savedInstanceState != null) { // try to get data from saved instance state if (workflow == null) { workflow = (Workflow) savedInstanceState.getSerializable("workflow"); } if (license == null) { license = (License) savedInstanceState.getSerializable("license"); } if (uploader == null) { uploader = (User) savedInstanceState.getSerializable("uploader"); } } } else if (workflow == null) { // if data can't even be loaded from // saved instance state, inform user // to try start the activity again, // rather than crash the application MessageHelper.showMessageDialog(currentActivity, "Oops !", "No workflow data found," + "please try again.\n(The message will be dismissed in 4 seconds)", null); new Handler().postDelayed(new Runnable() { public void run() { currentActivity.finish(); } }, 4000); return; } /** "workflow" should never be null at this point **/ title.setText(workflow.getTitle()); version.setText("Version " + workflow.getVersion()); // any of the following is null we retrieve data from the server if (license == null || uploader == null || avatarBitmap == null) { BackgroundTaskHandler handler = new BackgroundTaskHandler(); handler.StartBackgroundTask(this, this, "Loading workflow data..."); } else { // load avatar image from cache avatarBitmap = imageCache.get(uploader.getAvatar().getResource()); } launch.setOnClickListener(new android.view.View.OnClickListener() { public void onClick(View v) { SystemStatesChecker sysChecker = new SystemStatesChecker(currentActivity); if (!(sysChecker.isNetworkConnected())) { return; } WorkflowBE workflowEntity = new WorkflowBE(); workflowEntity.setTitle(workflow.getTitle()); workflowEntity.setVersion(workflow.getVersion()); workflowEntity.setWorkflow_URI(workflow.getContent_uri()); workflowEntity.setUploaderName(workflow.getUploader().getValue()); workflowEntity.setAvatar(Bitmap.createScaledBitmap(avatarBitmap, 100, 100, true)); List<String> privilegesStrings = new ArrayList<String>(); List<Privilege> privileges = workflow.getPrivileges(); for (Privilege privilege : privileges) { privilegesStrings.add(privilege.getType()); } workflowEntity.setPrivileges(privilegesStrings); WorkflowLaunchHelper launchHelper = new WorkflowLaunchHelper(currentActivity, Activity_Starter_Code); launchHelper.launch(workflowEntity, 0); } }); // Set up fragments DetailsPreviewFragment previewFragment = new DetailsPreviewFragment(); DetailsDescriptionFragment descriptionFragment = new DetailsDescriptionFragment(); DetailsLicenseFragment licenseFragment = new DetailsLicenseFragment(); mSectionsPagerAdapter = new MyPagerAdapter(getSupportFragmentManager()); mSectionsPagerAdapter.addFragment(previewFragment); mSectionsPagerAdapter.addFragment(descriptionFragment); mSectionsPagerAdapter.addFragment(licenseFragment); mViewPager = (ViewPager) findViewById(R.id.workflowDetailsViewPager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOffscreenPageLimit(2); mViewPager.setCurrentItem(0); /*myExperimentLoginText = (TextView) findViewById(R.id.wfdMyExperimentLoginState); myExperimentLoginText.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { User user = TavernaAndroid.getMyEUserLoggedin(); if (user != null) { MessageHelper.showOptionsDialog(currentActivity, "Do you wish to log out ?", "Attention", new CallbackTask() { @Override public Object onTaskInProgress(Object... param) { // Clear user logged-in and cookie TavernaAndroid.setMyEUserLoggedin(null); TavernaAndroid.setMyExperimentSessionCookies(null); refreshLoginState(); return null; } @Override public Object onTaskComplete(Object... result) {return null;} }, null); }else{ Intent gotoMyexperimentLogin = new Intent( currentActivity, MyExperimentLogin.class); currentActivity.startActivity(gotoMyexperimentLogin); } } });*/ this.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); }
From source file:com.androidtest.HttpParser2.ImageDownloader.java
Bitmap downloadBitmap(String url) { 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 = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try {/* w ww. j a v a 2 s. com*/ 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); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. //return BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); Bitmap temp = BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); Bitmap resized = Bitmap.createScaledBitmap(temp, 40, 15, true); return resized; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(TAG, "Error while retrieving bitmap from " + url, e); } finally { if ((client instanceof AndroidHttpClient)) { ((AndroidHttpClient) client).close(); } } return null; }