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:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

/**
 * This method opens the FeedbackActivity from the feedback library in case if a PULL feedback is triggered with a specific PULL configuration.
 *
 * @param baseURL                the base URL
 * @param activity               the activity in which the method is called
 * @param applicationId          the application id
 * @param language               the language
 * @param pullConfigurationId    the pull configuration id
 * @param intermediateDialogText the text to show in the intermediate dialog
 *///from   w  ww.j a  v  a  2s  .com
public static void triggerSpecificPullFeedback(@NonNull final String baseURL, @NonNull final Activity activity,
        final long applicationId, final @NonNull String language, final long pullConfigurationId,
        final @NonNull String intermediateDialogText) {
    Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create())
            .build();
    feedbackAPI fbAPI = rtf.create(feedbackAPI.class);
    final 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);
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL)
                            .addConverterFactory(GsonConverterFactory.create()).build();
                    feedbackAPI fbAPI = rtf.create(feedbackAPI.class);
                    Call<OrchestratorConfigurationItem> result = fbAPI.getConfiguration(language,
                            applicationId);

                    // Asynchronous call
                    if (result != null) {
                        result.enqueue(new Callback<OrchestratorConfigurationItem>() {
                            @Override
                            public void onFailure(Call<OrchestratorConfigurationItem> call, Throwable t) {
                                Log.e(TAG, "Failed to retrieve the configuration. 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<OrchestratorConfigurationItem> call,
                                    Response<OrchestratorConfigurationItem> response) {
                                if (response.code() == 200) {
                                    Log.i(TAG, "Configuration successfully retrieved");
                                    OrchestratorConfigurationItem configuration = response.body();
                                    if (configuration != null) {
                                        List<ConfigurationItem> configurationItems = configuration
                                                .getConfigurationItems();
                                        long[] selectedPullConfigurationIndex = { -1L };
                                        ConfigurationItem selectedConfigurationItem = null;
                                        for (ConfigurationItem configurationItem : configurationItems) {
                                            if (configurationItem.getType().equals("PULL")
                                                    && configurationItem.getId() == pullConfigurationId) {
                                                selectedPullConfigurationIndex[0] = configurationItem.getId();
                                                selectedConfigurationItem = configurationItem;
                                                break;
                                            }
                                        }

                                        if (selectedPullConfigurationIndex[0] != -1
                                                && selectedConfigurationItem != null) {
                                            // If no "showIntermediateDialog" is provided, show it
                                            boolean showIntermediateDialog = true;
                                            for (Map<String, Object> parameter : selectedConfigurationItem
                                                    .getGeneralConfigurationItem().getParameters()) {
                                                String key = (String) parameter.get("key");
                                                // Intermediate dialog
                                                if (key.equals("showIntermediateDialog")) {
                                                    showIntermediateDialog = (Utils.intToBool(
                                                            ((Double) parameter.get("value")).intValue()));
                                                }
                                            }

                                            Intent intent = new Intent(activity, FeedbackActivity.class);
                                            String jsonString = new Gson().toJson(configuration);
                                            intent.putExtra(FeedbackActivity.IS_PUSH_STRING, false);
                                            intent.putExtra(FeedbackActivity.JSON_CONFIGURATION_STRING,
                                                    jsonString);
                                            intent.putExtra(
                                                    FeedbackActivity.SELECTED_PULL_CONFIGURATION_INDEX_STRING,
                                                    selectedPullConfigurationIndex[0]);
                                            intent.putExtra(FeedbackActivity.EXTRA_KEY_BASE_URL, baseURL);
                                            intent.putExtra(FeedbackActivity.EXTRA_KEY_LANGUAGE, language);
                                            if (!showIntermediateDialog) {
                                                // Start the feedback activity without asking the user
                                                activity.startActivity(intent);
                                            } else {
                                                // Ask the user if (s)he would like to give feedback or not
                                                DialogUtils.PullFeedbackIntermediateDialog d = DialogUtils.PullFeedbackIntermediateDialog
                                                        .newInstance(intermediateDialogText, jsonString,
                                                                selectedPullConfigurationIndex[0], baseURL,
                                                                language);
                                                d.show(activity.getFragmentManager(), "feedbackPopupDialog");
                                            }
                                        } else {
                                            DialogUtils.showInformationDialog(activity,
                                                    new String[] { activity.getResources().getString(
                                                            R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                                                    true);
                                        }
                                    }
                                } else {
                                    Log.e(TAG, "Failed to retrieve the configuration. Response code == "
                                            + response.code());
                                }
                            }
                        });
                    } else {
                        Log.e(TAG,
                                "Failed to retrieve the configuration. Call<OrchestratorConfigurationItem> result is null");
                    }
                } else {
                    Log.e(TAG, "The server is not up and running. Response code == " + response.code());
                }
            }
        });
    } else {
        Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null");
    }
}

