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:com.zphinx.sortattributes.SortDialogManager.java

/**
 * Initializes and displays the alert dialog hosting the list of
 * StateTextView objects/*from  w  ww. j  a va2 s  .  com*/
 *
 * @param activity
 *            - The activity which uses this dialog
 */
public void showAlertDialog(final Activity activity) {
    String title = null;
    Log.d(TAG, "The alertDialog is: " + alertDialog);
    if (alertDialog == null) {
        Resources res = activity.getResources();
        String[] sortStrings = res.getStringArray(R.array.searchSortValues);
        title = "Sort Search Results";

        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);
        ListAdapter adapter = new SortAdapter(activity, R.layout.spinner_sort_list, sortStrings);

        builder.setSingleChoiceItems(adapter, -1, createItemListener(activity, adapter));

        alertDialog = builder.create();
        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting alert dialog icon

        alertDialog.setCancelable(true);
        alertDialog.setCanceledOnTouchOutside(true);

        // Setting OK Button
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", sortListener(adapter, activity));

    }
    alertDialog.setOwnerActivity(activity);

    // Showing Alert Message
    alertDialog.show();
}

From source file:org.docrj.smartcard.reader.NavDrawer.java

public NavDrawer(Activity activity, Bundle inState, int resId, DrawerLayout drawerLayout, Toolbar toolbar) {
    mActivity = activity;//  w  w w . j  ava 2  s.  c  o  m
    mResId = resId;
    mDrawerLayout = drawerLayout;

    // this only takes effect on Lollipop, or when using translucentStatusBar on Kitkat
    drawerLayout.setStatusBarBackgroundColor(activity.getResources().getColor(R.color.primary));
    mParentItem = drawerLayout.findViewById(resId);
    mParentItem.setActivated(true);

    mDrawerToggle = new ActionBarDrawerToggle(activity, drawerLayout, toolbar, R.string.app_name,
            R.string.app_name) {

        /** called when a drawer has settled in a completely closed state */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            // force call to onPrepareOptionsMenu()
            mActivity.invalidateOptionsMenu();
        }

        /** called when a drawer has settled in a completely open state */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // force call to onPrepareOptionsMenu()
            mActivity.invalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(mDrawerToggle);

    View appSelect = drawerLayout.findViewById(R.id.app_select);
    View batchSelect = drawerLayout.findViewById(R.id.batch_select);
    View emvRead = drawerLayout.findViewById(R.id.emv_read);
    View apps = drawerLayout.findViewById(R.id.apps);
    View settings = drawerLayout.findViewById(R.id.settings);

    appSelect.setOnClickListener(mClickListener);
    batchSelect.setOnClickListener(mClickListener);
    emvRead.setOnClickListener(mClickListener);
    apps.setOnClickListener(mClickListener);
    settings.setOnClickListener(mClickListener);

    if (inState != null) {
        if (inState.getBoolean("drawer_open")) {
            drawerLayout.openDrawer(Gravity.START | Gravity.LEFT);
        }
    }
}

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

/** 
 * Send the <code>access_token</code> to the server for authorization.
 *///from w  w  w .  j  a v a  2 s  .  c  om
@Override
public void hybridAuth(Activity activity) {
    String host = activity.getResources().getString(R.string.external_host);
    final String endpoint = host + "/auth/facebook/hybrid.json";
    // Send the Facebook access_token, which is portable, to the server alone with the Date
    // when it expires.
    String fbAccessToken = Session.getActiveSession().getAccessToken();
    Date fbAccessTokenExpires = Session.getActiveSession().getExpirationDate();
    JSONObject params = new JSONObject();
    try {
        params.put("access_token", fbAccessToken);
        params.put("expires_at", fbAccessTokenExpires.toString());
    } catch (JSONException e) {
        Log.e(TAG, "JSON Exception", e);
    }

    JsonObjectRequest jor = new JsonObjectRequest(com.android.volley.Request.Method.POST, endpoint, params,
            new com.android.volley.Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject json) {
                    Log.i(TAG, json.toString());
                }
            }, new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError e) {
                    Log.e(TAG, "FB Auth Error", e);
                }
            });
    WigwamNow.getQueue().add(jor);
}

From source file:com.connectutb.xfuel.FuelPlanner.java

