Example usage for android.app Activity getResources

List of usage examples for android.app Activity getResources

Introduction

In this page you can find the example usage for android.app Activity getResources.

Prototype

@Override
    public Resources getResources() 

Source Link

Usage

From source file:ca.ualberta.trinkettrader.Inventory.Trinket.Pictures.Picture.java

/**
 * Creates a new picture from a file stored on the elasticsearch server.
 *
 * @param filename         filename of the picture stored on the server
 * @param directoryManager directory manager that can be used to store the picture
 * @param activity         android activity used to get the application's context
 *//*from ww w . ja  va 2 s  .  c  o m*/
public Picture(String filename, PictureDirectoryManager directoryManager, Activity activity)
        throws IOException, PackageManager.NameNotFoundException {
    this.directoryManager = directoryManager;
    this.filename = filename;
    // poitroae; http://stackoverflow.com/questions/8717333/converting-drawable-resource-image-into-bitmap; 2015-11-25
    Bitmap placeholder = BitmapFactory.decodeResource(activity.getResources(), R.drawable.placeholder);
    this.file = directoryManager.compressPicture(this.filename, placeholder);
    // \u00d3scar L\u00f3pez; http://stackoverflow.com/questions/8721262/how-to-get-file-size-in-java; 2015-11-04
    pictureByteArray = new byte[(int) this.file.length()];
    int result = 0;
    while (result == 0) {
        result = new FileInputStream(this.file).read(pictureByteArray);
    }
    this.observers = new HashSet<>();
}

From source file:com.nanostuffs.yurdriver.parse.MultiPartRequester.java

public MultiPartRequester(Activity activity, Map<String, String> map, int serviceCode,
        AsyncTaskCompleteListener asyncTaskCompleteListener) {
    this.map = map;
    this.serviceCode = serviceCode;
    this.activity = activity;

    // is Internet Connection Available...

    if (AndyUtils.isNetworkAvailable(activity)) {
        mAsynclistener = (AsyncTaskCompleteListener) asyncTaskCompleteListener;
        request = (AsyncHttpRequest) new AsyncHttpRequest().execute(map.get("url"));
    } else {/*  w w w  .  j av  a  2  s  .  c o m*/
        AndyUtils.showToast(activity.getResources().getString(R.string.toast_no_internet), activity);
    }

}

From source file:com.handlerexploit.news.fragments.WeatherFragment.java

private void render(WeatherInfo weatherInfo) {
    Activity activity = getActivity();
    if (activity != null && weatherInfo != null) {
        View root = getView();/*  w w  w.j a v a  2s .c om*/

        TextView city = (TextView) root.findViewById(R.id.city);
        city.setText(weatherInfo.getCity());

        CurrentWeather currentWeather = weatherInfo.getCurrentWeather();

        RemoteImageView icon = (RemoteImageView) root.findViewById(R.id.icon);
        int resId = activity.getResources().getIdentifier(currentWeather.getIcon(), "drawable",
                activity.getPackageName());
        if (resId != 0) {
            ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(resId);
            icon.setImageResource(resId);
        } else {
            ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(R.drawable.unknown);
            icon.setImageResource(R.drawable.unknown);
        }

        TextView temp = (TextView) root.findViewById(R.id.temp);
        temp.setText(currentWeather.getTempF() + " \u00B0F | " + currentWeather.getTempC() + " \u00B0C");
        ((TextView) activity.findViewById(R.id.weather_small_text))
                .setText(currentWeather.getTempF() + "\u00B0");

        TextView condition = (TextView) root.findViewById(R.id.condition);
        String conditionText = currentWeather.getCondition();
        if (conditionText != null && !conditionText.equals("")) {
            condition.setText(conditionText);
        } else {
            condition.setText("N/A");
        }

        TextView windCondition = (TextView) root.findViewById(R.id.windCondition);
        windCondition.setText(currentWeather.getWindCondition());

        TextView humidity = (TextView) root.findViewById(R.id.humidity);
        humidity.setText(currentWeather.getHumidity());

        LinearLayout forcastConditions = (LinearLayout) root.findViewById(R.id.forcastConditions);
        forcastConditions.removeAllViews();

        LayoutInflater inflater = LayoutInflater.from(activity);
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        params.weight = 1f;

        ArrayList<Condition> forcastArray = weatherInfo.getForcastConditions();
        for (int i = 0; i < forcastArray.size(); i++) {
            Condition forcastCondition = forcastArray.get(i);
            View forcastRoot = inflater.inflate(R.layout.fragment_weather_condition_item, null);

            TextView forcastDay = (TextView) forcastRoot.findViewById(R.id.day);
            forcastDay.setText(forcastCondition.getDay());

            RemoteImageView forcastIcon = (RemoteImageView) forcastRoot.findViewById(R.id.icon);
            int forcastResId = activity.getResources().getIdentifier(forcastCondition.getIcon(), "drawable",
                    activity.getPackageName());
            if (forcastResId != 0) {
                forcastIcon.setImageResource(forcastResId);
            } else {
                forcastIcon.setImageResource(R.drawable.unknown);
            }

            TextView forcastHigh = (TextView) forcastRoot.findViewById(R.id.high);
            forcastHigh.setText(forcastCondition.getHigh() + "\u00B0");

            TextView forcastLow = (TextView) forcastRoot.findViewById(R.id.low);
            forcastLow.setText(forcastCondition.getLow() + "\u00B0");

            forcastConditions.addView(forcastRoot, params);
        }
    }
}

