Example usage for android.webkit URLUtil isValidUrl

List of usage examples for android.webkit URLUtil isValidUrl

Introduction

In this page you can find the example usage for android.webkit URLUtil isValidUrl.

Prototype

public static boolean isValidUrl(String url) 

Source Link

Usage

From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java

private String uploadFiles(List<File> files) {
    String result = "";
    try {/*w ww. j  a  v a2 s.  com*/

        if (URLUtil.isValidUrl(posturl)) {
            HttpClient httpclient = getNewHttpClient();

            HttpPost httppost = new HttpPost(posturl);
            MultipartEntity mpEntity = new MultipartEntity();
            //            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            mpEntity.addPart("username", new StringBody(username));
            mpEntity.addPart("password", new StringBody(password));
            for (File file : files) {
                Log.d(SensorRegistry.TAG, "preparing " + file.getName() + " for upload");
                ContentBody cbFile = new FileBody(file, "application/json");
                mpEntity.addPart(file.toString(), cbFile);
            }
            httppost.addHeader("username", username);
            httppost.addHeader("password", password);
            httppost.setEntity(mpEntity);
            HttpResponse response = httpclient.execute(httppost);

            String reply;
            InputStream in = response.getEntity().getContent();

            StringBuilder sb = new StringBuilder();
            try {
                int chr;
                while ((chr = in.read()) != -1) {
                    sb.append((char) chr);
                }
                reply = sb.toString();
            } finally {
                in.close();
            }
            result = response.getStatusLine().toString();
            Log.d(SensorRegistry.TAG, "Http upload completed with response: " + result + " " + reply);

        } else {
            result = "URL invalid";
            Log.d(SensorRegistry.TAG, "Invalid http upload url, aborting.");
        }
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (FileNotFoundException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (ClientProtocolException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (IOException e) {
        result = "upload failed due to timeout";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    }
    return result;
}

From source file:com.hemou.android.util.StrUtils.java

public static boolean isValidUrl(String url) {
    return URLUtil.isValidUrl(url);
}

From source file:com.svo.library.widget.RLWebBrowser.java

/**
 * /*from  ww  w .  j  a  v  a2s  .c o m*/
 * @param url
 * @param listener
 */
public void load(String url, Listener listener) {
    this.listener = listener;
    listener.onPrepare();
    if (url != null && URLUtil.isValidUrl(url)) {
        webView.loadUrl(url);
    } else {
        RLUiUtil.toast(context, R.string.invalid_url);
    }
}

From source file:org.ormma.controller.OrmmaDisplayController.java

/**
 * Play audio/*w  w  w . ja v a 2  s .c  o  m*/
 * @param url - audio url to be played
 * @param autoPlay - if audio should play immediately
 * @param controls - should native player controls be visible
 * @param loop - should video start over again after finishing
 * @param position - should audio be included with ad content
 * @param startStyle - normal/full screen (if audio should play in native full screen mode)
 * @param stopStyle - normal/exit (exit if player should exit after audio stops)
 */
public void playAudio(String url, boolean autoPlay, boolean controls, boolean loop, boolean position,
        String startStyle, String stopStyle) {
    Log.d(LOG_TAG, "playAudio: url: " + url + " autoPlay: " + autoPlay + " controls: " + controls + " loop: "
            + loop + " position: " + position + " startStyle: " + startStyle + " stopStyle: " + stopStyle);
    if (!URLUtil.isValidUrl(url)) {
        mOrmmaView.raiseError("Invalid url", "playAudio");
    } else {
        mOrmmaView.playAudio(url, autoPlay, controls, loop, position, startStyle, stopStyle);
    }

}

From source file:com.gumgoose.app.quakebuddy.EarthquakeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.earthquake_activity);

    // Monitor upgrades in QuakeBuddy and trigger the changes dialog
    detectVersionChange();//from   ww  w. j a va2  s  .  co  m

    // Find a reference to the ListView in the layout
    ListView earthquakeListView = (ListView) findViewById(R.id.list);

    // Find a reference to the loading indicator in the layout
    mLoadingIndicator = findViewById(R.id.loading_indicator);

    // Find a reference to the empty list View placeholder
    mEmptyStateView = findViewById(R.id.empty_view);

    // Find a reference to the empty list TextView placeholder
    mEmptyTextView = (TextView) findViewById(R.id.empty_message);

    // Set the empty state View to display when the ListView is empty
    earthquakeListView.setEmptyView(mEmptyStateView);

    // Make a new adapter and enable it on the earthquake ListView
    mAdapter = new QuakeAdapter(this, new ArrayList<Quake>());
    earthquakeListView.setAdapter(mAdapter);

    // Find a reference to the swipe to refresh feature
    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
    swipe.setOnRefreshListener(EarthquakeActivity.this);
    swipe.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

    // Set an OnItemClick listener on the ListView
    earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Fetch the USGS earthquake URL and check whether the URL is valid
            String quakeUrl = mAdapter.getItem(position).getQuakeURL();

            if (URLUtil.isValidUrl(quakeUrl)) {
                // URL is valid, start WebViewActivity with URL intent
                Intent websiteIntent = new Intent(EarthquakeActivity.this, WebViewActivity.class);
                websiteIntent.putExtra("url", quakeUrl);
                startActivity(websiteIntent);
            } else {
                // Inform the user by Toast message and exit gracefully
                Toast.makeText(EarthquakeActivity.this, R.string.error_invalid_url, Toast.LENGTH_LONG).show();
            }
        }
    });

    // Connect to the ConnectivityManager system service
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // Check whether there is an active network connection
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        // Network detected, initialize the Loader
        LoaderManager loaderManager = getLoaderManager();
        loaderManager.initLoader(EARTHQUAKE_LOADER_ID, null, this);
    } else {
        // Display the empty View on ListView with no internet message
        mLoadingIndicator.setVisibility(View.GONE);
        swipe.setRefreshing(false);
        mEmptyTextView.setText(R.string.no_internet_connection);
        mEmptyStateView.setVisibility(View.VISIBLE);
    }
}