public FuelPlanner(Activity context, String aircraft, String orig, String dest, boolean metar, String rules,
        String units, ProgressBar loading) {
    /* Assign variables */
    this.context = context;
    this.httppost = new HttpPost(context.getResources().getString(R.string.post_url));
    this.httpclient = new DefaultHttpClient();
    this.aircraft = aircraft;
    this.orig = orig;
    this.dest = dest;
    this.bMetar = metar;
    if (metar) {//  w w  w  .j av  a 2s  . c  o  m
        this.metar = "YES";
    } else {
        this.metar = "NO";
    }
    this.rules = rules;
    this.units = units;
    /** API license information */
    this.account = context.getString(R.string.account);
    this.license = context.getString(R.string.license);
    this.email = context.getString(R.string.email);

    this.loading = loading;

    settings = PreferenceManager.getDefaultSharedPreferences(context);
}

From source file:com.mikecorrigan.trainscorekeeper.Players.java

@SuppressLint("NewApi")
public Players(final Activity context, ViewGroup viewGroup, final JSONArray jsonPlayers) {
    Log.vc(VERBOSE, TAG,//from  w w w. j a  v a2s.c o m
            "ctor: context=" + context + ", viewGroup=" + viewGroup + ", jsonPlayers=" + jsonPlayers);

    viewGroup.removeAllViews();

    Resources resources = context.getResources();

    String[] playerNames = resources.getStringArray(R.array.playerNames);

    TypedArray drawablesArray = resources.obtainTypedArray(R.array.playerDrawables);

    TypedArray colorIdsArray = resources.obtainTypedArray(R.array.playerTextColors);
    int[] colorIds = new int[colorIdsArray.length()];
    for (int i = 0; i < colorIdsArray.length(); i++) {
        colorIds[i] = colorIdsArray.getResourceId(i, -1);
    }

    listeners = new HashSet<Listener>();
    players = new SparseArray<Player>();

    for (int i = 0; i < playerNames.length; i++) {
        PlayerButton toggleButton = new PlayerButton(context);
        toggleButton.setPlayerId(i);
        LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, 1f);
        toggleButton.setLayoutParams(layoutParams);
        Drawable drawable = drawablesArray.getDrawable(i);
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            toggleButton.setBackgroundDrawable(drawable);
        } else {
            toggleButton.setBackground(drawable);
        }
        toggleButton.setPadding(10, 10, 10, 10);
        toggleButton.setTextColor(resources.getColor(colorIds[i]));
        toggleButton.setOnClickListener(onSelect);

        viewGroup.addView(toggleButton);

        final String name = playerNames[i];

        boolean enabled = true;

        // If the players configuration is available, determine which players are enabled.
        if (jsonPlayers != null) {
            enabled = false;
            for (int j = 0; j < jsonPlayers.length(); j++) {
                String jsonName = jsonPlayers.optString(j, "");
                if (jsonName.equalsIgnoreCase(name)) {
                    enabled = true;
                    break;
                }
            }
        }

        Player player = new Player(toggleButton, i, name, enabled);
        players.put(i, player);
    }

    setSelection(-1);

    drawablesArray.recycle();
    colorIdsArray.recycle();
}

From source file:com.actionbarsherlock.ActionBarSherlock.java

/**
 * Wrap an activity with an action bar abstraction which will enable the
 * use of a custom implementation on platforms where a native version does
 * not exist./*from  ww w.j  a v  a2 s .c o  m*/
 *
 * @param activity Owning activity.
 * @param flags Option flags to control behavior.
 * @return Instance to interact with the action bar.
 */
