Example usage for android.widget ProgressBar setIndeterminate

List of usage examples for android.widget ProgressBar setIndeterminate

Introduction

In this page you can find the example usage for android.widget ProgressBar setIndeterminate.

Prototype

@android.view.RemotableViewMethod
public synchronized void setIndeterminate(boolean indeterminate) 

Source Link

Document

Change the indeterminate mode for this progress bar.

Usage

From source file:com.giovanniterlingen.windesheim.view.Adapters.NatschoolContentAdapter.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final TextView contentName = holder.contentName;
    final ImageView icon = holder.icon;
    final FrameLayout menuButton = holder.menuButton;
    final ImageView menuButtonImage = holder.menuButtonImage;
    contentName.setText(content.get(position).name);
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override/*from   w  ww.  ja va2 s  .  com*/
        public void onClick(View v) {
            onContentClick(content.get(holder.getAdapterPosition()), holder.getAdapterPosition());
        }
    });
    if (content.get(position).type == -1) {
        icon.setImageDrawable(ResourcesCompat.getDrawable(activity.getResources(),
                getDrawableByName(content.get(position).name), null));
        menuButton.setVisibility(View.VISIBLE);
        menuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuButtonImage.setImageDrawable(
                        ResourcesCompat.getDrawable(activity.getResources(), R.drawable.overflow_open, null));
                PopupMenu popupMenu = new PopupMenu(activity, menuButton);
                popupMenu.inflate(R.menu.menu_file);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        if (item.getItemId() == R.id.delete_file) {
                            showPromptDialog(holder.getAdapterPosition());
                            return true;
                        }
                        return true;
                    }
                });
                popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
                    @Override
                    public void onDismiss(PopupMenu menu) {
                        menuButtonImage.setImageDrawable(ResourcesCompat.getDrawable(activity.getResources(),
                                R.drawable.overflow_normal, null));
                    }
                });
                popupMenu.show();
            }
        });
    } else if (content.get(position).url == null || (content.get(position).url.length() == 0)) {
        if (content.get(position).imageUrl != null) {
            icon.setImageDrawable(
                    ResourcesCompat.getDrawable(activity.getResources(), R.drawable.ic_work, null));
        } else {
            icon.setImageDrawable(
                    ResourcesCompat.getDrawable(activity.getResources(), R.drawable.ic_folder, null));
        }
    } else {
        if (content.get(position).type == 1 || content.get(position).type == 3
                || content.get(position).type == 11) {
            icon.setImageDrawable(
                    ResourcesCompat.getDrawable(activity.getResources(), R.drawable.ic_link, null));
        } else if (content.get(position).type == 10) {
            icon.setImageDrawable(ResourcesCompat.getDrawable(activity.getResources(),
                    getDrawableByName(content.get(position).url), null));

            final TextView progressTextView = holder.progressTextView;
            final ProgressBar progressBar = holder.progressBar;
            final FrameLayout cancelButton = holder.cancelButton;

            if (content.get(position).downloading) {
                contentName.setVisibility(View.GONE);
                progressTextView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                if (content.get(position).progress == -1 && content.get(position).progressString == null) {
                    progressTextView.setText(activity.getResources().getString(R.string.downloading));
                    progressBar.setIndeterminate(true);
                } else {
                    progressTextView.setText(content.get(position).progressString);
                    progressBar.setIndeterminate(false);
                    progressBar.setMax(100);
                    progressBar.setProgress(content.get(position).progress);
                }
                cancelButton.setVisibility(View.VISIBLE);
                cancelButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NotificationCenter.getInstance().postNotificationName(
                                NotificationCenter.downloadCancelled,
                                content.get(holder.getAdapterPosition()).id);
                        contentName.setVisibility(View.VISIBLE);
                        progressTextView.setVisibility(View.GONE);
                        progressBar.setVisibility(View.GONE);
                        cancelButton.setVisibility(View.GONE);
                    }
                });
            } else {
                contentName.setVisibility(View.VISIBLE);
                progressTextView.setVisibility(View.GONE);
                progressBar.setVisibility(View.GONE);
                cancelButton.setVisibility(View.GONE);
            }
        }
    }
}

