Example usage for android.webkit WebView loadUrl

List of usage examples for android.webkit WebView loadUrl

Introduction

In this page you can find the example usage for android.webkit WebView loadUrl.

Prototype

public void loadUrl(String url) 

Source Link

Document

Loads the given URL.

Usage

From source file:com.appnexus.opensdk.MRAIDImplementation.java

WebViewClient getWebViewClient() {

    return new WebViewClient() {

        @Override//from   ww  w. j av  a2  s  . c o m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.startsWith("mraid:") && !url.startsWith("javascript:")) {
                Intent intent;
                if (owner.owner.getOpensNativeBrowser()) {
                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                } else {
                    intent = new Intent(owner.getContext(), BrowserActivity.class);
                    intent.putExtra("url", url);
                }
                try {
                    owner.getContext().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Clog.w(Clog.mraidLogTag, Clog.getString(R.string.opening_url_failed, url));
                }
                return true;
            } else if (url.startsWith("mraid://")) {
                MRAIDImplementation.this.dispatch_mraid_call(url);

                return true;
            }

            // See if any native activities can handle the Url
            try {
                owner.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                // If it's an IAV, prevent it from closing
                if (owner.owner instanceof InterstitialAdView) {
                    ((InterstitialAdView) (owner.owner)).interacted();
                }
                return true;
            } catch (ActivityNotFoundException e) {
                return false;
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            Clog.e(Clog.httpRespLogTag,
                    Clog.getString(R.string.webclient_error, error.getPrimaryError(), error.toString()));
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingURL) {
            Clog.e(Clog.httpRespLogTag, Clog.getString(R.string.webclient_error, errorCode, description));
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // Fire the ready event only once
            if (!readyFired) {
                view.loadUrl(String.format("javascript:window.mraid.util.setPlacementType('%s')",
                        owner.owner.isBanner() ? "inline" : "interstitial"));
                view.loadUrl("javascript:window.mraid.util.setIsViewable(true)");
                view.loadUrl("javascript:window.mraid.util.stateChangeEvent('default')");
                view.loadUrl("javascript:window.mraid.util.readyEvent();");

                // Store width and height for close()
                default_width = owner.getLayoutParams().width;
                default_height = owner.getLayoutParams().height;

                readyFired = true;
            }
        }
    };
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

/**
 * after received the JS's openWin and communicate message
 * Will convert message to target window with source reference 
 * And will delegate communication message in local
 * Local method for C->JS//ww  w  . j  a v  a2s  .c  o  m
 * @param target original target value in invoke the method ubiGCPlayerCommunicate.
 * @param source come from the source target win,is used by the source parameter in invoking javascript:ubiGCPlayerDelegate..
 * @param jsonData
 */
public void ubiGCPlayerDelegate(final String target, String source, final String jsonData) {
    final String strUrl = "javascript:ubiGCPlayerDelegate('" + source + "','" + jsonData + "')";
    ((Activity) this.mContext).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (target.equalsIgnoreCase(MULTI_TAB_WIN_MAIN)) {//if come from main win,it will using  main webview object
                mWebView.loadUrl(strUrl);
            } else {//else if come from sub win ,it will find the current sub win obj in loop list and using it.
                if (mChildWebviewLst != null && mChildWebviewLst.size() > 0) {
                    WebView subWebviewObj = mChildWebviewLst.get(0);
                    if (subWebviewObj != null) {
                        subWebviewObj.loadUrl(strUrl);
                    }
                }
            }
        }
    });
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

/**
 * release the webview url/*from w w  w. ja va  2  s  . c om*/
 */