public static ActionBarSherlock wrap(Activity activity, int flags) {
    //Create a local implementation map we can modify
    HashMap<Implementation, Class<? extends ActionBarSherlock>> impls = new HashMap<Implementation, Class<? extends ActionBarSherlock>>(
            IMPLEMENTATIONS);
    boolean hasQualfier;

    /* DPI FILTERING */
    hasQualfier = false;
    for (Implementation key : impls.keySet()) {
        //Only honor TVDPI as a specific qualifier
        if (key.dpi() == DisplayMetrics.DENSITY_TV) {
            hasQualfier = true;
            break;
        }
    }
    if (hasQualfier) {
        final boolean isTvDpi = activity.getResources()
                .getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
        for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext();) {
            int keyDpi = keys.next().dpi();
            if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
                    || (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
                keys.remove();
            }
        }
    }

    /* API FILTERING */
    hasQualfier = false;
    for (Implementation key : impls.keySet()) {
        if (key.api() != Implementation.DEFAULT_API) {
            hasQualfier = true;
            break;
        }
    }
    if (hasQualfier) {
        final int runtimeApi = Build.VERSION.SDK_INT;
        int bestApi = 0;
        for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext();) {
            int keyApi = keys.next().api();
            if (keyApi > runtimeApi) {
                keys.remove();
            } else if (keyApi > bestApi) {
                bestApi = keyApi;
            }
        }
        for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext();) {
            if (keys.next().api() != bestApi) {
                keys.remove();
            }
        }
    }

    if (impls.size() > 1) {
        throw new IllegalStateException("More than one implementation matches configuration.");
    }
    if (impls.isEmpty()) {
        throw new IllegalStateException("No implementations match configuration.");
    }
    Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
    if (DEBUG)
        Log.i(TAG, "Using implementation: " + impl.getSimpleName());

    try {
        Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
        return ctor.newInstance(activity, flags);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.level28.android.moca.ui.ItemListFragment.java

/**
 * Display a {@link Toast} after an exception occurred in background.
 * <p>/*from ww  w .j av a2 s .com*/
 * Subclasses may want to override this method to change the exception
 * reporting method.
 * 
 * @param exception
 *            the exception thrown by the loader
 * @param messageResId
 *            string resource id returned by
 *            {@link #getErrorMessage(Exception)}
 */
protected void showError(final Exception exception, final int messageResId) {
    final Activity activity = getActivity();
    final Application application = activity.getApplication();
    final String message = activity.getResources().getString(messageResId);

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(application, message, Toast.LENGTH_LONG).show();
        }
    });
}

From source file:com.andryr.musicplayer.fragments.ArtistFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mThumbWidth = activity.getResources().getDimensionPixelSize(R.dimen.art_thumbnail_size);
    mThumbHeight = mThumbWidth;//w w  w  .  ja  va2  s. c o  m
    try {
        mActivity = (MainActivity) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
    }
}

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

/**
 * This method takes a screenshot of the current screen automatically and opens the FeedbackActivity from the feedback library in case if a PUSH feedback is triggered.
 *
 * @param baseURL       the base URL//from   ww w . ja v  a 2  s  .c  o m
 * @param activity      the activity in which the method is called
 * @param applicationId the application id
 * @param language      the language
 */
public static void startActivityWithScreenshotCapture(@NonNull final String baseURL,
        @NonNull final Activity activity, final long applicationId, @NonNull final String language) {
    Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create())
            .build();
    feedbackAPI fbAPI = rtf.create(feedbackAPI.class);
    Call<ResponseBody> checkUpAndRunning = fbAPI.pingOrchestrator();

    if (checkUpAndRunning != null) {
        checkUpAndRunning.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "Failed to ping the server. onFailure method called", t);
                DialogUtils.showInformationDialog(activity,
                        new String[] { activity.getResources().getString(
                                R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                        true);
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    Intent intent = new Intent(activity, FeedbackActivity.class);
                    String defaultImagePath = Utils.captureScreenshot(activity);
                    intent.putExtra(FeedbackActivity.DEFAULT_IMAGE_PATH, defaultImagePath);
                    intent.putExtra(FeedbackActivity.EXTRA_KEY_APPLICATION_ID, applicationId);
                    intent.putExtra(FeedbackActivity.EXTRA_KEY_BASE_URL, baseURL);
                    intent.putExtra(FeedbackActivity.EXTRA_KEY_LANGUAGE, language);
                    activity.startActivity(intent);
                } else {
                    Log.e(TAG, "The server is not up and running. Response code == " + response.code());
                    DialogUtils.showInformationDialog(activity,
                            new String[] { activity.getResources().getString(
                                    R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                            true);
                }
            }
        });
    } else {
        Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null");
        DialogUtils.showInformationDialog(activity,
                new String[] { activity.getResources()
                        .getString(R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                true);
    }
}

From source file:com.midisheetmusicmemo.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *///from   w ww  .j  a  v a 2  s .  c  om
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        file.close();
        return data;
    } catch (Exception e) {
        return null;
    }
}