From source file:actionbartoggle.ActionBarToggle.java

/**
 * Construct a new ActionBarToggle./*from ww  w .j av a  2  s.  c  o m*/
 *
 * <p>The given {@link Activity} will be linked to the specified {@link DrawerLayout}.
 * The provided drawer indicator drawable will animate slightly off-screen as the drawer
 * is opened, indicating that in the open state the drawer will move off-screen when pressed
 * and in the closed state the drawer will move on-screen when pressed.</p>
 *
 * <p>String resources must be provided to describe the open/close drawer actions for
 * accessibility services.</p>
 *
 * @param activity The Activity hosting the drawer
 * @param layout The DrawerLayout to link to the given Activity's ActionBar
 * @param drawerImageRes A Drawable resource to use as the drawer indicator
 * @param openDrawerContentDescRes A String resource to describe the "open drawer" action
 *                                 for accessibility
 * @param closeDrawerContentDescRes A String resource to describe the "close drawer" action
 *                                  for accessibility
 */
public ActionBarToggle(Activity activity, ViewGroup layout, int drawerImageRes, int openDrawerContentDescRes,
        int closeDrawerContentDescRes) {
    mActivity = activity;

    // Allow the Activity to provide an impl
    if (activity instanceof DelegateProvider) {
        mActivityImpl = ((DelegateProvider) activity).getDrawerToggleDelegate();
    } else {
        mActivityImpl = null;
    }

    if (layout instanceof SlidingPaneLayout) {
        view_type = TYPE.Slider;
        mSlidingPaneLayout = (SlidingPaneLayout) layout;
        mDrawerLayout = null;
        mDrawerIndicatorEnabled = !mSlidingPaneLayout.isSlideable();
    } else if (layout instanceof DrawerLayout) {
        view_type = TYPE.Drawer;
        mSlidingPaneLayout = null;
        mDrawerLayout = (DrawerLayout) layout;
    } else {
        view_type = TYPE.View;
        mSlidingPaneLayout = null;
        mDrawerLayout = null;
    }

    mDrawerImageResource = drawerImageRes;
    mOpenDrawerContentDescRes = openDrawerContentDescRes;
    mCloseDrawerContentDescRes = closeDrawerContentDescRes;

    mThemeImage = getThemeUpIndicator();
    mDrawerImage = activity.getResources().getDrawable(drawerImageRes);
    mSlider = new SlideDrawable(mDrawerImage);
    mSlider.setOffsetBy(TOGGLE_DRAWABLE_OFFSET);
}

From source file:dev.dworks.libs.actionbartoggle.ActionBarToggle.java

/**
 * Construct a new ActionBarToggle./*from  w  w w.  ja v  a  2s.  co  m*/
 *
 * <p>The given {@link Activity} will be linked to the specified {@link DrawerLayout}.
 * The provided drawer indicator drawable will animate slightly off-screen as the drawer
 * is opened, indicating that in the open state the drawer will move off-screen when pressed
 * and in the closed state the drawer will move on-screen when pressed.</p>
 *
 * <p>String resources must be provided to describe the open/close drawer actions for
 * accessibility services.</p>
 *
 * @param activity The Activity hosting the drawer
 * @param layout The DrawerLayout to link to the given Activity's ActionBar
 * @param drawerImageRes A Drawable resource to use as the drawer indicator
 * @param openDrawerContentDescRes A String resource to describe the "open drawer" action
 *                                 for accessibility
 * @param closeDrawerContentDescRes A String resource to describe the "close drawer" action
 *                                  for accessibility
 */