public void reload(String reloadUrl) {
    if (!sBCurrentActivityStatus) {
        return;
    }
    DebugLog.d(TAG, "0829 reload() enter");
    int size = mChildViewList.size();
    if (size > 1) {
        for (int i = 0; i < (size - 1); i++) {
            WebView child = (WebView) mChildViewList.get(i).findViewById(GameActivityRes.ID_CHILD_WEBVIEW);
            if (child.getTag() != null) {
                child.loadUrl(child.getTag().toString());
                child.setTag(null);
            } else {
                child.reload();
            }
        }
    }
    //      String reloadUrl = Utils.checkUrl(GameInfo.DEFAULT_URL);
    mWebView.loadUrl(reloadUrl);
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final int userId = Util.getUserId(Process.myUid());

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;//from   w w w.  j  ava 2 s. c  o m

    // Import license file
    if (Intent.ACTION_VIEW.equals(getIntent().getAction()))
        if (Util.importProLicense(new File(getIntent().getData().getPath())) != null)
            Toast.makeText(this, getString(R.string.menu_pro), Toast.LENGTH_LONG).show();

    // Set layout
    setContentView(R.layout.mainlist);
    setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar));
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    // Set sub title
    if (Util.hasProLicense(this) != null)
        getSupportActionBar().setSubtitle(R.string.menu_pro);

    // Annotate
    Meta.annotate(this.getResources());

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build spinner adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spAdapter.addAll(listRestrictionName);

    // Handle info
    ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo);
    imgInfo.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void onClick(View view) {
            int position = spRestriction.getSelectedItemPosition();
            if (position != AdapterView.INVALID_POSITION) {
                String query = (position == 0 ? "restrictions"
                        : (String) PrivacyManager.getRestrictions(ActivityMain.this).values().toArray()[position
                                - 1]);

                WebView webview = new WebView(ActivityMain.this);
                webview.getSettings().setUserAgentString("Mozilla/5.0");
                // needed for hashtag
                webview.getSettings().setJavaScriptEnabled(true);
                webview.loadUrl("https://github.com/M66B/XPrivacy#" + query);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
                alertDialogBuilder.setTitle((String) spRestriction.getSelectedItem());
                alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
                alertDialogBuilder.setView(webview);
                alertDialogBuilder.setCancelable(true);
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        }
    });

    // Setup category spinner
    spRestriction = (Spinner) findViewById(R.id.spRestriction);
    spRestriction.setAdapter(spAdapter);
    spRestriction.setOnItemSelectedListener(this);
    int pos = getSelectedCategory(userId);
    spRestriction.setSelection(pos);

    // Setup sort
    mSortMode = Integer.parseInt(PrivacyManager.getSetting(userId, PrivacyManager.cSettingSortMode, "0"));
    mSortInvert = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingSortInverted, false);

    // Start task to get app list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, (Object) null);

    // Check environment
    Requirements.check(this);

    // Licensing
    checkLicense();

    // Listen for package add/remove
    IntentFilter iff = new IntentFilter();
    iff.addAction(Intent.ACTION_PACKAGE_ADDED);
    iff.addAction(Intent.ACTION_PACKAGE_REMOVED);
    iff.addDataScheme("package");
    registerReceiver(mPackageChangeReceiver, iff);
    mPackageChangeReceiverRegistered = true;

    boolean showChangelog = true;

    // First run
    if (PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFirstRun, true)) {
        showChangelog = false;
        optionAbout();
    }

    // Tutorial
    if (!PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingTutorialMain, false)) {
        showChangelog = false;
        ((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE);
        ((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE);
    }
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ViewParent parent = view.getParent();
            while (!parent.getClass().equals(ScrollView.class))
                parent = parent.getParent();
            ((View) parent).setVisibility(View.GONE);
            PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialMain, Boolean.TRUE.toString());
        }
    };
    ((Button) findViewById(R.id.btnTutorialHeader)).setOnClickListener(listener);
    ((Button) findViewById(R.id.btnTutorialDetails)).setOnClickListener(listener);

    // Legacy
    if (!PrivacyManager.cVersion3) {
        long now = new Date().getTime();
        String legacy = PrivacyManager.getSetting(userId, PrivacyManager.cSettingLegacy, null);
        if (legacy == null || now > Long.parseLong(legacy) + 7 * 24 * 60 * 60 * 1000L) {
            showChangelog = false;
            PrivacyManager.setSetting(userId, PrivacyManager.cSettingLegacy, Long.toString(now));

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle(R.string.app_name);
            alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
            alertDialogBuilder.setMessage(R.string.title_update_legacy);
            alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Util.viewUri(ActivityMain.this,
                            Uri.parse("https://github.com/M66B/XPrivacy/blob/master/CHANGELOG.md#xprivacy3"));
                }
            });
            alertDialogBuilder.setNegativeButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Do nothing
                        }
                    });

            // Show dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    }

    // Show changelog
    if (showChangelog) {
        String sVersion = PrivacyManager.getSetting(userId, PrivacyManager.cSettingChangelog, null);
        Version changelogVersion = new Version(sVersion == null ? "0.0" : sVersion);
        Version currentVersion = new Version(Util.getSelfVersionName(this));
        if (sVersion == null || changelogVersion.compareTo(currentVersion) < 0)
            optionChangelog();
    }
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