From source file:me.calebjones.spacelaunchnow.utils.Utils.java

public static void openCustomTab(Activity activity, Context context, String url) {
    CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();

    ListPreferences sharedPreference = ListPreferences.getInstance(context);

    if (sharedPreference.isNightModeActive(context)) {
        intentBuilder.setToolbarColor(ContextCompat.getColor((context), R.color.darkPrimary));
    } else {//from w w  w  .jav a  2  s.  c  o m
        intentBuilder.setToolbarColor(ContextCompat.getColor((context), R.color.colorPrimary));
    }

    intentBuilder.setShowTitle(true);

    PendingIntent actionPendingIntent = createPendingShareIntent(context, url);
    intentBuilder.setActionButton(
            BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_menu_share_white), "Share",
            actionPendingIntent);
    intentBuilder
            .setCloseButtonIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_arrow_back));

    intentBuilder.setStartAnimations(activity, R.anim.slide_in_right, R.anim.slide_out_left);
    intentBuilder.setExitAnimations(activity, android.R.anim.slide_in_left, android.R.anim.slide_out_right);

    if (URLUtil.isValidUrl(url)) {
        CustomTabActivityHelper.openCustomTab(activity, intentBuilder.build(), Uri.parse(url),
                new WebViewFallback());
    } else {
        Toast.makeText(activity, "ERROR: URL is malformed - sorry! " + url, Toast.LENGTH_SHORT);
    }
}

From source file:com.optimusinfo.elasticpath.cortex.purchase.PurchaseFragment.java

/**
 * This function posts the add to cart object
 * /*from   ww w.  j av a2s . c  om*/
 * @param mPostUrl
 */
public void postPurchaseOrder(String mPostUrl) {
    mPostPurchaseListner = new ListenerCompletePurchaseOrder() {
        @Override
        public void onTaskSuccessful(final String response) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showProgressDialog(false);
                    mIsOrderConfirmed = true;
                    mOrderDetailsUrl = response;
                    if (mOrderDetailsUrl != null) {
                        getOrderDetails(mOrderDetailsUrl);
                    }
                }
            });
        }

        @Override
        public void onTaskFailed(final int errorCode) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showProgressDialog(false);
                    // TODO - For Future Req
                    NotificationUtils.showErrorToast(getActivity(), errorCode);
                }
            });
        }

        @Override
        public void onAuthenticationFailed() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showProgressDialog(false);
                    // TODO For Future Req
                    NotificationUtils.showErrorToast(getActivity(), Constants.ErrorCodes.ERROR_SERVER);
                }
            });
        }
    };
    showProgressDialog(true);
    mLayout.setVisibility(View.INVISIBLE);
    if (!TextUtils.isEmpty(mPostUrl) && URLUtil.isValidUrl(mPostUrl)) {
        OrderModel.postPurchaseOrder(getActivity(), mPostUrl, Constants.Config.CONTENT_TYPE_PURCHASE_ORDER,
                getUserAuthenticationToken(), mPostPurchaseListner);
    }

}

From source file:org.ormma.controller.OrmmaDisplayController.java

/**
 * Play video//from  w w w.  java  2  s . c  om
 * @param url - video url to be played
 * @param audioMuted - should audio be muted
 * @param autoPlay - should video play immediately
 * @param controls  - should native player controls be visible
 * @param loop - should video start over again after finishing
 * @param position - top and left coordinates of video in pixels if video should play inline
 * @param startStyle - normal/fullscreen (if video should play in native full screen mode)
 * @param stopStyle - normal/exit (exit if player should exit after video stops)
 */