public ActionBarToggle(Activity activity, ViewGroup layout, int drawerImageRes, int openDrawerContentDescRes,
        int closeDrawerContentDescRes) {
    mActivity = activity;

    // Allow the Activity to provide an impl
    if (activity instanceof ActionBarDrawerToggle.DelegateProvider) {
        mActivityImpl = ((ActionBarDrawerToggle.DelegateProvider) activity).getDrawerToggleDelegate();
    } else {
        mActivityImpl = null;
    }

    if (layout instanceof SlidingPaneLayout) {
        view_type = TYPE.Slider;
        mSlidingPaneLayout = (SlidingPaneLayout) layout;
        mDrawerLayout = null;
        mDrawerIndicatorEnabled = !mSlidingPaneLayout.isSlideable();
    } else if (layout instanceof DrawerLayout) {
        view_type = TYPE.Drawer;
        mSlidingPaneLayout = null;
        mDrawerLayout = (DrawerLayout) layout;
    } else {
        view_type = TYPE.View;
        mSlidingPaneLayout = null;
        mDrawerLayout = null;
    }

    mDrawerImageResource = drawerImageRes;
    mOpenDrawerContentDescRes = openDrawerContentDescRes;
    mCloseDrawerContentDescRes = closeDrawerContentDescRes;

    mThemeImage = getThemeUpIndicator();
    mDrawerImage = activity.getResources().getDrawable(drawerImageRes);
    mSlider = new SlideDrawable(mDrawerImage);
    mSlider.setOffsetBy(TOGGLE_DRAWABLE_OFFSET);
}

From source file:github.why168.swipeback.view.SwipeBackLayout.java

/**
 * ??/*  ww  w .j  a va 2 s .  c o m*/
 *
 * @param activity
 * @return
 */
public int getNavigationBarHeight(Activity activity) {
    int navigationBarHeight = 0;
    Resources resources = activity.getResources();
    int resourceId = resources
            .getIdentifier(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
                    ? "navigation_bar_height"
                    : "navigation_bar_height_landscape", "dimen", "android");
    if (resourceId > 0 && checkDeviceHasNavigationBar(activity)) {
        navigationBarHeight = resources.getDimensionPixelSize(resourceId);
    }
    return navigationBarHeight;
}

From source file:github.why168.swipeback.view.SwipeBackLayout.java

private boolean oldCheckDeviceHasNavigationBar(Activity activity) {
    boolean hasNavigationBar = false;
    Resources resources = activity.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = resources.getBoolean(id);
    }/*from  w  w  w  . j a v  a 2s . co m*/
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }//  ww  w . j a  v  a  2 s  .c  o  m

            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            totalLength = entity.getContentLength();

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((SSCXferActivity) activity).finishedUploading(false);

                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

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

public void openTorrent(final Activity activity, final String name, InputStream is) {
    try {//from ww w.ja va 2  s.  c  om
        int available = is.available();
        if (available <= 0) {
            available = 32 * 1024;
        }
        ByteArrayBuffer bab = new ByteArrayBuffer(available);

        boolean ok = AndroidUtils.readInputStreamIfStartWith(is, bab, new byte[] { 'd' });
        if (!ok) {
            String s;
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && bab.length() == 0) {
                s = activity.getResources().getString(R.string.not_torrent_file_kitkat, name);
            } else {
                s = activity.getResources().getString(R.string.not_torrent_file, name,
                        Math.max(bab.length(), 5));
            }
            AndroidUtils.showDialog(activity, R.string.add_torrent, Html.fromHtml(s));
            return;
        }
        final String metainfo = Base64Encode.encodeToString(bab.buffer(), 0, bab.length());
        openTorrentWithMetaData(activity, name, metainfo);
    } catch (IOException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
    } catch (OutOfMemoryError em) {
        VuzeEasyTracker.getInstance(activity).logError(em);
        AndroidUtils.showConnectionError(activity, "Out of Memory", true);
    }
}