From source file:com.bluros.updater.UpdatesSettings.java

private void startDownload() {
    UpdateInfo ui = mDownloadingPreference.getUpdateInfo();
    if (ui == null) {
        return;//from w w  w  .j  a  v a  2 s  . com
    }

    mDownloadingPreference.setStyle(UpdatePreference.STYLE_DOWNLOADING);

    // Set progress bar to indeterminate while incremental check runs
    ProgressBar progressBar = mDownloadingPreference.getProgressBar();
    progressBar.setIndeterminate(true);

    // Disable cancel button while incremental check runs
    ImageView updatesButton = mDownloadingPreference.getUpdatesButton();
    updatesButton.setEnabled(false);

    mDownloadFileName = ui.getFileName();
    mDownloading = true;

    // Start the download
    Intent intent = new Intent(this, DownloadReceiver.class);
    intent.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
    intent.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) ui);
    sendBroadcast(intent);

    mUpdateHandler.post(mUpdateProgress);
}

From source file:org.alfresco.mobile.android.application.fragments.node.browser.ProgressNodeAdapter.java

@Override
protected void updateTopText(TwoLinesProgressViewHolder vh, Node item) {
    ProgressBar progressView = vh.progress;

    if (item instanceof NodePlaceHolder) {
        vh.topText.setText(item.getName());
        vh.topText.setEnabled(false);/*from ww w  .  ja va2 s.c o m*/
        long totalSize = ((NodePlaceHolder) item).getLength();

        if ((Integer) item.getPropertyValue(PublicAPIPropertyIds.REQUEST_STATUS) == Operation.STATUS_PAUSED
                || (Integer) item
                        .getPropertyValue(PublicAPIPropertyIds.REQUEST_STATUS) == Operation.STATUS_PENDING) {
            progressView.setVisibility(View.GONE);
        } else {
            progressView.setVisibility(View.VISIBLE);
            progressView.setIndeterminate(false);
            if (totalSize == -1) {
                progressView.setMax(MAX_PROGRESS);
                progressView.setProgress(0);
            } else {
                long progress = ((NodePlaceHolder) item).getProgress();
                float value = (((float) progress / ((float) totalSize)) * MAX_PROGRESS);
                int percentage = Math.round(value);

                if (percentage == MAX_PROGRESS) {
                    if ((Integer) item
                            .getPropertyValue(PublicAPIPropertyIds.REQUEST_TYPE) == DownloadRequest.TYPE_ID) {
                        progressView.setVisibility(View.GONE);
                        super.updateTopText(vh, item);
                        vh.bottomText.setVisibility(View.VISIBLE);
                        super.updateBottomText(vh, item);
                        super.updateIcon(vh, item);
                    } else {
                        progressView.setIndeterminate(true);
                    }
                } else {
                    progressView.setIndeterminate(false);
                    progressView.setMax(MAX_PROGRESS);
                    progressView.setProgress(percentage);
                }
            }
        }
    } else {
        progressView.setVisibility(View.GONE);
        super.updateTopText(vh, item);
    }
}

From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java