public void playVideo(String url, boolean audioMuted, boolean autoPlay, boolean controls, boolean loop,
        int[] position, String startStyle, String stopStyle) {
    Log.d(LOG_TAG,
            "playVideo: url: " + url + " audioMuted: " + audioMuted + " autoPlay: " + autoPlay + " controls: "
                    + controls + " loop: " + loop + " x: " + position[0] + " y: " + position[1] + " width: "
                    + position[2] + " height: " + position[3] + " startStyle: " + startStyle + " stopStyle: "
                    + stopStyle);
    Dimensions d = null;
    if (position[0] != -1) {
        d = new Dimensions();
        d.x = position[0];
        d.y = position[1];
        d.width = position[2];
        d.height = position[3];
        d = getDeviceDimensions(d);
    }
    if (!URLUtil.isValidUrl(url)) {
        mOrmmaView.raiseError("Invalid url", "playVideo");
    } else {
        mOrmmaView.playVideo(url, audioMuted, autoPlay, controls, loop, d, startStyle, stopStyle);
    }
}

From source file:com.sakisds.icymonitor.activities.AddServerActivity.java

@SuppressWarnings("ConstantConditions")
@Override/* w  ww  .j  a  v a2 s  .  com*/
public void onClick(View view) {
    // Check if name is empty
    if (mEditText_name.getText().toString().equals("")) {
        mEditText_name.setError(getResources().getString(R.string.error_empty_name));
        mEditText_name.requestFocus();
    } else if (mEditText_port.getText().toString().equals("")) {
        mEditText_port.setError(getString(R.string.error_empty_port));
        mEditText_port.requestFocus();
    } else if (mEditText_address.getText().toString().equals("")) {
        mEditText_address.setError(getString(R.string.error_empty_address));
        mEditText_address.requestFocus();
    } else { // If it's not
        // Validate URL
        String url = mEditText_address.getText().toString();
        // Add http:// if needed
        if (!url.substring(0, 7).equals("http://")) {
            url = "http://" + url;
        }
        url += ":" + mEditText_port.getText().toString();
        url = url.replace(" ", "");
        if (!URLUtil.isValidUrl(url)) { // If invalid
            mEditText_address.setError(getResources().getString(R.string.error_invalid_address));
            mEditText_address.requestFocus();
        } else { // If URL is valid
            // Create a dialog
            final ProgressDialog progress = ProgressDialog.show(this, "",
                    getResources().getString(R.string.connecting), false);

            // Store actual URL
            final String actualURL = url;

            // Check if auth is enabled
            mClient.get(url + "/authEnabled", null, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(JSONObject response) {
                    try {
                        if (response.getBoolean("AuthEnabled")) {
                            progress.setMessage(getString(R.string.check_computer));
                        }
                    } catch (JSONException ignored) {
                    } // If there are issues they will be dealt with later
                }
            });

            // Register
            RequestParams params = new RequestParams();
            params.put("name", android.os.Build.MODEL);
            params.put("id", String.valueOf(mSettings.getLong("device_id", -2)));
            params.put("gcm", mGCMID);
            params.put("ask", "true");

            JsonHttpResponseHandler handler = new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(JSONObject response) {
                    try {
                        // Get string
                        String version = response.getString("Version");

                        // Parse response
                        if (version.equals(ConnectionActivity.ACCEPTED_SERVER_VERSION)) {
                            String regStatus = response.getString("Status");

                            if (regStatus.equals("ALLOWED")) {
                                saveServer(actualURL);
                                progress.dismiss();
                                mResponseReady = true;
                            } else if (regStatus.equals("DENIED")) {
                                mEditText_address.setError(getResources().getString(R.string.error_rejected));
                                mEditText_address.requestFocus();
                                progress.dismiss();
                                mResponseReady = true;
                            }
                        } else {
                            mEditText_address
                                    .setError(getResources().getString(R.string.error_outdated_server));
                            mEditText_address.requestFocus();
                            progress.dismiss();
                            mResponseReady = true;
                        }
                    } catch (JSONException e) {
                        mEditText_address.setError(getResources().getString(R.string.error_invalid_response));
                        mEditText_address.requestFocus();
                        progress.dismiss();
                        mResponseReady = true;
                    }
                }

                @Override
                public void onFailure(Throwable e, JSONObject errorResponse) {
                    progress.dismiss();
                    mEditText_address.setError(getResources().getString(R.string.error_could_not_reach_host));
                    mEditText_address.requestFocus();
                    mResponseReady = true;
                }
            };

            mClient.get(url + "/register", params, handler);
            params.remove("ask");

            WaitingTask task = new WaitingTask();

            task.mUrl = url + "/register";
            task.mParams = params;
            task.mHandler = handler;

            task.execute();
        }
    }
}

From source file:com.dm.material.dashboard.candybar.fragments.dialog.AboutFragment.java

private void initImageHeader() {
    String url = getActivity().getString(R.string.about_image);
    if (URLUtil.isValidUrl(url)) {
        ImageLoader.getInstance().displayImage(url, mImageView,
                ImageConfig.getImageOptions(true, Preferences.getPreferences(getActivity()).isCacheAllowed()));
    } else {/*  w ww . j a v a  2 s  .  c o m*/
        int res = DrawableHelper.getResourceId(getActivity(), url);
        if (res > 0)
            mImageView.setImageDrawable(ContextCompat.getDrawable(getActivity(), res));
    }
}