Saturday, August 15, 2015

Profile Page Camera and Gallery


.

Profile Page Camera and Gallery

Using Android Studio 1.4
To allow the user to choose between Camera or Gallery for profile photo, the application provides two types of object click/tap ie Short Tap and Long Tap.

1) Start Up

Follow previous tutorial or download start up project MyProfile4-profile-photo.zip.

2) Edit MainActivity

package com.notarazi.myprofile;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MyProfile extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_my_profile);
       checkFirstLogin();
       prepareForm();
       ImageView ivUserPhoto=(ImageView) findViewById(R.id.userphoto);
       ivUserPhoto.isClickable();
       ivUserPhoto.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // TODO Auto-generated method stub
               Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
           }
       });
       ivUserPhoto.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View v) {
               // TODO Auto-generated method stub
               Toast.makeText(getBaseContext(), "Long Clicked", Toast.LENGTH_SHORT).show();
               return true;
           }
       });
   }
   private void prepareForm() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       EditText etUserName=(EditText)findViewById(R.id.username);
       EditText etUserPhone=(EditText)findViewById(R.id.userphone);
       EditText etUserEmail=(EditText)findViewById(R.id.useremail);
       ImageView ivUserPhoto=(ImageView) findViewById(R.id.userphoto);
       ImageView ivUserSavedPhoto=(ImageView) findViewById(R.id.usersavedphoto);
       // If value for key not exist then return second param value - In this case "..."
       etUserName.setText(preferences.getString("username""..."));
       etUserPhone.setText(preferences.getString("userphone""..."));
       etUserEmail.setText(preferences.getString("useremail""..."));
       String img_str=preferences.getString("userphoto""");
       if (!img_str.equals("")){
           //decode string to image
           String base=img_str;
           byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
           ivUserPhoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
           ivUserSavedPhoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
       }
   }
   private void checkFirstLogin() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       // If value for key not exist then return second param value - In this case true
       if (preferences.getBoolean("firstLogin"true)) {
           initProfile();
           SharedPreferences.Editor editor = preferences.edit();
           editor.putBoolean("firstLogin"false);
           editor.commit();
       }
   }
   private void initProfile() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       SharedPreferences.Editor editor = preferences.edit();
       editor.putString("username","Demo TryTest");
       editor.putString("userphone","01234567890");
       editor.putString("useremail","demotrytest@gmail.com");
       editor.commit();
   }
   public void setProfilePhoto(View view){
       ImageView ivphoto = (ImageView)findViewById(R.id.userphoto);
       //code image to string
       ivphoto.buildDrawingCache();
       Bitmap bitmap = ivphoto.getDrawingCache();
       ByteArrayOutputStream stream=new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG90, stream);
       byte[] image=stream.toByteArray();
       //System.out.println("byte array:"+image);
       //final String img_str = "data:image/png;base64,"+ Base64.encodeToString(image, 0);
       //System.out.println("string:"+img_str);
       String img_str = Base64.encodeToString(image, 0);
       //decode string to image
       String base=img_str;
       byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
       ImageView ivsavedphoto = (ImageView)this.findViewById(R.id.usersavedphoto);
       ivsavedphoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes,0, imageAsBytes.length) );
       //save in sharedpreferences
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       SharedPreferences.Editor editor = preferences.edit();
       editor.putString("userphoto",img_str);
       editor.commit();
   }
}
  

3) Edit MainActivity (Insert Camera and Gallery feature)

