List of usage examples for android.graphics BitmapFactory decodeByteArray
public static Bitmap decodeByteArray(byte[] data, int offset, int length)
From source file:com.example.amand.mobileprogrammingfitnessapp.LoggedActivity.java
public void setNavigationDetails(String currentUser) { String temp2 = database.getfirstName(currentUser); String temp3 = database.getSurname(currentUser); // the firstname and second name is obtained by calling the database methods, these methods take // string username as parameters. The database method, finds the details in the database depending on the // username. The details are then stored and set on the navigation header textviews. username.setText(currentUser);//from ww w .j ava2 s .c o m namee.setText(temp2 + " " + temp3); // the same is applied with the image. The methodd returns byte array that is decoded into an image // and is set on the circular imageview decode = database.getImage(currentUser); Bitmap image = BitmapFactory.decodeByteArray(decode, 0, decode.length); circle.setImageBitmap(image); Bundle bundle = new Bundle(); bundle.putString("key", currentUser); GymFrag frag = new GymFrag(); frag.setArguments(bundle); }
From source file:com.ravi.apps.android.newsbytes.DetailsFragment.java
/** * Binds the data to the corresponding views. */// ww w . j a v a2 s. c o m private void bindDataToView() { // Load photo into image view. If this is a favorite story, // then load from byte array else use Picasso. if (mNews.getIsFavorite() == 1) { // Get the photo byte array from the news object. byte[] photoByteStream = mNews.getPhoto(); // Check if byte array for photo is non null and non zero length. if (photoByteStream != null && photoByteStream.length != 0) { // Get the photo bitmap from byte array. Bitmap photoBitmap = BitmapFactory.decodeByteArray(photoByteStream, 0, photoByteStream.length); // Set the photo bitmap into the image view. mPhoto.setImageBitmap(photoBitmap); mPhoto.setScaleType(ImageView.ScaleType.FIT_XY); } else { // Show photo placeholder icon and log error message. mPhoto.setImageResource(R.drawable.photo_placeholder); Log.e(LOG_TAG, getString(R.string.msg_err_no_photo)); } } else { // Load the photo using picasso. if (mNews.getUriPhoto() != null) { Picasso.with(getActivity()).load(mNews.getUriPhoto()).into(mPhotoTarget); } else { // Show photo placeholder icon and log error message. mPhoto.setImageResource(R.drawable.photo_placeholder); Log.e(LOG_TAG, getString(R.string.msg_err_no_photo)); } } // Check if it's not a favorite and the thumbnail byte array was not generated in the // headlines screen. If so, use picasso to get the bitmap and generate thumbnail byte // array and then store it in the news object. It will be required if the user // chooses to mark this as favorite. if (mNews.getIsFavorite() == 0 && mNews.getThumbnail() != null && mNews.getThumbnail().length == 0) { // Generate the thumbnail byte array using picasso. Picasso.with(getActivity()).load(mNews.getUriThumbnail()).into(mThumbnailTarget); } // Compose a single string for both caption and copyright and set to the text view. String caption = ""; // Get the caption. if (mNews.getCaptionPhoto() != null && !mNews.getCaptionPhoto().isEmpty()) { caption = mNews.getCaptionPhoto(); } // Get the copyright and append it to the caption. if (mNews.getCopyrightPhoto() != null && !mNews.getCopyrightPhoto().isEmpty()) { if (caption.isEmpty()) { caption = getString(R.string.label_copyright) + mNews.getCopyrightPhoto(); } else { caption += " " + getString(R.string.label_copyright) + mNews.getCopyrightPhoto(); } } // Check if the composed string is empty and set accordingly. if (!caption.isEmpty()) { mCaption.setText(caption); mCaption.setContentDescription(caption); } else { // Caption and copyright are not available, remove the view and log error message. ((ViewGroup) mCaption.getParent()).removeView(mCaption); Log.e(LOG_TAG, getString(R.string.msg_err_no_caption_copyright)); } // Set the headline. if (mNews.getHeadline() != null && !mNews.getHeadline().isEmpty()) { mHeadline.setText(mNews.getHeadline()); mHeadline.setContentDescription(mNews.getHeadline()); } else { // Headline is not available, show and log error message. mHeadline.setText(getString(R.string.msg_err_no_headline)); mHeadline.setContentDescription(getString(R.string.msg_err_no_headline)); Log.e(LOG_TAG, getString(R.string.msg_err_no_headline)); } // Set the author. if (mNews.getAuthor() != null && !mNews.getAuthor().isEmpty()) { mAuthor.setText(mNews.getAuthor()); mAuthor.setContentDescription(mNews.getAuthor()); } else { // Author is not available, remove the view and log error message. ((ViewGroup) mAuthor.getParent()).removeView(mAuthor); Log.e(LOG_TAG, getString(R.string.msg_err_no_author)); } // Set the date. if (mNews.getDate() != null && !mNews.getDate().isEmpty() && Utility.getFormattedDate(getActivity(), mNews.getDate()) != null) { String date = Utility.getFormattedDate(getActivity(), mNews.getDate()); mDate.setText(date); mDate.setContentDescription(date); } else { // Date is not available, remove the view and log error message. ((ViewGroup) mDate.getParent()).removeView(mDate); Log.e(LOG_TAG, getString(R.string.msg_err_no_date)); } // Set the summary. if (mNews.getSummary() != null && !mNews.getSummary().isEmpty()) { mSummary.setText(mNews.getSummary()); mSummary.setContentDescription(mNews.getSummary()); } else { // Summary is not available, show and log error message. mSummary.setText(getString(R.string.msg_err_no_summary)); mSummary.setContentDescription(getString(R.string.msg_err_no_summary)); Log.e(LOG_TAG, getString(R.string.msg_err_no_summary)); } }
From source file:com.marlonjones.voidlauncher.InstallShortcutReceiver.java
private static PendingInstallShortcutInfo decode(String encoded, Context context) { try {// w w w .ja v a 2 s. c o m JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue(); Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0); if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) { // The is an internal launcher target shortcut. UserHandleCompat user = UserManagerCompat.getInstance(context) .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY)); if (user == null) { return null; } LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context) .resolveActivity(launcherIntent, user); return info == null ? null : new PendingInstallShortcutInfo(info, context); } Intent data = new Intent(); data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent); data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY)); String iconBase64 = object.optString(ICON_KEY); String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY); String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY); if (iconBase64 != null && !iconBase64.isEmpty()) { byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT); Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length); data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b); } else if (iconResourceName != null && !iconResourceName.isEmpty()) { Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource(); iconResource.resourceName = iconResourceName; iconResource.packageName = iconResourcePackageName; data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); } return new PendingInstallShortcutInfo(data, context); } catch (JSONException | URISyntaxException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } return null; }
From source file:com.akop.bach.ImageCache.java
public Bitmap getBitmap(String imageUrl, boolean bypassCache, int resizeH, int resizeV) { File file = getCacheFile(imageUrl, null); // See if it's in the local cache // (but only if not being forced to refresh) if (!bypassCache && file.canRead()) { if (App.getConfig().logToConsole()) App.logv("Cache hit: " + file.getAbsolutePath()); file.lastModified();//from w w w . ja va 2 s . c o m try { return BitmapFactory.decodeFile(file.getAbsolutePath()); } catch (OutOfMemoryError e) { return null; } } // Fetch the image byte[] blob; int length; try { HttpClient client = new IgnorantHttpClient(); HttpResponse resp = client.execute(new HttpGet(imageUrl)); HttpEntity entity = resp.getEntity(); if (entity == null) return null; InputStream stream = entity.getContent(); if (stream == null) return null; try { if ((length = (int) entity.getContentLength()) <= 0) return null; blob = new byte[length]; // Read the stream until nothing more to read for (int r = 0; r < length; r += stream.read(blob, r, length - r)) ; } finally { stream.close(); entity.consumeContent(); } } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); return null; } // if (file.canWrite()) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (resizeH > -1 || resizeV > -1) { Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, length); float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight(); int newWidth = (resizeH < 0) ? (int) ((float) resizeV * aspectRatio) : resizeH; int newHeight = (resizeV < 0) ? (int) ((float) resizeH / aspectRatio) : resizeV; Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); resized.compress(Bitmap.CompressFormat.PNG, 100, fos); return resized; } else { fos.write(blob); } if (App.getConfig().logToConsole()) App.logv("Wrote to cache: " + file.getAbsolutePath()); } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } Bitmap bmp = null; try { bmp = BitmapFactory.decodeByteArray(blob, 0, length); } catch (Exception e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } return bmp; }
From source file:com.android.launcher3.InstallShortcutReceiver.java
private static PendingInstallShortcutInfo decode(String encoded, Context context) { try {//from w w w . ja v a 2s. c o m JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue(); Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0); if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) { // The is an internal launcher target shortcut. UserHandleCompat user = UserManagerCompat.getInstance(context) .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY)); if (user == null) { return null; } LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context) .resolveActivity(launcherIntent, user); return info == null ? null : new PendingInstallShortcutInfo(info, context); } Intent data = new Intent(); data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent); data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY)); String iconBase64 = object.optString(ICON_KEY); String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY); String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY); if (iconBase64 != null && !iconBase64.isEmpty()) { byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT); Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length); data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b); } else if (iconResourceName != null && !iconResourceName.isEmpty()) { Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource(); iconResource.resourceName = iconResourceName; iconResource.packageName = iconResourcePackageName; data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); } return new PendingInstallShortcutInfo(data, context); } catch (JSONException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } catch (URISyntaxException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } return null; }
From source file:com.pimp.companionforband.activities.main.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sContext = getApplicationContext();/*from w w w . j a v a 2s. co m*/ sActivity = this; sharedPreferences = getApplicationContext().getSharedPreferences("MyPrefs", 0); editor = sharedPreferences.edit(); bandSensorData = new BandSensorData(); mDestinationUri = Uri.fromFile(new File(getCacheDir(), SAMPLE_CROPPED_IMAGE_NAME)); SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; if (!checkCameraPermission(true)) requestCameraPermission(true); if (!checkCameraPermission(false)) requestCameraPermission(false); FiveStarsDialog fiveStarsDialog = new FiveStarsDialog(this, "pimplay69@gmail.com"); fiveStarsDialog.setTitle(getString(R.string.rate_dialog_title)) .setRateText(getString(R.string.rate_dialog_text)).setForceMode(false).setUpperBound(4) .setNegativeReviewListener(this).showAfter(5); AnalyticsApplication application = (AnalyticsApplication) getApplication(); mTracker = application.getDefaultTracker(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOffscreenPageLimit(2); mViewPager.setPageTransformer(true, new ZoomOutPageTransformer()); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { String name; switch (position) { case 0: name = "THEME"; break; case 1: name = "SENSORS"; break; case 2: name = "EXTRAS"; break; default: name = "CfB"; } mTracker.setScreenName("Image~" + name); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); logSwitch = (Switch) findViewById(R.id.log_switch); backgroundLogSwitch = (Switch) findViewById(R.id.backlog_switch); logStatus = (TextView) findViewById(R.id.logStatus); backgroundLogStatus = (TextView) findViewById(R.id.backlogStatus); } @Override public void onPageScrollStateChanged(int state) { } }); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); Drawable headerBackground = null; String encoded = sharedPreferences.getString("me_tile_image", "null"); if (!encoded.equals("null")) { byte[] imageAsBytes = Base64.decode(encoded.getBytes(), Base64.DEFAULT); headerBackground = new BitmapDrawable( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)); } AccountHeader accountHeader = new AccountHeaderBuilder().withActivity(this).withCompactStyle(true) .withHeaderBackground((headerBackground == null) ? getResources().getDrawable(R.drawable.pipboy) : headerBackground) .addProfiles(new ProfileDrawerItem() .withName(sharedPreferences.getString("device_name", "Companion For Band")) .withEmail(sharedPreferences.getString("device_mac", "pimplay69@gmail.com")) .withIcon(getResources().getDrawable(R.drawable.band))) .build(); result = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withActionBarDrawerToggleAnimated(true) .withAccountHeader(accountHeader) .addDrawerItems( new PrimaryDrawerItem().withName(getString(R.string.drawer_cloud)) .withIcon(GoogleMaterial.Icon.gmd_cloud).withIdentifier(1), new DividerDrawerItem(), new PrimaryDrawerItem().withName(getString(R.string.rate)) .withIcon(GoogleMaterial.Icon.gmd_rate_review).withIdentifier(2), new PrimaryDrawerItem().withName(getString(R.string.feedback)) .withIcon(GoogleMaterial.Icon.gmd_feedback).withIdentifier(3), new DividerDrawerItem(), new PrimaryDrawerItem().withName(getString(R.string.share)) .withIcon(GoogleMaterial.Icon.gmd_share).withIdentifier(4), new PrimaryDrawerItem().withName(getString(R.string.other)) .withIcon(GoogleMaterial.Icon.gmd_apps).withIdentifier(5), new DividerDrawerItem(), new PrimaryDrawerItem().withName(getString(R.string.report)) .withIcon(GoogleMaterial.Icon.gmd_bug_report).withIdentifier(6), new PrimaryDrawerItem().withName(getString(R.string.translate)) .withIcon(GoogleMaterial.Icon.gmd_translate).withIdentifier(9), new DividerDrawerItem(), new PrimaryDrawerItem().withName(getString(R.string.support)) .withIcon(GoogleMaterial.Icon.gmd_attach_money).withIdentifier(7), new PrimaryDrawerItem().withName(getString(R.string.aboutLib)) .withIcon(GoogleMaterial.Icon.gmd_info).withIdentifier(8)) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { boolean flag; if (drawerItem != null) { flag = true; switch ((int) drawerItem.getIdentifier()) { case 1: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Cloud").build()); if (!sharedPreferences.getString("access_token", "hi").equals("hi")) startActivity(new Intent(getApplicationContext(), CloudActivity.class)); else startActivity(new Intent(getApplicationContext(), WebviewActivity.class)); break; case 2: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Rate and Review").build()); String MARKET_URL = "https://play.google.com/store/apps/details?id="; String PlayStoreListing = getPackageName(); Intent rate = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URL + PlayStoreListing)); startActivity(rate); break; case 3: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Feedback").build()); final StringBuilder emailBuilder = new StringBuilder(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:pimplay69@gmail.com")); intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); emailBuilder.append("\n \n \nOS Version: ").append(System.getProperty("os.version")) .append("(").append(Build.VERSION.INCREMENTAL).append(")"); emailBuilder.append("\nOS API Level: ").append(Build.VERSION.SDK_INT); emailBuilder.append("\nDevice: ").append(Build.DEVICE); emailBuilder.append("\nManufacturer: ").append(Build.MANUFACTURER); emailBuilder.append("\nModel (and Product): ").append(Build.MODEL).append(" (") .append(Build.PRODUCT).append(")"); PackageInfo appInfo = null; try { appInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } assert appInfo != null; emailBuilder.append("\nApp Version Name: ").append(appInfo.versionName); emailBuilder.append("\nApp Version Code: ").append(appInfo.versionCode); intent.putExtra(Intent.EXTRA_TEXT, emailBuilder.toString()); startActivity(Intent.createChooser(intent, "Send via")); break; case 4: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Share").build()); Intent i = new AppInviteInvitation.IntentBuilder( getString(R.string.invitation_title)) .setMessage(getString(R.string.invitation_message)) .setCallToActionText(getString(R.string.invitation_cta)).build(); startActivityForResult(i, REQUEST_INVITE); break; case 5: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Other Apps").build()); String PlayStoreDevAccount = "https://play.google.com/store/apps/developer?id=P.I.M.P."; Intent devPlay = new Intent(Intent.ACTION_VIEW, Uri.parse(PlayStoreDevAccount)); startActivity(devPlay); break; case 6: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Report Bugs").build()); startActivity(new Intent(MainActivity.this, GittyActivity.class)); break; case 7: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Donate").build()); String base64EncodedPublicKey = getString(R.string.base64); mHelper = new IabHelper(getApplicationContext(), base64EncodedPublicKey); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { Toast.makeText(MainActivity.this, "Problem setting up In-app Billing: " + result, Toast.LENGTH_LONG).show(); } } }); final Dialog dialog = new Dialog(MainActivity.this); dialog.setContentView(R.layout.dialog_donate); dialog.setTitle("Donate"); String[] title = { "Coke", "Coffee", "Burger", "Pizza", "Meal" }; String[] price = { "Rs. 10.00", "Rs. 50.00", "Rs. 100.00", "Rs. 500.00", "Rs. 1,000.00" }; ListView listView = (ListView) dialog.findViewById(R.id.list); listView.setAdapter(new DonateListAdapter(MainActivity.this, title, price)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: mHelper.launchPurchaseFlow(MainActivity.this, SKU_COKE, 1, mPurchaseFinishedListener, "payload"); break; case 1: mHelper.launchPurchaseFlow(MainActivity.this, SKU_COFFEE, 1, mPurchaseFinishedListener, "payload"); break; case 2: mHelper.launchPurchaseFlow(MainActivity.this, SKU_BURGER, 1, mPurchaseFinishedListener, "payload"); break; case 3: mHelper.launchPurchaseFlow(MainActivity.this, SKU_PIZZA, 1, mPurchaseFinishedListener, "payload"); break; case 4: mHelper.launchPurchaseFlow(MainActivity.this, SKU_MEAL, 1, mPurchaseFinishedListener, "payload"); break; } } }); dialog.show(); break; case 8: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("About").build()); new LibsBuilder().withLicenseShown(true).withVersionShown(true) .withActivityStyle(Libs.ActivityStyle.DARK).withAboutVersionShown(true) .withActivityTitle(getString(R.string.app_name)).withAboutIconShown(true) .withListener(libsListener).start(MainActivity.this); break; case 9: mTracker.send(new HitBuilders.EventBuilder().setCategory("Action") .setAction("Translate").build()); Intent translate = new Intent(Intent.ACTION_VIEW, Uri.parse("https://poeditor.com/join/project/AZQxDV2440")); startActivity(translate); break; default: break; } } else { flag = false; } return flag; } }).withSavedInstance(savedInstanceState).build(); AppUpdater appUpdater = new AppUpdater(this); appUpdater.start(); final DirectoryChooserConfig config = DirectoryChooserConfig.builder() .allowNewDirectoryNameModification(true).newDirectoryName("CfBCamera") .initialDirectory( sharedPreferences.getString("pic_location", "/storage/emulated/0/CompanionForBand/Camera")) .build(); mDialog = DirectoryChooserFragment.newInstance(config); new BandUtils().execute(); CustomActivityOnCrash.install(this); }
From source file:com.appdevper.mediaplayer.app.MediaNotificationManager.java
private Bitmap downloadBitmap(String mediaId) { String url = MusicProvider.getInstance().getMusic(mediaId) .getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE); final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); metaRetriever.setDataSource(url, new HashMap<String, String>()); try {// w ww. j av a 2 s .c o m final byte[] art = metaRetriever.getEmbeddedPicture(); return BitmapFactory.decodeByteArray(art, 0, art.length); } catch (Exception e) { Log.d(TAG, "Couldn't create album art: " + e.getMessage()); return BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art); } }
From source file:com.tjcj.carrental.fragment.DriverFragment.java
/** * string?bitmap/*from ww w . j a va 2 s .co m*/ * * @param st */ public static Bitmap convertStringToIcon(String st) { Bitmap bitmap = null; try { byte[] bitmapArray; bitmapArray = Base64.decode(st, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); return bitmap; } catch (Exception e) { return null; } }
From source file:com.mk4droid.IMC_Activities.Fragment_Map.java
private void PutMarkers(int reZoomSW) { if (gmap == null) { return;/*from w ww . j ava 2 s . co m*/ } if (mMarkers != null) if (mMarkers.size() > 0) for (int i = 0; i < mMarkers.size(); i++) mMarkers.get(i).remove(); mMarkers = new ArrayList<Marker>(); if (Service_Data.mIssueL == null) return; if (Service_Data.mIssueL.size() > 0) { minLat = Service_Data.mIssueL.get(0)._latitude; minLong = Service_Data.mIssueL.get(0)._longitude; maxLat = Service_Data.mIssueL.get(0)._latitude; maxLong = Service_Data.mIssueL.get(0)._longitude; } //------------------ Urban Problems ---------------- int NIssues = Service_Data.mIssueL.size(); for (int j = 0; j < Service_Data.mCategL.size(); j++) { if (Service_Data.mCategL.get(j)._visible == 1) { // Filters for Visibility // Every categ has an overlayitem with multiple overlays in it !!! //---------- Drawable icon ------- byte[] b = Service_Data.mCategL.get(j)._icon; Bitmap bm = null; if (b != null) { bm = BitmapFactory.decodeByteArray(b, 0, b.length); } else { // Load a standard icon bm = BitmapFactory.decodeResource(getResources(), R.drawable.comments_icon); } for (int i = 0; i < NIssues; i++) { //------ iterate to find category of issue and icon to display if ((Service_Data.mIssueL.get(i)._currentstatus == 1 && mshPrefs.getBoolean("OpenSW", true)) || (Service_Data.mIssueL.get(i)._currentstatus == 2 && mshPrefs.getBoolean("AckSW", true)) || (Service_Data.mIssueL.get(i)._currentstatus == 3 && mshPrefs.getBoolean("ClosedSW", true))) { if (Service_Data.mIssueL.get(i)._catid == Service_Data.mCategL.get(j)._id) { if (mshPrefs.getBoolean("MyIssuesSW", false) && !Integer.toString(Service_Data.mIssueL.get(i)._userid).equals(UserID_STR)) continue; //--------- upd view limits ------------- maxLat = Math.max(Service_Data.mIssueL.get(i)._latitude, maxLat); minLat = Math.min(Service_Data.mIssueL.get(i)._latitude, minLat); maxLong = Math.max(Service_Data.mIssueL.get(i)._longitude, maxLong); minLong = Math.min(Service_Data.mIssueL.get(i)._longitude, minLong); mMarkers.add(gmap.addMarker(new MarkerOptions() .position(new LatLng(Service_Data.mIssueL.get(i)._latitude, Service_Data.mIssueL.get(i)._longitude)) .title(Service_Data.mIssueL.get(i)._title) .snippet("# " + Integer.toString(Service_Data.mIssueL.get(i)._id)) .icon(BitmapDescriptorFactory.fromBitmap(bm)))); } // cat match } // open closed } // i } // visible } // j if (reZoomSW == 1) { if (Fragment_NewIssueB.LastIssLat != 0 && Fragment_NewIssueB.LastIssLong != 0) { gmap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(Fragment_NewIssueB.LastIssLat, Fragment_NewIssueB.LastIssLong), 14)); Fragment_NewIssueB.LastIssLat = 0; Fragment_NewIssueB.LastIssLong = 0; } else { if (Math.abs((maxLat - minLat)) + Math.abs(maxLong - minLong) != 0) { LatLngBounds bounds = new LatLngBounds.Builder().include(new LatLng(maxLat, minLong)) // Upper Right .include(new LatLng(minLat, maxLong)) // Lower Left .build(); metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); gmap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, metrics.widthPixels, metrics.heightPixels, 50)); } else if (Service_Location.locUser.getLatitude() != 0 && Service_Location.locUser.getLongitude() != 0) { gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng( Service_Location.locUser.getLatitude(), Service_Location.locUser.getLongitude()), 14)); } else { gmap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(Service_Location.locUserPred.getLatitude(), Service_Location.locUserPred.getLongitude()), 14)); } } } }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
@SuppressWarnings("unchecked") protected T transform(String url, byte[] data, AjaxStatus status) { if (type == null) { return null; }/*from ww w. j av a2s. co m*/ File file = status.getFile(); if (data != null) { if (type.equals(Bitmap.class)) { return (T) BitmapFactory.decodeByteArray(data, 0, data.length); } if (type.equals(JSONObject.class)) { JSONObject result = null; String str = null; try { str = new String(data, encoding); result = (JSONObject) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); AQUtility.debug(str); } return (T) result; } if (type.equals(JSONArray.class)) { JSONArray result = null; try { String str = new String(data, encoding); result = (JSONArray) new JSONTokener(str).nextValue(); } catch (Exception e) { AQUtility.debug(e); } return (T) result; } if (type.equals(String.class)) { String result = null; if (status.getSource() == AjaxStatus.NETWORK) { AQUtility.debug("network"); result = correctEncoding(data, encoding, status); } else { AQUtility.debug("file"); try { result = new String(data, encoding); } catch (Exception e) { AQUtility.debug(e); } } return (T) result; } /* * if(type.equals(XmlDom.class)){ XmlDom result = null; try { result = new XmlDom(data); } catch (Exception * e) { AQUtility.debug(e); } return (T) result; } */ if (type.equals(byte[].class)) { return (T) data; } if (transformer != null) { return transformer.transform(url, type, encoding, data, status); } if (st != null) { return st.transform(url, type, encoding, data, status); } } else if (file != null) { if (type.equals(File.class)) { return (T) file; } if (type.equals(XmlDom.class)) { XmlDom result = null; try { FileInputStream fis = new FileInputStream(file); result = new XmlDom(fis); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) result; } if (type.equals(XmlPullParser.class)) { XmlPullParser parser = Xml.newPullParser(); try { FileInputStream fis = new FileInputStream(file); parser.setInput(fis, encoding); status.closeLater(fis); } catch (Exception e) { AQUtility.report(e); return null; } return (T) parser; } if (type.equals(InputStream.class)) { try { FileInputStream fis = new FileInputStream(file); status.closeLater(fis); return (T) fis; } catch (Exception e) { AQUtility.report(e); return null; } } } return null; }