From source file:com.google.plus.wigwamnow.social.GoogleProvider.java

/**
 * Initiate server-side authorization by sending a one time code to the server.
 *///from ww  w  .  j  ava  2s.  c o  m
@Override
public void hybridAuth(final Activity activity) {
    // Check that the activity has a PlusClient
    if (!(activity instanceof PlusClientHostActivity)) {
        throw new IllegalArgumentException("Activity must host a PlusClient!");
    }

    final PlusClientHostActivity clientHost = (PlusClientHostActivity) activity;

    // Create the hybrid authorization resources
    final String clientId = activity.getResources().getString(R.string.plus_client_id);
    final String[] activities = activity.getResources().getStringArray(R.array.visible_activities);
    final String[] scopes = activity.getResources().getStringArray(R.array.plus_scopes);
    final String scopeString = "oauth2:server:client_id:" + clientId + ":api_scope:"
            + TextUtils.join(" ", scopes);

    final Bundle appActivities = new Bundle();
    appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES, TextUtils.join(" ", activities));

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

        final Activity hostActivity = activity;

        @Override
        protected String doInBackground(Void... params) {
            try {
                return GoogleAuthUtil.getToken(hostActivity, clientHost.getPlusClient().getAccountName(),
                        scopeString, appActivities);
            } catch (IOException transientEx) {
                // Network or server error, try later
                Log.e(TAG, transientEx.toString(), transientEx);
                return null;
            } catch (UserRecoverableAuthException e) {
                // Recover (with e.getIntent())
                Log.e(TAG, e.toString(), e);
                Intent recover = e.getIntent();
                hostActivity.startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
            } catch (GoogleAuthException authEx) {
                // The call is not ever expected to succeed and should not be retried.
                Log.e(TAG, authEx.toString(), authEx);
                return null;
            } catch (Exception e) {
                Log.e(TAG, e.toString(), e);
                throw new RuntimeException(e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(String code) {
            Log.d(TAG, "Authorization code retrieved:" + code);
            if (code != null && !mPendingCodeSend) {
                mPendingCodeSend = true;
                initGoogleHybridFlow(code, hostActivity);
            }
        }

    };
    task.execute();

}

From source file:com.android.settings.profiles.ProfilesSettings.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // We don't call super.onActivityCreated() here, since it assumes we already set up
    // Preference (probably in onCreate()), while ProfilesSettings exceptionally set it up in
    // this method.
    // On/off switch
    Activity activity = getActivity();
    //Switch//from   w  ww  .  j  a  v a 2 s . c  om
    mActionBarSwitch = new Switch(activity);

    if (activity instanceof PreferenceActivity) {
        PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
        if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
            final int padding = activity.getResources()
                    .getDimensionPixelSize(R.dimen.action_bar_switch_padding);
            mActionBarSwitch.setPaddingRelative(0, 0, padding, 0);
            activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
                    ActionBar.DISPLAY_SHOW_CUSTOM);
            activity.getActionBar().setCustomView(mActionBarSwitch,
                    new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.END));
        }
    }

    mProfileEnabler = new ProfileEnabler(activity, mActionBarSwitch);

    // After confirming PreferenceScreen is available, we call super.
    super.onActivityCreated(savedInstanceState);
}