private void optionChangelog() {
    WebView webview = new WebView(this);
    webview.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            int userId = Util.getUserId(Process.myUid());
            Version currentVersion = new Version(Util.getSelfVersionName(ActivityMain.this));
            PrivacyManager.setSetting(userId, PrivacyManager.cSettingChangelog, currentVersion.toString());
        }/*from  ww w. j  a  va 2s .  c o  m*/
    });
    webview.loadUrl("https://github.com/M66B/XPrivacy/blob/master/CHANGELOG.md");

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle(R.string.menu_changelog);
    alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
    alertDialogBuilder.setView(webview);
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void trySetupContentView() {
    mContentView.setVerticalScrollBarEnabled(false);
    mContentView.setHorizontalScrollBarEnabled(false);
    mContentView.getSettings().setJavaScriptEnabled(true);

    mContentView.setWebChromeClient(new WebChromeClient() {
        @Override//  ww  w . j  a  v a2s .  c o  m
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            Log.d(TAG, "newProgress = [" + newProgress + "]");
        }
    });

    mContentView.addJavascriptInterface(this, "Attiq");
    mContentView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (!mIsFirstTimeLoaded && mLoadingView != null) {
                mLoadingView.setAlpha(1.f);
                mLoadingView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            if (PrefUtil.isMathJaxEnabled()) {
                view.evaluateJavascript("javascript:document.getElementById('content').innerHTML='"
                        + doubleEscapeTeX(mArticle.getRenderedBody()) + "';", null);
                view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);",
                        new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                view.loadUrl("javascript:(function () "
                                        + "{document.getElementsByTagName('body')[0].style.marginBottom = '0'})()");
                            }
                        });
            }

            mIsFirstTimeLoaded = true;
            if (mLoadingView != null) {
                ViewCompat.animate(mLoadingView).alpha(0.f).setDuration(300)
                        .setListener(new ViewPropertyAnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(View view) {
                                if (mLoadingView != null) {
                                    mLoadingView.setVisibility(View.GONE);
                                }
                            }
                        }).start();
            }
        }
    });

    mContentView.setFindListener(new WebView.FindListener() {
        @Override
        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
            if (mMenuLayout != null) {
                mMenuLayout.closeDrawer(GravityCompat.END);
            }
            if (numberOfMatches > 0 && mMenuAnchor != null && mContentView != null) {
                // FIXME Doesn't work now, because WebView is staying inside ScrollView
                mContentView.loadUrl("javascript:scrollToElement(\"" + mMenuAnchor.text() + "\");");
            }
        }
    });
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private WebViewClient createWebViewClientThatHandlesFileLinksForCharts() {
    WebViewClient webViewClient = new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);//w ww  . j av  a 2  s  .c  o m
            if (uri.getScheme().startsWith("http")) {
                return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues.
            }

            String inputIdStr = uri.getQueryParameter("inputId");
            if (inputIdStr == null) {
                return true;
            }
            long inputId = Long.parseLong(inputIdStr);
            JSONArray results = new JSONArray();
            for (Event event : experiment.getEvents()) {
                JSONArray eventJson = new JSONArray();
                DateTime responseTime = event.getResponseTime();
                if (responseTime == null) {
                    continue; // missed signal;
                }
                eventJson.put(responseTime.getMillis());

                // in this case we are looking for one input from the responses that we are charting.
                for (Output response : event.getResponses()) {
                    if (response.getInputServerId() == inputId) {
                        Input inputById = experiment.getInputById(inputId);
                        if (!inputById.isInvisible() && inputById.isNumeric()) {
                            eventJson.put(response.getDisplayOfAnswer(inputById));
                            results.put(eventJson);
                            continue;
                        }
                    }
                }

            }
            env.put("data", results.toString());
            env.put("inputId", inputIdStr);

            view.loadUrl(stripQuery(url));
            return true;
        }
    };
    return webViewClient;
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*  ww w . j  a v  a2  s . c o  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main__activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (toolbar != null) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Helpers.isOnline(ShareActivity.this)) {
                    Intent intent = new Intent(ShareActivity.this, MainActivity.class);
                    startActivityForResult(intent, 100);
                    overridePendingTransition(0, 0);
                    finish();
                } else {
                    Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }
    setTitle(R.string.new_post);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.applyDiasporaMobileSiteChanges(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.main__layout), "Unable to get image",
                            Snackbar.LENGTH_LONG).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.main__layout), R.string.no_internet,
                    Snackbar.LENGTH_LONG).show();
        }
    }

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
                handleSendSubject(intent);
            } else {
                handleSendText(intent);
            }
        } else if (type.startsWith("image/")) {
            // TODO Handle single image being sent -> see manifest
            handleSendImage(intent);
        }
        //} else {
        // Handle other intents, such as being started from the home screen
    }

}