protected void createLocationPanelView(final IGISApplication app) {
    if (null == mGeometry && mFeatureId == NOT_FOUND) {
        mLatView = (TextView) findViewById(R.id.latitude_view);
        mLongView = (TextView) findViewById(R.id.longitude_view);
        mAltView = (TextView) findViewById(R.id.altitude_view);
        mAccView = (TextView) findViewById(R.id.accuracy_view);
        final ImageButton refreshLocation = (ImageButton) findViewById(R.id.refresh);
        mAccurateLocation = (SwitchCompat) findViewById(R.id.accurate_location);
        mAccurateLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override//from   w  w w. j a v a  2s . c o  m
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mAccurateLocation.getTag() == null) {
                    refreshLocation.performClick();
                    mAccurateLocation.setTag(new Object());
                }
            }
        });
        mAccuracyCE = (AppCompatSpinner) findViewById(R.id.accurate_ce);

        refreshLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f,
                        Animation.RELATIVE_TO_SELF, 0.5f);
                rotateAnimation.setDuration(500);
                rotateAnimation.setRepeatCount(1);
                refreshLocation.startAnimation(rotateAnimation);

                if (mAccurateLocation.isChecked()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ModifyAttributesActivity.this);
                    View layout = View.inflate(ModifyAttributesActivity.this,
                            R.layout.dialog_progress_accurate_location, null);
                    TextView message = (TextView) layout.findViewById(R.id.message);
                    final ProgressBar progress = (ProgressBar) layout.findViewById(R.id.progress);
                    final TextView progressPercent = (TextView) layout.findViewById(R.id.progress_percent);
                    final TextView progressNumber = (TextView) layout.findViewById(R.id.progress_number);
                    final CheckBox finishBeep = (CheckBox) layout.findViewById(R.id.finish_beep);
                    builder.setView(layout);
                    builder.setTitle(R.string.accurate_location);

                    final AccurateLocationTaker accurateLocation = new AccurateLocationTaker(view.getContext(),
                            100f, mMaxTakeCount, MAX_TAKE_TIME, PROGRESS_DELAY,
                            (String) mAccuracyCE.getSelectedItem());

                    progress.setIndeterminate(true);
                    message.setText(R.string.accurate_taking);
                    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            accurateLocation.cancelTaking();
                        }
                    });
                    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            accurateLocation.cancelTaking();
                        }
                    });
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            ControlHelper.unlockScreenOrientation(ModifyAttributesActivity.this);
                        }
                    });

                    final AlertDialog dialog = builder.create();
                    accurateLocation
                            .setOnProgressUpdateListener(new AccurateLocationTaker.OnProgressUpdateListener() {
                                @SuppressLint("SetTextI18n")
                                @Override
                                public void onProgressUpdate(Long... values) {
                                    int value = values[0].intValue();
                                    if (value == 1) {
                                        progress.setIndeterminate(false);
                                        progress.setMax(mMaxTakeCount);
                                    }

                                    if (value > 0)
                                        progress.setProgress(value);

                                    progressPercent.setText(value * 100 / mMaxTakeCount + " %");
                                    progressNumber.setText(value + " / " + mMaxTakeCount);
                                }
                            });

                    accurateLocation.setOnGetAccurateLocationListener(
                            new AccurateLocationTaker.OnGetAccurateLocationListener() {
                                @Override
                                public void onGetAccurateLocation(Location accurateLocation, Long... values) {
                                    dialog.dismiss();
                                    if (finishBeep.isChecked())
                                        playBeep();

                                    setLocationText(accurateLocation);
                                }
                            });

                    ControlHelper.lockScreenOrientation(ModifyAttributesActivity.this);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                    accurateLocation.startTaking();
                } else if (null != app) {
                    GpsEventSource gpsEventSource = app.getGpsEventSource();
                    Location location = gpsEventSource.getLastKnownLocation();
                    setLocationText(location);
                }
            }
        });
    } else {
        //hide location panel
        ViewGroup rootView = (ViewGroup) findViewById(R.id.controls_list);
        rootView.removeView(findViewById(R.id.location_panel));
    }
}

From source file:cm.aptoide.pt.ApkInfo.java