From source file:com.leavjenn.smoothdaterangepicker.date.SmoothDateRangePickerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //        Log.d(TAG, "onCreateView: ");
    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    View view = inflater.inflate(R.layout.sdrp_dialog, container);

    mDayOfWeekView = (TextView) view.findViewById(R.id.date_picker_header);
    mDayOfWeekViewEnd = (TextView) view.findViewById(R.id.date_picker_header_end);
    mMonthAndDayView = (LinearLayout) view.findViewById(R.id.date_picker_month_and_day);
    mMonthAndDayViewEnd = (LinearLayout) view.findViewById(R.id.date_picker_month_and_day_end);
    mMonthAndDayView.setOnClickListener(this);
    mMonthAndDayViewEnd.setOnClickListener(this);

    mSelectedMonthTextView = (TextView) view.findViewById(R.id.date_picker_month);
    mSelectedMonthTextViewEnd = (TextView) view.findViewById(R.id.date_picker_month_end);

    mSelectedDayTextView = (TextView) view.findViewById(R.id.date_picker_day);
    mSelectedDayTextViewEnd = (TextView) view.findViewById(R.id.date_picker_day_end);

    mYearView = (TextView) view.findViewById(R.id.date_picker_year);
    mYearViewEnd = (TextView) view.findViewById(R.id.date_picker_year_end);
    mYearView.setOnClickListener(this);
    mYearViewEnd.setOnClickListener(this);

    mDurationView = (LinearLayout) view.findViewById(R.id.date_picker_duration_layout);
    mDurationView.setOnClickListener(this);
    mDurationTextView = (TextView) view.findViewById(R.id.date_picker_duration_days);
    mDurationEditText = (EditText) view.findViewById(R.id.date_picker_duration_days_et);
    // disable soft keyboard popup when edittext is selected
    mDurationEditText.setRawInputType(InputType.TYPE_CLASS_TEXT);
    mDurationEditText.setTextIsSelectable(true);
    mDurationDayTextView = (TextView) view.findViewById(R.id.tv_duration_day);
    mDurationArrow = (TextView) view.findViewById(R.id.arrow_start);
    mDurationArrow.setOnClickListener(this);
    mDurationArrowEnd = (TextView) view.findViewById(R.id.arrow_end);
    mDurationArrowEnd.setOnClickListener(this);

    viewList = new ArrayList<>();
    viewList.add(MONTH_AND_DAY_VIEW, mMonthAndDayView);
    viewList.add(YEAR_VIEW, mYearView);//  www . j  av a2 s  .com
    viewList.add(MONTH_AND_DAY_VIEW_END, mMonthAndDayViewEnd);
    viewList.add(YEAR_VIEW_END, mYearViewEnd);
    viewList.add(DURATION_VIEW, mDurationView);

    int listPosition = -1;
    int listPositionOffset = 0;
    int listPositionEnd = -1;
    int listPositionOffsetEnd = 0;
    int currentView = MONTH_AND_DAY_VIEW;
    if (savedInstanceState != null) {
        mWeekStart = savedInstanceState.getInt(KEY_WEEK_START);
        mMinYear = savedInstanceState.getInt(KEY_YEAR_START);
        mMaxYear = savedInstanceState.getInt(KEY_YEAR_END);
        currentView = savedInstanceState.getInt(KEY_CURRENT_VIEW);
        listPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
        listPositionOffset = savedInstanceState.getInt(KEY_LIST_POSITION_OFFSET);
        listPositionEnd = savedInstanceState.getInt(KEY_LIST_POSITION_END);
        listPositionOffsetEnd = savedInstanceState.getInt(KEY_LIST_POSITION_OFFSET_END);
        mMinDate = (Calendar) savedInstanceState.getSerializable(KEY_MIN_DATE);
        mMaxDate = (Calendar) savedInstanceState.getSerializable(KEY_MAX_DATE);
        mMinSelectableDate = (Calendar) savedInstanceState.getSerializable(KEY_MIN_DATE_SELECTABLE);
        highlightedDays = (Calendar[]) savedInstanceState.getSerializable(KEY_HIGHLIGHTED_DAYS);
        selectableDays = (Calendar[]) savedInstanceState.getSerializable(KEY_SELECTABLE_DAYS);
        mThemeDark = savedInstanceState.getBoolean(KEY_THEME_DARK);
        mAccentColor = savedInstanceState.getInt(KEY_ACCENT);
        mVibrate = savedInstanceState.getBoolean(KEY_VIBRATE);
        mDismissOnPause = savedInstanceState.getBoolean(KEY_DISMISS);
    }

    final Activity activity = getActivity();
    mDayPickerView = new SimpleDayPickerView(activity, this);
    mYearPickerView = new YearPickerView(activity, this);
    mDayPickerViewEnd = new SimpleDayPickerView(activity, this);
    mYearPickerViewEnd = new YearPickerView(activity, this);
    mNumberPadView = new NumberPadView(activity, this);

    Resources res = getResources();
    mDayPickerDescription = res.getString(R.string.mdtp_day_picker_description);
    mSelectDay = res.getString(R.string.mdtp_select_day);
    mYearPickerDescription = res.getString(R.string.mdtp_year_picker_description);
    mSelectYear = res.getString(R.string.mdtp_select_year);

    int bgColorResource = mThemeDark ? R.color.mdtp_date_picker_view_animator_dark_theme
            : R.color.mdtp_date_picker_view_animator;
    view.setBackgroundColor(activity.getResources().getColor(bgColorResource));

    if (mThemeDark) {
        view.findViewById(R.id.hyphen).setBackgroundColor(
                activity.getResources().getColor(R.color.date_picker_selector_unselected_dark_theme));
        Utils.setMultiTextColorList(activity.getResources().getColorStateList(R.color.sdrp_selector_dark),
                mDayOfWeekView, mDayOfWeekViewEnd, mSelectedMonthTextView, mSelectedMonthTextViewEnd,
                mSelectedDayTextView, mSelectedDayTextViewEnd, mYearView, mYearViewEnd, mDurationTextView,
                mDurationDayTextView, mDurationArrow, mDurationArrowEnd, mDurationEditText,
                (TextView) view.findViewById(R.id.tv_duration));
    }

    mAnimator = (AccessibleDateAnimator) view.findViewById(R.id.animator);

    mAnimator.addView(mDayPickerView);
    mAnimator.addView(mYearPickerView);
    mAnimator.addView(mDayPickerViewEnd);
    mAnimator.addView(mYearPickerViewEnd);
    mAnimator.addView(mNumberPadView);
    mAnimator.setDateMillis(mCalendar.getTimeInMillis());
    Animation animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(ANIMATION_DURATION);
    mAnimator.setInAnimation(animation);
    Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
    animation2.setDuration(ANIMATION_DURATION);
    mAnimator.setOutAnimation(animation2);

    Button okButton = (Button) view.findViewById(R.id.ok);
    okButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            tryVibrate();
            if (mCallBack != null) {
                mCallBack.onDateRangeSet(SmoothDateRangePickerFragment.this, mCalendar.get(Calendar.YEAR),
                        mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH),
                        mCalendarEnd.get(Calendar.YEAR), mCalendarEnd.get(Calendar.MONTH),
                        mCalendarEnd.get(Calendar.DAY_OF_MONTH));
            }
            dismiss();
        }
    });
    okButton.setTypeface(TypefaceHelper.get(activity, "Roboto-Medium"));

    Button cancelButton = (Button) view.findViewById(R.id.cancel);
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tryVibrate();
            if (getDialog() != null)
                getDialog().cancel();
        }
    });
    cancelButton.setTypeface(TypefaceHelper.get(activity, "Roboto-Medium"));
    cancelButton.setVisibility(isCancelable() ? View.VISIBLE : View.GONE);

    //If an accent color has not been set manually, try and get it from the context
    if (mAccentColor == -1) {
        int accentColor = Utils.getAccentColorFromThemeIfAvailable(getActivity());
        if (accentColor != -1) {
            mAccentColor = accentColor;
        }
    }
    if (mAccentColor != -1) {
        if (mDayOfWeekView != null)
            mDayOfWeekView.setBackgroundColor(mAccentColor);
        if (mDayOfWeekViewEnd != null)
            mDayOfWeekViewEnd.setBackgroundColor(mAccentColor);

        view.findViewById(R.id.layout_container).setBackgroundColor(mAccentColor);
        view.findViewById(R.id.day_picker_selected_date_layout).setBackgroundColor(mAccentColor);
        view.findViewById(R.id.day_picker_selected_date_layout_end).setBackgroundColor(mAccentColor);
        mDurationView.setBackgroundColor(mAccentColor);
        mDurationEditText.setHighlightColor(Utils.darkenColor(mAccentColor));
        mDurationEditText.getBackground().setColorFilter(Utils.darkenColor(mAccentColor),
                PorterDuff.Mode.SRC_ATOP);
        okButton.setTextColor(mAccentColor);
        cancelButton.setTextColor(mAccentColor);
        mYearPickerView.setAccentColor(mAccentColor);
        mDayPickerView.setAccentColor(mAccentColor);
        mYearPickerViewEnd.setAccentColor(mAccentColor);
        mDayPickerViewEnd.setAccentColor(mAccentColor);
    }

    updateDisplay(false);
    setCurrentView(currentView);

    if (listPosition != -1) {
        if (currentView == MONTH_AND_DAY_VIEW) {
            mDayPickerView.postSetSelection(listPosition);
        } else if (currentView == YEAR_VIEW) {
            mYearPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        }
    }

    if (listPositionEnd != -1) {
        if (currentView == MONTH_AND_DAY_VIEW_END) {
            mDayPickerViewEnd.postSetSelection(listPositionEnd);
        } else if (currentView == YEAR_VIEW_END) {
            mYearPickerViewEnd.postSetSelectionFromTop(listPositionEnd, listPositionOffsetEnd);
        }
    }

    mHapticFeedbackController = new HapticFeedbackController(activity);

    return view;
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToFTPserver(final Activity activity, final Handler handler,
        final String latestVideoFile_filename, final String latestVideoFile_absolutepath,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doVideoFTP starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();

    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // FTP; connect preferences here!
            ////from  w w  w.j  ava2s  .  c  om
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
            String ftpHostName = prefs.getString("defaultFTPhostPreference", null);
            String ftpUsername = prefs.getString("defaultFTPusernamePreference", null);
            String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null);

            // use name of local file.
            String ftpRemoteFtpFilename = latestVideoFile_filename;

            // FTP
            FTPClient ftpClient = new FTPClient();
            InetAddress uploadhost = null;
            try {

                uploadhost = InetAddress.getByName(ftpHostName);
            } catch (UnknownHostException e1) {
                // If DNS resolution fails then abort immediately - show
                // dialog to
                // inform user first.
                e1.printStackTrace();
                Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed.");
                uploadhost = null;
            }

            if (uploadhost == null) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean connected = false;

            try {
                ftpClient.connect(uploadhost);
                connected = true;

            } catch (SocketException e) {
                e.printStackTrace();
                connected = false;

            } catch (UnknownHostException e) {
                //
                e.printStackTrace();
                connected = false;
            } catch (IOException e) {
                //
                e.printStackTrace();
                connected = false;
            }

            if (!connected) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean reply = false;
            try {

                reply = ftpClient.login(ftpUsername, ftpPassword);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp.login - video uploading failed.");
            }

            // check the reply code here
            // If we cant login, abort after showing user a dialog.
            if (!reply) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    //
                    e.printStackTrace();
                }

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();
                    }
                }, 0);

                return;
            }

            // Set File type to binary
            try {
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (IOException e) {
                //
                e.printStackTrace();
                // keep going?!
            }

            // BEYOND HERE DONT USE DIALOGS!

            // Construct the input stream to send to Ftp server, from the
            // local
            // video file on the sd card
            BufferedInputStream buffIn = null;
            File file = new File(latestVideoFile_absolutepath);

            try {
                buffIn = new BufferedInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on local video file - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                return;
            }

            ftpClient.enterLocalPassiveMode();

            try {
                // UPLOAD THE LOCAL VIDEO FILE.
                ftpClient.storeFile(ftpRemoteFtpFilename, buffIn);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on storeFile - video uploading failed.");

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                buffIn.close();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on buff.close - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.logout();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp logout - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp disconnect - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }

            if (emailAddress != null && ftpHostName != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_));

                }
            }, 0);

        }
    });

    t.start();

    return t;
}

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

