Monday, March 21, 2016

android - How to encode a URL

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ccd1c5"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="#000000"
        android:padding="5dp"
        />
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load URL"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.webkit.WebView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private Button mButton;
    private WebView mWebView;

    private String mURL;
    private String mQuery;

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

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Specify the url to surf
        mURL = "http://stackoverflow.com/search?q=";

        /*
            URLEncoder
                This class is used to encode a string using the format required by
                application/x-www-form-urlencoded MIME content type.

                All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') and
                characters '.', '-', '*', '_' are converted into their hexadecimal value prepended
                by '%'. For example: '#' -> %23. In addition, spaces are substituted by '+'.
        */

        // Try to encode the url query parameters
        try{
            /*
                public static String encode (String s, String charsetName)
                    Encodes s using the Charset named by charsetName.

                Parameters
                    s : String
                    charsetName : String

                Returns
                    String

                Throws
                    UnsupportedEncodingException
            */
            mQuery = URLEncoder.encode("android drawables","UTF-8");
        }catch(UnsupportedEncodingException e){ // Catch the encoding exception
            e.printStackTrace();
        }

        // Build the final url to browse
        mURL += mQuery;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mButton = (Button) findViewById(R.id.btn);
        mWebView = (WebView) findViewById(R.id.web_view);

        // Display the encoded url in TextView
        mTextView.setText("Encoded URL\n" + mURL);

        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Set a WebViewClient for WebView
                mWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        // Page loading started
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        // Page loading finished
                        Toast.makeText(mContext, "Page Loaded.", Toast.LENGTH_SHORT).show();
                    }
                });

                // Enable JavaScript
                mWebView.getSettings().setJavaScriptEnabled(true);

                // Load the url in the WebView
                mWebView.loadUrl(mURL);
            }
        });
    }
}