@SuppressLint("NewApi")
private void loadElements(long id) {
    viewComments = (ViewGroup) findViewById(R.id.commentContainer);
    viewComments.removeAllViews();//from   w w w  . j  a  va 2s.  c  o m
    viewLikes = (ViewGroup) findViewById(R.id.likesLayout);
    loading = LayoutInflater.from(context).inflate(R.layout.loadingfootercomments, null);
    viewComments.addView(loading, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    installString = getString(R.string.install);
    viewLikesButton = (ViewGroup) findViewById(R.id.ratings);
    ((TextView) viewLikes.findViewById(R.id.likes)).setText(context.getString(R.string.loading_likes));
    ((TextView) viewLikes.findViewById(R.id.dislikes)).setText("");

    findViewById(R.id.downloading_icon).setVisibility(View.GONE);
    findViewById(R.id.downloading_name).setVisibility(View.GONE);
    findViewById(R.id.download_progress).setVisibility(View.GONE);
    ProgressBar progress = (ProgressBar) findViewById(R.id.downloading_progress);
    progress.setIndeterminate(true);
    Bundle b = new Bundle();
    b.putLong("_id", id);

    //      findViewById(R.id.inst_version).setVisibility(View.VISIBLE);
    getSupportLoaderManager().restartLoader(20, b, new LoaderCallbacks<ViewApk>() {

        @Override
        public Loader<ViewApk> onCreateLoader(int arg0, final Bundle arg1) {
            pd.show();
            pd.setMessage(getString(R.string.please_wait));
            pd.setCancelable(false);
            return new ViewApkLoader(ApkInfo.this) {

                @Override
                public ViewApk loadInBackground() {
                    return db.getApk(arg1.getLong("_id"), category);
                }
            };

        }

        @Override
        public void onLoadFinished(Loader<ViewApk> arg0, ViewApk arg1) {
            //                AdView adView = (AdView)findViewById(R.id.adView);
            //                adView.loadAd(new AdRequest());

            mAdView = (MoPubView) findViewById(R.id.adview);
            mAdView.setAdUnitId(ApplicationAptoide.ADUNITID); // Enter your Ad Unit ID from www.mopub.com
            mAdView.loadAd();
            pd.dismiss();
            viewApk = arg1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    loadDescription();
                }
            }).start();

            mainObbUrl = viewApk.getMainObbUrl();
            mainObbMd5 = viewApk.getMainObbMd5();
            mainObbName = viewApk.getMainObbFileName();
            mainObbSize = viewApk.getMainObbFileSize();

            patchObbUrl = viewApk.getPatchObbUrl();
            patchObbMd5 = viewApk.getPatchObbMd5();
            patchObbName = viewApk.getPatchObbFileName();
            patchObbSize = viewApk.getPatchObbFileSize();

            if (viewApk.getLikes() != -1) {
                setLikes(viewApk.getLikes() + "", viewApk.getDislikes() + "");
            }

            if (viewApk.getComments().size() > 0) {
                setComments(viewApk.getComments());
                loading.setVisibility(View.GONE);
            }

            loadScreenshots();

            //viewApk.getWebservicePath

            int installedVercode = db.getInstalledAppVercode(viewApk.getApkid());

            if (installedVercode <= viewApk.getVercode() && installedVercode != 0) {
                findViewById(R.id.inst_version).setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.inst_version)).setText(getString(R.string.installed_version)
                        + ": " + db.getInstalledAppVername(viewApk.getApkid()));
                if (installedVercode < viewApk.getVercode() && !getIntent().hasExtra("installed")) {
                    installString = getString(R.string.update);
                } else if (getIntent().hasExtra("installed")) {
                    installString = getString(R.string.open);
                }
                ((Button) findViewById(R.id.btinstall)).setText(installString);

            } else if (installedVercode > viewApk.getVercode()) {
                if (getIntent().hasExtra("installed")) {
                    installString = getString(R.string.open);
                } else {
                    installString = getString(R.string.install);

                }
                ((Button) findViewById(R.id.btinstall)).setText(installString);

                findViewById(R.id.inst_version).setVisibility(View.GONE);
            }

            if (installedVercode == viewApk.getVercode()) {
                if (getIntent().hasExtra("installed")) {
                    installString = getString(R.string.open);
                } else {
                    installString = getString(R.string.install);
                }
                ((Button) findViewById(R.id.btinstall)).setText(installString);
                findViewById(R.id.inst_version).setVisibility(View.GONE);
            }

            repo_string = viewApk.getRepoName();
            checkDownloadStatus();
            webservicespath = viewApk.getWebservicesPath();

            try {
                ((RatingBar) findViewById(R.id.ratingbar)).setRating(Float.parseFloat(viewApk.getRating()));
                ((RatingBar) findViewById(R.id.ratingbar)).setIsIndicator(true);
            } catch (Exception e) {
                ((RatingBar) findViewById(R.id.ratingbar)).setRating(0);
                ((RatingBar) findViewById(R.id.ratingbar)).setIsIndicator(true);
            }
            ((TextView) findViewById(R.id.app_store)).setText(getString(R.string.store) + ": " + repo_string);
            ((TextView) findViewById(R.id.versionInfo)).setText(getString(R.string.clear_dwn_title) + ": "
                    + viewApk.getDownloads() + " " + getString(R.string.size) + ": "
                    + withSuffix((Long.parseLong(viewApk.getSize()) * 1024 + mainObbSize + patchObbSize)));
            ((TextView) findViewById(R.id.version_label))
                    .setText(getString(R.string.version) + " " + viewApk.getVername());
            ((TextView) findViewById(R.id.app_name)).setText(viewApk.getName());
            //            ImageLoader imageLoader = ImageLoader.getInstance(context);
            //            imageLoader.DisplayImage(viewApk.getIcon(),(ImageView) findViewById(R.id.app_icon), context, (viewApk.getApkid()+"|"+viewApk.getVercode()));
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .displayer(new FadeInBitmapDisplayer(1000))
                    .showStubImage(android.R.drawable.sym_def_app_icon).resetViewBeforeLoading().cacheInMemory()
                    .cacheOnDisc().build();
            ImageLoader.getInstance().displayImage(viewApk.getIcon(), (ImageView) findViewById(R.id.app_icon),
                    options, null, (viewApk.getApkid() + "|" + viewApk.getVercode()));

            new GetApkInfo().execute();

            /*Comments comments = new Comments(context,webservicespath);
            comments.getComments(repo_string, viewApk.getApkid(),viewApk.getVername(),(LinearLayout) findViewById(R.id.commentContainer), false);*/
            likes = new Likes(context, webservicespath);
            /*likes.getLikes(repo_string, viewApk.getApkid(), viewApk.getVername(),(ViewGroup) findViewById(R.id.likesLayout),(ViewGroup) findViewById(R.id.ratings));*/

            ItemBasedApks items = new ItemBasedApks(context, viewApk);
            items.getItems((LinearLayout) findViewById(R.id.itembasedapks_container),
                    (LinearLayout) findViewById(R.id.itembasedapks_maincontainer),
                    (TextView) findViewById(R.id.itembasedapks_label));

            if (!spinnerInstanciated) {
                loadApkVersions();
            }
            setClickListeners();

            //Malware badges
            loadMalwareBadges();
            if (Build.VERSION.SDK_INT >= 11) {
                invalidateOptionsMenu();
            }

            //                if(!getIntent().hasExtra("installed")){
            //                    new checkPaymentTask().execute();
            //                }

        }

        private void loadMalwareBadges() {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        loadMalware(viewApk.getMalwareStatus());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

        @Override
        public void onLoaderReset(Loader<ViewApk> arg0) {

        }
    });

    //

    //

    //      Button serch_mrkt = (Button)findViewById(R.id.btmarket);
    //      serch_mrkt.setOnClickListener(new OnClickListener() {
    //
    //         public void onClick(View v) {

    //         }
    //
    //      });

    //

    //
    //

}

