Thursday, 21 May 2015

Showing Base 64 image in using Shared Preference in Android

Step 1:
Create a project

And Copy Paste Below code into it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/web_img"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/textView1"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_toRightOf="@+id/imageView1"
        android:text="@string/txt_imageview" />

</RelativeLayout>

You can Do it For Both For image View and For WebView.
Copy paste Following code into main activity
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.ImageView;


public class MainActivity extends ActionBarActivity {

ImageView img;
String url_to_show;
SharedPreferences sharedpreferences;

String byte_image_imageview = "";
public static final String MyPREFERENCES = "MyPrefs";
public static final String ByteImageString = "ByteImageString";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

img = (ImageView) findViewById(R.id.imageView1);

byte_image_imageview = "Paste Any Base 64 String Here";
Editor editor = sharedpreferences.edit();
editor.putString(ByteImageString, byte_image_imageview);

editor.commit();
String imag_abc = sharedpreferences.getString(ByteImageString, "");
byte[] decodedString = Base64.decode(imag_abc, Base64.DEFAULT);
url_to_show = "<html><body>" + byte_image + "<html><body>";
// webview.setBackgroundColor(0x00000000);
webview.loadData(url_to_show, "text/html", "utf-8");

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
img.setImageBitmap(decodedByte);

}



}


No comments:

Post a Comment