public Thread videoUploadToFacebook(final Activity activity, final Handler handler, final Facebook mFacebook,
        final String path, final String title, final String description, final String emailAddress,
        final long sdrecord_id) {

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // Track errors
            boolean failed = false;

            Log.i(TAG, "Upload starting");
            // Initialising REST API video.upload parameters
            Bundle params = new Bundle();

            params.putString("method", "facebook.video.upload");
            params.putString("format", "json");
            params.putString("title", title);
            params.putString("description", description);
            params.putString("call_id", String.valueOf(System.currentTimeMillis()));
            params.putString("v", "1.0");
            params.putString("oauth_token", mFacebook.getAccessToken());

            // Reading input file
            try {
                File videoFile = new File(path);
                byte[] data = null;
                try {

                    // XXX
                    // SPLIT THIS INTO 5K chunks!!
                    // XXX

                    data = new byte[(int) videoFile.length()];
                } catch (OutOfMemoryError e) {
                    failed = true;//from  ww w .  j  a  v a2s.com
                }
                if (data != null) {
                    InputStream is = new FileInputStream(videoFile);
                    is.read(data);
                    params.putByteArray(videoFile.getName(), data);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Cannot read video file :", ex);
            }

            // Sending POST request to Facebook
            String response = null;
            String url = "https://api-video.facebook.com/restserver.php";

            try {
                if (!failed) {
                    response = Util.openUrl(url, "POST", params);
                }
                // SessionEvents.onUploadComplete(response);
            } catch (FileNotFoundException e) {
                // SessionEvents.onFileNotFoundException(e);
                failed = true;
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // SessionEvents.onMalformedURLException(e);
                failed = true;
                e.printStackTrace();
            } catch (IOException e) {
                // SessionEvents.onIOException(e);
                failed = true;
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                failed = true;
                e.printStackTrace();
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

                return;
            }

            Log.i(TAG, "Uploading to facebook complete. Response is " + response);

            // response is JSON
            JSONObject fb_response = null;
            // decode, and grab URL
            try {
                fb_response = (JSONObject) new JSONTokener(response).nextValue();
            } catch (JSONException e) {
                //
                e.printStackTrace();
                fb_response = null;
            }
            String hosted_url = "facebook.com";

            if (fb_response != null) {

                try {
                    hosted_url = fb_response.getString("link");
                    Log.i(TAG, "Facebook hosted url is : " + hosted_url);
                } catch (JSONException e) {
                    //
                    e.printStackTrace();
                    hosted_url = null;
                }

                if (hosted_url != null) {
                    // Log record of this URL in POSTs table
                    dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, url, hosted_url, "");

                    mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                    // Use the handler to execute a Runnable on the
                    // main thread in order to have access to the
                    // UI elements.
                    handler.postDelayed(new Runnable() {

                        public void run() {
                            // Update UI

                            // Indicate back to calling activity the result!
                            // update uploadInProgress state also.

                            ((VidiomActivity) activity).finishedUploading(true);
                            ((VidiomActivity) activity)
                                    .createNotification(res.getString(R.string.upload_to_facebook_succeeded_));

                        }
                    }, 0);
                }

            } else {

                // an error -- fb_response is NULL.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

            }

            if (emailAddress != null && fb_response != null && hosted_url != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + hosted_url, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

        }
    });

    t.start();

    return t;

}