package com.notarazi.myprofile;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MyProfile extends AppCompatActivity {
   ImageView ivUserPhoto;
   private static final int IMAGE_PICK 1;
   private static final int IMAGE_CAPTURE 2;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_my_profile);
       checkFirstLogin();
       prepareForm();
       ivUserPhoto=(ImageView) findViewById(R.id.userphoto);
       ivUserPhoto.isClickable();
       ivUserPhoto.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // TODO Auto-generated method stub
               //Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
               Intent intent = newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
               startActivityForResult(intent, IMAGE_CAPTURE);
           }
       });
       ivUserPhoto.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View v) {
               // TODO Auto-generated method stub
               //Toast.makeText(getBaseContext(), "Long Clicked", Toast.LENGTH_SHORT).show();
               Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               intent.setType("image/*");
               startActivityForResult(Intent.createChooser(intent, "Select Photo"), IMAGE_PICK);
               return true;
           }
       });
   }
   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       if (resultCode == Activity.RESULT_OK) {
           switch (requestCode) {
               case IMAGE_PICKthis.imageFromGallery(resultCode, data);
                   break;
               case IMAGE_CAPTUREthis.imageFromCamera(resultCode, data);
                   break;
               default:
                   break; }
       }
   }
   private void imageFromCamera(int resultCode, Intent data) {
       this.ivUserPhoto.setImageBitmap((Bitmap) data.getExtras().get("data")); }
   private void imageFromGallery(int resultCode, Intent data) {
       Uri selectedImage = data.getData();
       String [] filePathColumn = {MediaStore.Images.Media.DATA};
       Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, nullnullnull);
       cursor.moveToFirst();
       int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
       String filePath = cursor.getString(columnIndex);
       cursor.close();
       this.ivUserPhoto.setImageBitmap(BitmapFactory.decodeFile(filePath));
   }
   private void prepareForm() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       EditText etUserName=(EditText)findViewById(R.id.username);
       EditText etUserPhone=(EditText)findViewById(R.id.userphone);
       EditText etUserEmail=(EditText)findViewById(R.id.useremail);
       ImageView ivUserPhoto=(ImageView) findViewById(R.id.userphoto);
       ImageView ivUserSavedPhoto=(ImageView) findViewById(R.id.usersavedphoto);
       // If value for key not exist then return second param value - In this case "..."
       etUserName.setText(preferences.getString("username""..."));
       etUserPhone.setText(preferences.getString("userphone""..."));
       etUserEmail.setText(preferences.getString("useremail""..."));
       String img_str=preferences.getString("userphoto""");
       if (!img_str.equals("")){
           //decode string to image
           String base=img_str;
           byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
           ivUserPhoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
           ivUserSavedPhoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
       }
   }
   private void checkFirstLogin() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       // If value for key not exist then return second param value - In this case true
       if (preferences.getBoolean("firstLogin"true)) {
           initProfile();
           SharedPreferences.Editor editor = preferences.edit();
           editor.putBoolean("firstLogin"false);
           editor.commit();
       }
   }
   private void initProfile() {
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       SharedPreferences.Editor editor = preferences.edit();
       editor.putString("username","Demo TryTest");
       editor.putString("userphone","01234567890");
       editor.putString("useremail","demotrytest@gmail.com");
       editor.commit();
   }
   public void setProfilePhoto(View view){
       ImageView ivphoto = (ImageView)findViewById(R.id.userphoto);
       //code image to string
       ivphoto.buildDrawingCache();
       Bitmap bitmap = ivphoto.getDrawingCache();
       ByteArrayOutputStream stream=new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG90, stream);
       byte[] image=stream.toByteArray();
       //System.out.println("byte array:"+image);
       //final String img_str = "data:image/png;base64,"+ Base64.encodeToString(image, 0);
       //System.out.println("string:"+img_str);
       String img_str = Base64.encodeToString(image, 0);
       //decode string to image
       String base=img_str;
       byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
       ImageView ivsavedphoto = (ImageView)this.findViewById(R.id.usersavedphoto);
       ivsavedphoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes,0, imageAsBytes.length) );
       //save in sharedpreferences
       SharedPreferences preferences = getSharedPreferences("myprefs",MODE_PRIVATE);
       SharedPreferences.Editor editor = preferences.edit();
       editor.putString("userphoto",img_str);
       editor.commit();
   }
}

4) Orientation Change Problem

The apps may experience image redraw problem (the recent image you put in will disappear) when the device orientation change. To prevent redraw, edit the Manifest as follows.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.notarazi.myprofile" >
   <uses-feature android:name="android.hardware.camera"
       android:required="false" />
   <uses-permission android:name="android.permission.CAMERA" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@style/AppTheme" >
       <activity android:name=".MyProfile"
           android:configChanges="keyboardHidden|orientation|screenSize">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

DOWNLOAD

REFERENCES


.

No comments:

Post a Comment