From source file:org.anurag.file.quest.TaskerActivity.java

/**
 * FUNCTION MAKE 3d LIST VIEW VISIBLE OR GONE AS PER REQUIREMENT
 * @param mode/*from   w w  w .  j  a  v a  2  s .  c o m*/
 * @param con
 */
public static void load_FIle_Gallery(final int mode) {
    final Dialog pDialog = new Dialog(mContext, R.style.custom_dialog_theme);
    final Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                try {
                    pDialog.setContentView(R.layout.p_dialog);
                    pDialog.setCancelable(false);
                    pDialog.getWindow().getAttributes().width = size.x * 4 / 5;
                    WebView web = (WebView) pDialog.findViewById(R.id.p_Web_View);
                    web.loadUrl("file:///android_asset/Progress_Bar_HTML/index.html");
                    web.setEnabled(false);
                    pDialog.show();
                } catch (InflateException e) {
                    error = true;
                    Toast.makeText(mContext,
                            "An exception encountered please wait while loading" + " file list",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                if (pDialog != null)
                    if (pDialog.isShowing())
                        pDialog.dismiss();

                if (mediaFileList.size() > 0) {
                    FILE_GALLEY.setVisibility(View.GONE);
                    LIST_VIEW_3D.setVisibility(View.VISIBLE);
                    element = new MediaElementAdapter(mContext, R.layout.row_list_1, mediaFileList);
                    //AT THE PLACE OF ELEMENT YOU CAN USE MUSIC ADAPTER....
                    // AND SEE WHAT HAPPENS
                    if (mediaFileList.size() > 0) {
                        LIST_VIEW_3D.setAdapter(element);
                        LIST_VIEW_3D.setEnabled(true);
                    } else if (mediaFileList.size() == 0) {
                        LIST_VIEW_3D.setAdapter(new EmptyAdapter(mContext, R.layout.row_list_3, EMPTY));
                        LIST_VIEW_3D.setEnabled(false);
                    }
                    LIST_VIEW_3D.setDynamics(new SimpleDynamics(0.7f, 0.6f));
                    if (!elementInFocus) {
                        mFlipperBottom.showPrevious();
                        mFlipperBottom.setAnimation(prevAnim());
                        elementInFocus = true;
                    }
                    if (SEARCH_FLAG) {
                        mVFlipper.showPrevious();
                        mVFlipper.setAnimation(nextAnim());
                    }
                } else {
                    LIST_VIEW_3D.setVisibility(View.GONE);
                    FILE_GALLEY.setVisibility(View.VISIBLE);
                    Toast.makeText(mContext, R.string.empty, Toast.LENGTH_SHORT).show();
                    if (elementInFocus) {
                        mFlipperBottom.showNext();
                        mFlipperBottom.setAnimation(nextAnim());
                    }
                    elementInFocus = false;
                }
                break;
            }
        }
    };
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            handle.sendEmptyMessage(0);
            while (!Utils.loaded) {
                //STOPPING HERE WHILE FILES ARE BEING LOADED IN BACKGROUND....
            }
            if (mode == 0)
                mediaFileList = Utils.music;
            else if (mode == 1)
                mediaFileList = Utils.apps;
            else if (mode == 2)
                mediaFileList = Utils.doc;
            else if (mode == 3)
                mediaFileList = Utils.img;
            else if (mode == 4)
                mediaFileList = Utils.vids;
            else if (mode == 5)
                mediaFileList = Utils.zip;
            else if (mode == 6)
                mediaFileList = Utils.mis;
            handle.sendEmptyMessage(1);
        }
    });
    thread.start();
}