From source file:org.quantumbadger.redreader.activities.ImageViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences);

    if (solidblack)
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

    final Intent intent = getIntent();

    mUrl = General.uriFromString(intent.getDataString());
    final RedditPost src_post = intent.getParcelableExtra("post");

    if (mUrl == null) {
        General.quickToast(this, "Invalid URL. Trying web browser.");
        revertToWeb();// w  ww.  j a  va2  s  .c  o  m
        return;
    }

    Log.i("ImageViewActivity", "Loading URL " + mUrl.toString());

    final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(progressBar);

    CacheManager.getInstance(this)
            .makeRequest(mRequest = new CacheRequest(mUrl, RedditAccountManager.getAnon(), null,
                    Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                    Constants.FileType.IMAGE, false, false, false, this) {

                private void setContentView(View v) {
                    layout.removeAllViews();
                    layout.addView(v);
                    v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                    v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                }

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

                @Override
                protected void onDownloadNecessary() {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(true);
                        }
                    });
                }

                @Override
                protected void onDownloadStarted() {
                }

                @Override
                protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status,
                        final String readableMessage) {

                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                            url.toString());

                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        public void run() {
                            // TODO handle properly
                            mRequest = null;
                            progressBar.setVisibility(View.GONE);
                            layout.addView(new ErrorView(ImageViewActivity.this, error));
                        }
                    });
                }

                @Override
                protected void onProgress(final boolean authorizationInProgress, final long bytesRead,
                        final long totalBytes) {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(authorizationInProgress);
                            progressBar.setProgress((int) ((100 * bytesRead) / totalBytes));
                        }
                    });
                }

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

                    if (mimetype == null
                            || (!Constants.Mime.isImage(mimetype) && !Constants.Mime.isVideo(mimetype))) {
                        revertToWeb();
                        return;
                    }

                    final InputStream cacheFileInputStream;
                    try {
                        cacheFileInputStream = cacheFile.getInputStream();
                    } catch (IOException e) {
                        notifyFailure(RequestFailureType.PARSE, e, null,
                                "Could not read existing cached image.");
                        return;
                    }

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

                    if (Constants.Mime.isVideo(mimetype)) {

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;

                                try {
                                    final RelativeLayout layout = new RelativeLayout(context);
                                    layout.setGravity(Gravity.CENTER);

                                    final VideoView videoView = new VideoView(ImageViewActivity.this);

                                    videoView.setVideoURI(cacheFile.getUri());
                                    layout.addView(videoView);
                                    setContentView(layout);

                                    layout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                                    layout.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                                    videoView.setLayoutParams(
                                            new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                    ViewGroup.LayoutParams.MATCH_PARENT));

                                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                        @Override
                                        public void onPrepared(MediaPlayer mp) {
                                            mp.setLooping(true);
                                            videoView.start();
                                        }
                                    });

                                    videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                        @Override
                                        public boolean onError(final MediaPlayer mediaPlayer, final int i,
                                                final int i1) {
                                            revertToWeb();
                                            return true;
                                        }
                                    });

                                    videoView.setOnTouchListener(new View.OnTouchListener() {
                                        @Override
                                        public boolean onTouch(final View view, final MotionEvent motionEvent) {
                                            finish();
                                            return true;
                                        }
                                    });

                                } catch (OutOfMemoryError e) {
                                    General.quickToast(context, R.string.imageview_oom);
                                    revertToWeb();

                                } catch (Throwable e) {
                                    General.quickToast(context, R.string.imageview_invalid_video);
                                    revertToWeb();
                                }
                            }
                        });

                    } else if (Constants.Mime.isImageGif(mimetype)) {

                        final PrefsUtility.GifViewMode gifViewMode = PrefsUtility
                                .pref_behaviour_gifview_mode(context, sharedPreferences);

                        if (gifViewMode == PrefsUtility.GifViewMode.INTERNAL_BROWSER) {
                            revertToWeb();
                            return;

                        } else if (gifViewMode == PrefsUtility.GifViewMode.EXTERNAL_BROWSER) {
                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                @Override
                                public void run() {
                                    LinkHandler.openWebBrowser(ImageViewActivity.this,
                                            Uri.parse(mUrl.toString()));
                                    finish();
                                }
                            });

                            return;
                        }

                        if (AndroidApi.isIceCreamSandwichOrLater()
                                && gifViewMode == PrefsUtility.GifViewMode.INTERNAL_MOVIE) {

                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                public void run() {

                                    if (mIsDestroyed)
                                        return;
                                    mRequest = null;

                                    try {
                                        final GIFView gifView = new GIFView(ImageViewActivity.this,
                                                cacheFileInputStream);
                                        setContentView(gifView);
                                        gifView.setOnClickListener(new View.OnClickListener() {
                                            public void onClick(View v) {
                                                finish();
                                            }
                                        });

                                    } catch (OutOfMemoryError e) {
                                        General.quickToast(context, R.string.imageview_oom);
                                        revertToWeb();

                                    } catch (Throwable e) {
                                        General.quickToast(context, R.string.imageview_invalid_gif);
                                        revertToWeb();
                                    }
                                }
                            });

                        } else {

                            gifThread = new GifDecoderThread(cacheFileInputStream,
                                    new GifDecoderThread.OnGifLoadedListener() {

                                        public void onGifLoaded() {
                                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                                public void run() {

                                                    if (mIsDestroyed)
                                                        return;
                                                    mRequest = null;

                                                    imageView = new ImageView(context);
                                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                                    setContentView(imageView);
                                                    gifThread.setView(imageView);

                                                    imageView.setOnClickListener(new View.OnClickListener() {
                                                        public void onClick(View v) {
                                                            finish();
                                                        }
                                                    });
                                                }
                                            });
                                        }

                                        public void onOutOfMemory() {
                                            General.quickToast(context, R.string.imageview_oom);
                                            revertToWeb();
                                        }

                                        public void onGifInvalid() {
                                            General.quickToast(context, R.string.imageview_invalid_gif);
                                            revertToWeb();
                                        }
                                    });

                            gifThread.start();

                        }

                    } else {

                        final ImageTileSource imageTileSource;
                        try {

                            final long bytes = cacheFile.getSize();
                            final byte[] buf = new byte[(int) bytes];

                            try {
                                new DataInputStream(cacheFileInputStream).readFully(buf);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                            try {
                                imageTileSource = new ImageTileSourceWholeBitmap(buf);

                            } catch (Throwable t) {
                                Log.e("ImageViewActivity", "Exception when creating ImageTileSource", t);
                                General.quickToast(context, R.string.imageview_decode_failed);
                                revertToWeb();
                                return;
                            }

                        } catch (OutOfMemoryError e) {
                            General.quickToast(context, R.string.imageview_oom);
                            revertToWeb();
                            return;
                        }

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;
                                mImageViewDisplayerManager = new ImageViewDisplayListManager(imageTileSource,
                                        ImageViewActivity.this);
                                surfaceView = new RRGLSurfaceView(ImageViewActivity.this,
                                        mImageViewDisplayerManager);
                                setContentView(surfaceView);

                                surfaceView.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        finish();
                                    }
                                });

                                if (mIsPaused) {
                                    surfaceView.onPause();
                                } else {
                                    surfaceView.onResume();
                                }
                            }
                        });
                    }
                }
            });

    final RedditPreparedPost post = src_post == null ? null
            : new RedditPreparedPost(this, CacheManager.getInstance(this), 0, src_post, -1, false, false, false,
                    false, RedditAccountManager.getInstance(this).getDefaultAccount(), false);

    final FrameLayout outerFrame = new FrameLayout(this);
    outerFrame.addView(layout);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(this);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(this,
                new BezelSwipeOverlay.BezelSwipeListener() {

                    public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) {

                        toolbarOverlay.setContents(
                                post.generateToolbar(ImageViewActivity.this, false, toolbarOverlay));
                        toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT
                                ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

    }

    setContentView(outerFrame);
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

private void uploadPhotoToServer(String file, final MsgGroups menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {
    try {//from  w w w .  j a  v  a  2 s  . com
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("image", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/photo", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("photos", photoArray);
                            menssage.fileName = photoArray.toString();
                            JSONArray targets = new JSONArray();
                            JSONArray contactos = new JSONArray(grupo.targets);
                            if (SpeakSocket.mSocket != null) {
                                if (SpeakSocket.mSocket.connected()) {
                                    for (int i = 0; i < contactos.length(); i++) {
                                        JSONObject contacto = contactos.getJSONObject(i);
                                        JSONObject newContact = new JSONObject();
                                        Contact contact = new Select().from(Contact.class)
                                                .where("id_contact = ?", contacto.getString("name"))
                                                .executeSingle();
                                        if (contact != null) {
                                            if (!contact.idContacto.equals(u.id)) {
                                                if (menssage.translation)
                                                    newContact.put("lang", contact.lang);
                                                else
                                                    newContact.put("lang", u.lang);
                                                newContact.put("name", contact.idContacto);
                                                newContact.put("screen_name", contact.screenName);
                                                newContact.put("status", 1);
                                                targets.put(targets.length(), newContact);
                                            }
                                        }
                                    }
                                    dataSend.put("targets", targets);
                                    menssage.receptores = targets.toString();
                                    SpeakSocket.mSocket.emit("message", dataSend);
                                } else {
                                    for (int i = 0; i < contactos.length(); i++) {
                                        JSONObject contacto = contactos.getJSONObject(i);
                                        JSONObject newContact = new JSONObject();
                                        Contact contact = new Select().from(Contact.class)
                                                .where("id_contact = ?", contacto.getString("name"))
                                                .executeSingle();
                                        if (contact != null) {
                                            if (!contact.idContacto.equals(u.id)) {
                                                if (menssage.translation)
                                                    newContact.put("lang", contact.lang);
                                                else
                                                    newContact.put("lang", u.lang);
                                                newContact.put("name", contact.idContacto);
                                                newContact.put("screen_name", contact.screenName);
                                                newContact.put("status", -1);
                                                targets.put(targets.length(), newContact);
                                            }
                                        }
                                    }
                                    menssage.receptores = targets.toString();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });
                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

private void uploadVideoToServer(String file, final MsgGroups menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {

    try {/*from   w w  w. j av a  2  s  . c  o  m*/
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("video", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });

        SpeakHttp.client.setTimeout(70000);
        SpeakHttp.client.setResponseTimeout(70000);
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/video", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("videos", photoArray);
                            menssage.fileName = photoArray.toString();
                            JSONArray targets = new JSONArray();
                            JSONArray contactos = new JSONArray(grupo.targets);
                            if (SpeakSocket.mSocket != null) {
                                if (SpeakSocket.mSocket.connected()) {
                                    for (int i = 0; i < contactos.length(); i++) {
                                        JSONObject contacto = contactos.getJSONObject(i);
                                        JSONObject newContact = new JSONObject();
                                        Contact contact = new Select().from(Contact.class)
                                                .where("id_contact = ?", contacto.getString("name"))
                                                .executeSingle();
                                        if (contact != null) {
                                            if (!contact.idContacto.equals(u.id)) {
                                                if (menssage.translation)
                                                    newContact.put("lang", contact.lang);
                                                else
                                                    newContact.put("lang", u.lang);
                                                newContact.put("name", contact.idContacto);
                                                newContact.put("screen_name", contact.screenName);
                                                newContact.put("status", 1);
                                                targets.put(targets.length(), newContact);
                                            }
                                        }
                                    }
                                    dataSend.put("targets", targets);
                                    menssage.receptores = targets.toString();
                                    SpeakSocket.mSocket.emit("message", dataSend);
                                } else {
                                    for (int i = 0; i < contactos.length(); i++) {
                                        JSONObject contacto = contactos.getJSONObject(i);
                                        JSONObject newContact = new JSONObject();
                                        Contact contact = new Select().from(Contact.class)
                                                .where("id_contact = ?", contacto.getString("name"))
                                                .executeSingle();
                                        if (contact != null) {
                                            if (!contact.idContacto.equals(u.id)) {
                                                if (menssage.translation)
                                                    newContact.put("lang", contact.lang);
                                                else
                                                    newContact.put("lang", u.lang);
                                                newContact.put("name", contact.idContacto);
                                                newContact.put("screen_name", contact.screenName);
                                                newContact.put("status", -1);
                                                targets.put(targets.length(), newContact);
                                            }
                                        }
                                    }
                                    menssage.receptores = targets.toString();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });

                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

private void uploadPhotoToServer(String file, final Message menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {
    try {/*from  w  w w  . j  av  a  2 s .c o  m*/
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("image", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/photo", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("photos", photoArray);
                            menssage.fileName = photoArray.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                menssage.status = 1;
                                SpeakSocket.mSocket.emit("message", dataSend);
                            } else {
                                menssage.status = -1;
                            }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });
                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                    Log.e("PROGRESO", (int) Math.round(prog) + "");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

private void uploadVideoToServer(String file, final Message menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {

    try {/*from  w  ww .  j a v a 2s .  c o  m*/
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("video", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });

        SpeakHttp.client.setTimeout(70000);
        SpeakHttp.client.setResponseTimeout(70000);
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/video", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("videos", photoArray);
                            menssage.fileName = photoArray.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                menssage.status = 1;
                                SpeakSocket.mSocket.emit("message", dataSend);
                            } else {
                                menssage.status = -1;
                            }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });

                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                    Log.e("PROGRESO", (int) Math.round(prog) + "");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}