Sunday, 16 June 2013

How to Convert String to Base64 ?

Demo:

1)MainActivity.java:

package com.venky.convertstringtobase64;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

      TextView tvNormal, tvEncoded;

      String normalString = "Welcome to Android !";
      String convertString;

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

            tvNormal = (TextView) findViewById(R.id.tvNormal);
            tvEncoded = (TextView) findViewById(R.id.tvEncoded);

            convertString = encodeToBase64(normalString);

            tvNormal.setText("Normal String\n" + normalString);
            tvEncoded.setText("Base64\n" + convertString);

      }

      public String encodeToBase64(String string) {
            String encodedString = "";
            try {
                  byte[] byteData = null;
                  if (Build.VERSION.SDK_INT >= 8) {
                        byteData = android.util.Base64.encode(string.getBytes(),
                                    android.util.Base64.DEFAULT);
                  }
                  encodedString = new String(byteData);
            } catch (Exception e) {
            }
            return encodedString;
      }
}


2)activity_main.xml:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5F04B4"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tvNormal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="15dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvEncoded"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="15dp"
        android:textStyle="bold" />

</LinearLayout>


3)Download this code Click Here

No comments:

Post a Comment