From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java

protected void updateMessageDetail(final boolean isUpdate) {
    T.UI();/*from   w w w  .j a v a 2 s. c om*/
    // Set sender avatar
    ImageView avatarImage = (ImageView) findViewById(R.id.avatar);
    String sender = mCurrentMessage.sender;
    setAvatar(avatarImage, sender);
    // Set sender name
    TextView senderView = (TextView) findViewById(R.id.sender);
    final String senderName = mFriendsPlugin.getName(sender);
    senderView.setText(senderName == null ? sender : senderName);
    // Set timestamp
    TextView timestampView = (TextView) findViewById(R.id.timestamp);
    timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000));

    // Set clickable region on top to go to friends detail
    final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header);
    messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender));
    messageHeader.setVisibility(View.VISIBLE);

    // Set message
    TextView messageView = (TextView) findViewById(R.id.message);
    WebView web = (WebView) findViewById(R.id.webview);
    FrameLayout flay = (FrameLayout) findViewById(R.id.message_details);
    Resources resources = getResources();
    flay.setBackgroundColor(resources.getColor(R.color.mc_background));
    boolean showBranded = false;

    int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark);
    int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light);

    senderView.setTextColor(lightSchemeTextColor);
    timestampView.setTextColor(lightSchemeTextColor);

    BrandingResult br = null;
    if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) {
        boolean brandingAvailable = false;
        try {
            brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding);
        } catch (BrandingFailureException e1) {
            L.d(e1);
        }
        try {
            if (brandingAvailable) {
                br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage);
                WebSettings settings = web.getSettings();
                settings.setJavaScriptEnabled(false);
                settings.setBlockNetworkImage(false);
                web.loadUrl("file://" + br.file.getAbsolutePath());
                web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                if (br.color != null) {
                    flay.setBackgroundColor(br.color);
                }
                if (!br.showHeader) {
                    messageHeader.setVisibility(View.GONE);
                    MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams();
                    mlp.setMargins(0, 0, 0, mlp.bottomMargin);
                } else if (br.scheme == ColorScheme.dark) {
                    senderView.setTextColor(darkSchemeTextColor);
                    timestampView.setTextColor(darkSchemeTextColor);
                }

                showBranded = true;
            } else {
                mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding);
            }
        } catch (BrandingFailureException e) {
            L.bug("Could not display message with branding: branding is available, but prepareBranding failed",
                    e);
        }
    }

    if (showBranded) {
        web.setVisibility(View.VISIBLE);
        messageView.setVisibility(View.GONE);
    } else {
        web.setVisibility(View.GONE);
        messageView.setVisibility(View.VISIBLE);
        messageView.setText(mCurrentMessage.message);
    }

    // Add list of members who did not ack yet
    FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary);
    memberSummary.removeAllViews();
    SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator());
    for (MemberStatusTO ms : mCurrentMessage.members) {
        if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED
                && !ms.member.equals(mCurrentMessage.sender)) {
            memberSummarySet.add(ms);
        }
    }
    FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0);
    for (MemberStatusTO ms : memberSummarySet) {
        FrameLayout fl = new FrameLayout(this);
        fl.setLayoutParams(flowLP);
        memberSummary.addView(fl);
        fl.addView(createParticipantView(ms));
    }
    memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE);

    // Add members statuses
    final LinearLayout members = (LinearLayout) findViewById(R.id.members);
    members.removeAllViews();
    final String myEmail = mService.getIdentityStore().getIdentity().getEmail();
    boolean isMember = false;
    mSomebodyAnswered = false;
    for (MemberStatusTO ms : mCurrentMessage.members) {
        boolean showMember = true;
        View view = getLayoutInflater().inflate(R.layout.message_member_detail, null);
        // Set receiver avatar
        RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar);
        rl.addView(createParticipantView(ms));
        // Set receiver name
        TextView receiverView = (TextView) view.findViewById(R.id.receiver);
        final String memberName = mFriendsPlugin.getName(ms.member);
        receiverView.setText(memberName == null ? sender : memberName);
        // Set received timestamp
        TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) {
            final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000);
            if (ms.member.equals(mCurrentMessage.sender))
                receivedView.setText(getString(R.string.sent_at, humanTime));
            else
                receivedView.setText(getString(R.string.received_at, humanTime));
        } else {
            receivedView.setText(R.string.not_yet_received);
        }
        // Set replied timestamp
        TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) {
            mSomebodyAnswered = true;
            String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000);
            if (ms.button_id != null) {

                ButtonTO button = null;
                for (ButtonTO b : mCurrentMessage.buttons) {
                    if (b.id.equals(ms.button_id)) {
                        button = b;
                        break;
                    }
                }
                if (button == null) {
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                } else {
                    repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp));
                }
            } else {
                if (ms.custom_reply == null) {
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                } else
                    repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp));
            }
        } else {
            repliedView.setText(R.string.not_yet_replied);
            showMember = !ms.member.equals(mCurrentMessage.sender);
        }
        if (br != null && br.scheme == ColorScheme.dark) {
            receiverView.setTextColor(darkSchemeTextColor);
            receivedView.setTextColor(darkSchemeTextColor);
            repliedView.setTextColor(darkSchemeTextColor);
        } else {
            receiverView.setTextColor(lightSchemeTextColor);
            receivedView.setTextColor(lightSchemeTextColor);
            repliedView.setTextColor(lightSchemeTextColor);
        }

        if (showMember)
            members.addView(view);
        isMember |= ms.member.equals(myEmail);
    }

    boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED;
    boolean canEdit = isMember && !isLocked;

    // Add attachments
    LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout);
    attachmentLayout.removeAllViews();
    if (mCurrentMessage.attachments.length > 0) {
        attachmentLayout.setVisibility(View.VISIBLE);

        for (final AttachmentTO attachment : mCurrentMessage.attachments) {
            View v = getLayoutInflater().inflate(R.layout.attachment_item, null);

            ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image);
            if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type)
                    || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_img);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_pdf);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4
                    .equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_video);
            } else {
                attachment_image.setImageResource(R.drawable.attachment_unknown);
                L.d("attachment.content_type not known: " + attachment.content_type);
            }

            TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text);
            attachment_text.setText(attachment.name);

            v.setOnClickListener(new SafeViewOnClickListener() {

                @Override
                public void safeOnClick(View v) {
                    String downloadUrlHash = mMessagingPlugin
                            .attachmentDownloadUrlHash(attachment.download_url);

                    File attachmentsDir;
                    try {
                        attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null);
                    } catch (IOException e) {
                        L.d("Unable to create attachment directory", e);
                        UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                R.string.unable_to_read_write_sd_card);
                        return;
                    }

                    boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                            downloadUrlHash);

                    if (!attachmentAvailable) {
                        try {
                            attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(),
                                    mCurrentMessage.key);
                        } catch (IOException e) {
                            L.d("Unable to create attachment directory", e);
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }

                        attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                                downloadUrlHash);
                    }

                    if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(R.string.no_internet_connection_try_again);
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        return;
                    }
                    if (IOUtils.shouldCheckExternalStorageAvailable()) {
                        String state = Environment.getExternalStorageState();
                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                            // Its all oke
                        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                            if (!attachmentAvailable) {
                                L.d("Unable to write to sd-card");
                                UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                        R.string.unable_to_read_write_sd_card);
                                return;
                            }
                        } else {
                            L.d("Unable to read or write to sd-card");
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }
                    }

                    L.d("attachment.content_type: " + attachment.content_type);
                    L.d("attachment.download_url: " + attachment.download_url);
                    L.d("attachment.name: " + attachment.name);
                    L.d("attachment.size: " + attachment.size);

                    if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) {
                        Intent i = new Intent(ServiceMessageDetailActivity.this,
                                AttachmentViewerActivity.class);
                        i.putExtra("thread_key", mCurrentMessage.getThreadKey());
                        i.putExtra("message", mCurrentMessage.key);
                        i.putExtra("content_type", attachment.content_type);
                        i.putExtra("download_url", attachment.download_url);
                        i.putExtra("name", attachment.name);
                        i.putExtra("download_url_hash", downloadUrlHash);

                        startActivity(i);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version,
                                getString(R.string.app_name)));
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }

            });

            attachmentLayout.addView(v);
        }

    } else {
        attachmentLayout.setVisibility(View.GONE);
    }

    LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout);
    if (mCurrentMessage.form == null) {
        widgetLayout.setVisibility(View.GONE);
    } else {
        widgetLayout.setVisibility(View.VISIBLE);
        widgetLayout.setEnabled(canEdit);
        displayWidget(widgetLayout, br);
    }

    // Add buttons
    TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons);
    tableLayout.removeAllViews();

    for (final ButtonTO button : mCurrentMessage.buttons) {
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }
    if (mCurrentMessage.form == null && (mCurrentMessage.flags
            & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) {
        ButtonTO button = new ButtonTO();
        button.caption = "Roger that!";
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }

    if (mCurrentMessage.broadcast_type != null) {
        L.d("Show broadcast spam control");
        final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control);
        View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border);
        final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider);

        final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_text_container);
        TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text);

        final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_settings_container);
        TextView broadcastSpamControlSettingsText = (TextView) findViewById(
                R.id.broadcast_spam_control_settings_text);
        TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon);
        broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace);
        broadcastSpamControlIcon.setText(R.string.fa_bell);

        final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender);
        if (fbi == null) {
            L.bug("BroadcastData was null for: " + mCurrentMessage.sender);
            collapseDetails(DETAIL_SECTIONS);
            return;
        }
        broadcastSpamControl.setVisibility(View.VISIBLE);

        broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() {

            @Override
            public void safeOnClick(View v) {
                L.d("goto broadcast settings");

                PressMenuIconRequestTO request = new PressMenuIconRequestTO();
                request.coords = fbi.coords;
                request.static_flow_hash = fbi.staticFlowHash;
                request.hashed_tag = fbi.hashedTag;
                request.generation = fbi.generation;
                request.service = mCurrentMessage.sender;
                mContext = "MENU_" + UUID.randomUUID().toString();
                request.context = mContext;
                request.timestamp = System.currentTimeMillis() / 1000;

                showTransmitting(null);
                Map<String, Object> userInput = new HashMap<String, Object>();
                userInput.put("request", request.toJSONMap());
                userInput.put("func", "com.mobicage.api.services.pressMenuItem");

                MessageFlowRun mfr = new MessageFlowRun();
                mfr.staticFlowHash = fbi.staticFlowHash;
                try {
                    JsMfr.executeMfr(mfr, userInput, mService, true);
                } catch (EmptyStaticFlowException ex) {
                    completeTransmit(null);
                    AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this);
                    builder.setMessage(ex.getMessage());
                    builder.setPositiveButton(R.string.rogerthat, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return;
                }
            }

        });

        UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast,
                mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender));

        broadcastSpamControlText
                .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type));
        broadcastSpamControlSettingsText.setText(fbi.label);
        int ligthAlpha = 180;
        int darkAlpha = 70;
        int alpha = ligthAlpha;
        if (br != null && br.scheme == ColorScheme.dark) {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black));
            broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor);
            activity.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlText.setTextColor(lightSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor),
                    Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);

            alpha = darkAlpha;
        } else {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white));
            broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor);
            activity.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlText.setTextColor(darkSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor),
                    Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);
        }

        if (br != null && br.color != null) {
            int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color),
                    Color.blue(br.color));
            broadcastSpamControl.setBackgroundColor(alphaColor);
        }

        mService.postOnUIHandler(new SafeRunnable() {

            @Override
            protected void safeRun() throws Exception {
                int maxHeight = broadcastSpamControl.getHeight();
                broadcastSpamControlDivider.getLayoutParams().height = maxHeight;
                broadcastSpamControlDivider.requestLayout();

                broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlSettingsContainer.requestLayout();

                broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlTextContainer.requestLayout();

                int broadcastSpamControlWidth = broadcastSpamControl.getWidth();
                android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer
                        .getLayoutParams();
                lp.width = broadcastSpamControlWidth / 4;
                broadcastSpamControlSettingsContainer.setLayoutParams(lp);
            }
        });
    }

    if (!isUpdate)
        collapseDetails(DETAIL_SECTIONS);
}