From source file:com.animedetour.android.main.DrawerController.java

public DrawerController(Activity activity, Monolog logger, FavoriteRepository favoriteData,
        DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes,
        View favoritesOption) {/* w  w w .  j  a  v a  2s .  c  o  m*/
    super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);

    this.toolbar = toolbar;
    this.logger = logger;
    this.layout = drawerLayout;
    this.favoriteData = favoriteData;
    this.favoritesOption = favoritesOption;
    this.resources = activity.getResources();
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static void showFeatureRequiresVuze(final Activity activity, final String feature) {
    activity.runOnUiThread(new Runnable() {
        public void run() {
            if (activity.isFinishing()) {
                if (DEBUG) {
                    System.out.println("can't display -- finishing");
                }/* www . j  a  va  2  s  .  c om*/
                return;
            }
            String msg = activity.getResources().getString(R.string.vuze_required, feature);
            Builder builder = new AlertDialog.Builder(activity).setMessage(msg).setCancelable(true)
                    .setPositiveButton(android.R.string.ok, new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
            builder.show();
        }
    });

}

From source file:com.smedic.tubtub.YouTubeSearch.java

public YouTubeSearch(Activity activity, Fragment playlistFragment) {
    this.activity = activity;
    this.playlistFragment = playlistFragment;
    handler = new Handler();
    credential = GoogleAccountCredential.usingOAuth2(activity.getApplicationContext(),
            Arrays.asList(Auth.SCOPES));
    credential.setBackOff(new ExponentialBackOff());
    appName = activity.getResources().getString(R.string.app_name);
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public static CharSequence readFile(Activity activity, int id) {
    BufferedReader in = null;// w w w.jav  a 2  s  .  co  m
    try {
        in = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
        String line;
        StringBuilder buffer = new StringBuilder();
        while ((line = in.readLine()) != null) {
            buffer.append(line).append('\n');
        }
        // Chomp the last newline
        buffer.deleteCharAt(buffer.length() - 1);
        return buffer;
    } catch (IOException e) {
        return "";
    } finally {
        closeStream(in);
    }
}

From source file:com.google.plus.wigwamnow.social.FacebookProvider.java

/**
 * Post a photo from a {@link Uri} to the user's WigwamNow album.
 *//*from  w  w  w. j  a v a2s .c  om*/
@Override
public boolean postPhoto(Uri photoUri, Activity activity) {
    final WigwamDetailActivity wda = (WigwamDetailActivity) activity;

    Session session = Session.getActiveSession();
    if (!hasPublishPermissions()) {
        requestPublishPermissions(session, activity);
        return false;
    }

    String postingPhotoString = activity.getResources().getString(R.string.posting_photo);
    showProgressDialog(postingPhotoString, activity);

    Request.Callback callback = new Request.Callback() {
        @Override
        public void onCompleted(Response response) {
            onPostActionResponse(response, wda);
        }
    };

    Bitmap bitmap = BitmapFactory.decodeFile(photoUri.getPath());
    Request request = Request.newUploadPhotoRequest(session, bitmap, callback);
    request.executeAsync();

    return true;
}