Example usage for android.app Activity getString

List of usage examples for android.app Activity getString

Introduction

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

Prototype

@NonNull
public final String getString(@StringRes int resId) 

Source Link

Document

Returns a localized string from the application's package's default string table.

Usage

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);
            }/*from  w  w w .ja  va2 s.co 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: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;//w  w  w .  jav a 2 s .  c o  m
                }
                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;

}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Check if the permissions provided in the list are granted.
 * This is an asynchronous method if permissions are requested, the final response
 * is provided in onRequestPermissionsResult(). In this case checkPermissions()
 * returns false.//from  w  ww.j a  v  a 2s.co m
 * <br>If checkPermissions() returns true, the permissions were already granted.
 * The permissions to be granted are given as bit map in aPermissionsToBeGrantedBitMap (ex: {@link #REQUEST_CODE_PERMISSION_TAKE_PHOTO}).
 * <br>aPermissionsToBeGrantedBitMap is passed as the request code in onRequestPermissionsResult().
 * <p>
 * If a permission was already denied by the user, a popup is displayed to
 * explain why vector needs the corresponding permission.
 *
 * @param aPermissionsToBeGrantedBitMap the permissions bit map to be granted
 * @param aCallingActivity              the calling Activity that is requesting the permissions
 * @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow)
 */
public static boolean checkPermissions(final int aPermissionsToBeGrantedBitMap,
        final Activity aCallingActivity) {
    boolean isPermissionGranted = false;

    // sanity check
    if (null == aCallingActivity) {
        Log.w(LOG_TAG, "## checkPermissions(): invalid input data");
        isPermissionGranted = false;
    } else if (REQUEST_CODE_PERMISSION_BY_PASS == aPermissionsToBeGrantedBitMap) {
        isPermissionGranted = true;
    } else if ((REQUEST_CODE_PERMISSION_TAKE_PHOTO != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_AUDIO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_VIDEO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBERS_SEARCH != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_HOME_ACTIVITY != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBER_DETAILS != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_ROOM_DETAILS != aPermissionsToBeGrantedBitMap)) {
        Log.w(LOG_TAG, "## checkPermissions(): permissions to be granted are not supported");
        isPermissionGranted = false;
    } else {
        List<String> permissionListAlreadyDenied = new ArrayList<>();
        List<String> permissionsListToBeGranted = new ArrayList<>();
        final List<String> finalPermissionsListToBeGranted;
        boolean isRequestPermissionRequired = false;
        Resources resource = aCallingActivity.getResources();
        String explanationMessage = "";
        String permissionType;

        // retrieve the permissions to be granted according to the request code bit map
        if (PERMISSION_CAMERA == (aPermissionsToBeGrantedBitMap & PERMISSION_CAMERA)) {
            permissionType = Manifest.permission.CAMERA;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_RECORD_AUDIO == (aPermissionsToBeGrantedBitMap & PERMISSION_RECORD_AUDIO)) {
            permissionType = Manifest.permission.RECORD_AUDIO;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_WRITE_EXTERNAL_STORAGE == (aPermissionsToBeGrantedBitMap
                & PERMISSION_WRITE_EXTERNAL_STORAGE)) {
            permissionType = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        // the contact book access is requested for any android platforms
        // for android M, we use the system preferences
        // for android < M, we use a dedicated settings
        if (PERMISSION_READ_CONTACTS == (aPermissionsToBeGrantedBitMap & PERMISSION_READ_CONTACTS)) {
            permissionType = Manifest.permission.READ_CONTACTS;

            if (Build.VERSION.SDK_INT >= 23) {
                isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                        permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
            } else {
                if (!ContactsManager.getInstance().isContactBookAccessRequested()) {
                    isRequestPermissionRequired = true;
                    permissionsListToBeGranted.add(permissionType);
                }
            }
        }

        finalPermissionsListToBeGranted = permissionsListToBeGranted;

        // if some permissions were already denied: display a dialog to the user before asking again..
        // if some permissions were already denied: display a dialog to the user before asking again..
        if (!permissionListAlreadyDenied.isEmpty()) {
            if (null != resource) {
                // add the user info text to be displayed to explain why the permission is required by the App
                if (aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_VIDEO_IP_CALL
                        || aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_AUDIO_IP_CALL) {
                    // Permission request for VOIP call
                    if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)
                            && permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Both missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_and_audio);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Audio missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio_explanation);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)) {
                        // Camera missing
                        explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_explanation);
                    }
                } else {
                    for (String permissionAlreadyDenied : permissionListAlreadyDenied) {
                        if (Manifest.permission.CAMERA.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        } else if (Manifest.permission.RECORD_AUDIO.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_record_audio);
                        } else if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_storage);
                        } else if (Manifest.permission.READ_CONTACTS.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_contacts);
                        } else {
                            Log.d(LOG_TAG, "## checkPermissions(): already denied permission not supported");
                        }
                    }
                }
            } else { // fall back if resource is null.. very unlikely
                explanationMessage = "You are about to be asked to grant permissions..\n\n";
            }

            // display the dialog with the info text
            AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
            if (null != resource) {
                permissionsInfoDialog.setTitle(resource.getString(R.string.permissions_rationale_popup_title));
            }

            permissionsInfoDialog.setMessage(explanationMessage);
            permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!finalPermissionsListToBeGranted.isEmpty()) {
                                ActivityCompat.requestPermissions(aCallingActivity,
                                        finalPermissionsListToBeGranted
                                                .toArray(new String[finalPermissionsListToBeGranted.size()]),
                                        aPermissionsToBeGrantedBitMap);
                            }
                        }
                    });

            Dialog dialog = permissionsInfoDialog.show();

            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    CommonActivityUtils.displayToast(aCallingActivity,
                            aCallingActivity.getString(R.string.missing_permissions_warning));
                }
            });

        } else {
            // some permissions are not granted, ask permissions
            if (isRequestPermissionRequired) {
                final String[] fPermissionsArrayToBeGranted = finalPermissionsListToBeGranted
                        .toArray(new String[finalPermissionsListToBeGranted.size()]);

                // for android < M, we use a custom dialog to request the contacts book access.
                if (permissionsListToBeGranted.contains(Manifest.permission.READ_CONTACTS)
                        && (Build.VERSION.SDK_INT < 23)) {
                    AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
                    permissionsInfoDialog.setIcon(android.R.drawable.ic_dialog_info);

                    if (null != resource) {
                        permissionsInfoDialog
                                .setTitle(resource.getString(R.string.permissions_rationale_popup_title));
                    }

                    permissionsInfoDialog.setMessage(
                            resource.getString(R.string.permissions_msg_contacts_warning_other_androids));

                    // gives the contacts book access
                    permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.yes),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(true);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    // or reject it
                    permissionsInfoDialog.setNegativeButton(aCallingActivity.getString(R.string.no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(false);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    permissionsInfoDialog.show();

                } else {
                    ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted,
                            aPermissionsToBeGrantedBitMap);
                }
            } else {
                // permissions were granted, start now..
                isPermissionGranted = true;
            }
        }
    }
    return isPermissionGranted;
}

From source file:org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Activity activity,
        final Action action) {

    switch (action) {

    case UPVOTE:// w ww.j  a  v a 2  s .co  m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.RedditAction.UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.RedditAction.HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        break;

    case DELETE:
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.DELETE);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.selftext));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        LinkHandler.getImageInfo(activity, post.url, Constants.Priority.IMAGE_VIEW, 0,
                new GetImageInfoListener() {

                    @Override
                    public void onFailure(final RequestFailureType type, final Throwable t,
                            final StatusLine status, final String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(activity, type, t, status,
                                post.url);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    public void onSuccess(final ImgurAPI.ImageInfo info) {

                        CacheManager.getInstance(activity)
                                .makeRequest(new CacheRequest(General.uriFromString(info.urlOriginal), anon,
                                        null, Constants.Priority.IMAGE_VIEW, 0,
                                        CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false,
                                        false, false, activity) {

                                    @Override
                                    protected void onCallbackException(Throwable t) {
                                        BugReportActivity.handleGlobalError(context, t);
                                    }

                                    @Override
                                    protected void onDownloadNecessary() {
                                        General.quickToast(context, R.string.download_downloading);
                                    }

                                    @Override
                                    protected void onDownloadStarted() {
                                    }

                                    @Override
                                    protected void onFailure(RequestFailureType type, Throwable t,
                                            StatusLine status, String readableMessage) {
                                        final RRError error = General.getGeneralErrorForFailure(context, type,
                                                t, status, url.toString());
                                        General.showResultDialog(activity, error);
                                    }

                                    @Override
                                    protected void onProgress(boolean authorizationInProgress, long bytesRead,
                                            long totalBytes) {
                                    }

                                    @Override
                                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile,
                                            long timestamp, UUID session, boolean fromCache, String mimetype) {

                                        File dst = new File(
                                                Environment.getExternalStoragePublicDirectory(
                                                        Environment.DIRECTORY_PICTURES),
                                                General.uriFromString(info.urlOriginal).getPath());

                                        if (dst.exists()) {
                                            int count = 0;

                                            while (dst.exists()) {
                                                count++;
                                                dst = new File(
                                                        Environment.getExternalStoragePublicDirectory(
                                                                Environment.DIRECTORY_PICTURES),
                                                        count + "_" + General.uriFromString(info.urlOriginal)
                                                                .getPath().substring(1));
                                            }
                                        }

                                        try {
                                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                                            if (cacheFileInputStream == null) {
                                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                                        "Could not find cached image");
                                                return;
                                            }

                                            General.copyFile(cacheFileInputStream, dst);

                                        } catch (IOException e) {
                                            notifyFailure(RequestFailureType.STORAGE, e, null,
                                                    "Could not copy file");
                                            return;
                                        }

                                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                Uri.parse("file://" + dst.getAbsolutePath())));

                                        General.quickToast(context,
                                                context.getString(R.string.action_save_image_success) + " "
                                                        + dst.getAbsolutePath());
                                    }
                                });

                    }

                    @Override
                    public void onNotAnImage() {
                        General.quickToast(activity, R.string.selected_link_is_not_image);
                    }
                });

        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.title);
        mailer.putExtra(Intent.EXTRA_TEXT, post.url);
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.url);
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity.getFragmentManager(), null);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((RedditPostView.PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

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  ww  w  . j a  v a  2s.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 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.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FTP);

    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // FTP; connect preferences here!
            ///*  w  w  w  .ja  va  2  s  .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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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) {

                                    }
                                }).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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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;
            }

            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.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

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

                        // Hide the progress bar
                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) 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, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP);

            // 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_ftp_host_succeeded_));

                }
            }, 0);

        }
    });

    t.start();

    return t;
}