Friday, 23 September 2016

Android Image Chooser from Gallery and Camera


Java File


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.theme.activity.DialogActivity;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ChosenImages;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.kbeanie.imagechooser.api.IntentUtils;

import java.io.File;

import fastxpo.gurubahi.crm.Constant;
import fastxpo.gurubahi.crm.R;

public class ImageChooserActivity extends DialogActivity implements ImageChooserListener {

    private final static String TAG = "ImageChooserActivity";
    private ImageChooserManager imageChooserManager;
    private String filePath;
    private int chooserType;
    private boolean isActivityResultOver = false;
    private String originalFilePath;
    private String thumbnailFilePath;
    private String thumbnailSmallFilePath;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        setContentView(R.layout.activity_image_chooser2);
        Button buttonTakePicture = (Button) findViewById(R.id.buttonTakePicture);
        Button buttonChooseImage = (Button) findViewById(R.id.buttonChooseImage);
        buttonTakePicture.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                takePicture();
            }
        });
        buttonChooseImage.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                chooseImage();
            }
        });
        checkForSharedImage(getIntent());
    }

    private void chooseImage() {
        chooserType = ChooserType.REQUEST_PICK_PICTURE;
        imageChooserManager = new ImageChooserManager(this,
                ChooserType.REQUEST_PICK_PICTURE, true);
        Bundle bundle = new Bundle();
        bundle.putBoolean(Intent.EXTRA_ALLOW_MULTIPLE, true);
        imageChooserManager.setExtras(bundle);
        imageChooserManager.setImageChooserListener(this);
        imageChooserManager.clearOldFiles();
        try {
            filePath = imageChooserManager.choose();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void takePicture() {
        chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
        imageChooserManager = new ImageChooserManager(this,
                ChooserType.REQUEST_CAPTURE_PICTURE, true);
        imageChooserManager.setImageChooserListener(this);
        try {
            filePath = imageChooserManager.choose();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "OnActivityResult");
        Log.i(TAG, "File Path : " + filePath);
        Log.i(TAG, "Chooser Type: " + chooserType);
        if (resultCode == RESULT_OK                && (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
            if (imageChooserManager == null) {
                reinitializeImageChooser();
            }
            imageChooserManager.submit(requestCode, data);
        } else {
        }
    }

    @Override    public void onImageChosen(final ChosenImage image) {
        runOnUiThread(new Runnable() {

            @Override            public void run() {
                Log.i(TAG, "Chosen Image: O - " + image.getFilePathOriginal());
                Log.i(TAG, "Chosen Image: T - " + image.getFileThumbnail());
                Log.i(TAG, "Chosen Image: Ts - " + image.getFileThumbnailSmall());
                isActivityResultOver = true;
                originalFilePath = image.getFilePathOriginal();
                thumbnailFilePath = image.getFileThumbnail();
                thumbnailSmallFilePath = image.getFileThumbnailSmall();
                if (image != null) {
                    Log.i(TAG, "Chosen Image: Is not null");
                    loadImage(image.getFileThumbnail());
                    loadImage(image.getFileThumbnailSmall());
                } else {
                    Log.i(TAG, "Chosen Image: Is null");
                }
            }
        });
    }

    @Override    public void onImagesChosen(final ChosenImages images) {
        runOnUiThread(new Runnable() {
            @Override            public void run() {
                Log.i(TAG, "On Images Chosen: " + images.size());
                onImageChosen(images.getImage(0));
            }
        });
    }

    private void loadImage(final String path) {
        File image = new File(path);
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
        Constant.bitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
        setResult(RESULT_OK);
        finish();
    }

    @Override    public void onError(final String reason) {
        runOnUiThread(new Runnable() {

            @Override            public void run() {
                Log.i(TAG, "OnError: " + reason);
                Toast.makeText(ImageChooserActivity.this, reason,
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    private void reinitializeImageChooser() {
        imageChooserManager = new ImageChooserManager(this, chooserType, true);
        Bundle bundle = new Bundle();
        bundle.putBoolean(Intent.EXTRA_ALLOW_MULTIPLE, true);
        imageChooserManager.setExtras(bundle);
        imageChooserManager.setImageChooserListener(this);
        imageChooserManager.reinitialize(filePath);
    }

    @Override    protected void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "Saving Stuff");
        Log.i(TAG, "File Path: " + filePath);
        Log.i(TAG, "Chooser Type: " + chooserType);
        outState.putBoolean("activity_result_over", isActivityResultOver);
        outState.putInt("chooser_type", chooserType);
        outState.putString("media_path", filePath);
        outState.putString("orig", originalFilePath);
        outState.putString("thumb", thumbnailFilePath);
        outState.putString("thumbs", thumbnailSmallFilePath);
        super.onSaveInstanceState(outState);
    }

    @Override    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey("chooser_type")) {
                chooserType = savedInstanceState.getInt("chooser_type");
            }
            if (savedInstanceState.containsKey("media_path")) {
                filePath = savedInstanceState.getString("media_path");
            }
            if (savedInstanceState.containsKey("activity_result_over")) {
                isActivityResultOver = savedInstanceState.getBoolean("activity_result_over");
                originalFilePath = savedInstanceState.getString("orig");
                thumbnailFilePath = savedInstanceState.getString("thumb");
                thumbnailSmallFilePath = savedInstanceState.getString("thumbs");
            }
        }
        Log.i(TAG, "Restoring Stuff");
        Log.i(TAG, "File Path: " + filePath);
        Log.i(TAG, "Chooser Type: " + chooserType);
        Log.i(TAG, "Activity Result Over: " + isActivityResultOver);
        if (isActivityResultOver) {
            populateData();
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void populateData() {
        Log.i(TAG, "Populating Data");
        loadImage(thumbnailFilePath);
        loadImage(thumbnailSmallFilePath);
    }

    @Override    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Activity Destroyed");
    }

    private void checkForSharedImage(Intent intent) {
        if (intent != null) {
            if (intent.getAction() != null && intent.getType() != null && intent.getExtras() != null) {
                ImageChooserManager m = new ImageChooserManager(this, ChooserType.REQUEST_PICK_PICTURE);
                m.setImageChooserListener(this);

                m.submit(ChooserType.REQUEST_PICK_PICTURE, IntentUtils.getIntentForMultipleSelection(intent));
            }
        }
    }
}


Layout File


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    tools:context=".activity.ImageChooserActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/buttonTakePicture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin10"
            android:background="@color/white"
            android:text="Take Picture"
            android:textAllCaps="false"
            android:textColor="@color/blue"
            android:textStyle="bold" />

        <Button
            android:id="@+id/buttonChooseImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin10"
            android:background="@color/white"
            android:text="Choose Image"
            android:textAllCaps="false"
            android:textColor="@color/blue"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>




Manifest for this activity

<activity    android:name=".activity.ImageChooserActivity"  
  android:theme="@style/Theme.UserDialog"></activity>


Theme:

<style name="Theme.UserDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">false</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:windowBackground">@android:color/transparent</item>
</style>


Gradel

compile 'com.kbeanie:image-chooser-library:+@aar'

Thank You








Android Sample Matrial Library

use this blow link to make Material Android  Apps


https://material.uplabs.com/posts/c/resources/library



Thank You

Monday, 8 August 2016

Shopping Navigation List with Three Level Expandable Recycler View

SwiftAdapter is an easy to use expandable list recyclerview adapter



Import Using Gradle

compile 'com.vkondrav.swiftadapter:swift-adapter:0.2.0'

Quickstart

Extend the SwiftAdapter
private static class Adapter extends SwiftAdapter<Adapter.ViewHolder> {
Declare you main ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
  public ViewHolder(View itemView) {
    super(itemView);
  }
}
Override count method to declare how many items of that type you will have
@Override
public int getNumberOfLvl0Items() {
  return 10;
}
Override onCreate method to create a specific type of item
@Override
public ViewHolder onCreateLvl0ItemViewHolder(ViewGroup parent) {
  return new ViewHolder(layoutInflater.inflate(R.layout.lvl0_item_layout, parent, false));
}
Override to bind data to the viewholder
@Override
public void onBindLvl0Item(ViewHolder holder, ItemIndex index) {
}

Advanced

There are 4 Levels where the view holders can exist. Each section hosts the items and sections below it.
  • Level 0 Items
  • Level 1 Sections
    • Level 1 Items
    • Level 2 Sections
      • Level 2 Items
      • Level 3 Sections
        • Level 3 Items
Each layer has a set of methods to construct it. By overriding these methods you can create each layer of the list
int getNumberOf_()
ViewHolder CreateViewHolder_()
void BindViewHolder_(ViewHolder holder, ItemIndex)
Open and Close each section by calling these methods and passing ItemIndex from that section.
void openCloseLvl1Section(ItemIndex itemIndex);
void openCloseLvl2Section(ItemIndex itemIndex);
void openCloseLvl3Section(ItemIndex itemIndex);
ItemIndex can always be obtained from the specific OnBind Method or by calling getCurrentItemIndex and passing the ViewHolder for that section
public ItemIndex getCurrentItemIndex(T holder)
Need Source for Android Studio Project below link
https://github.com/vkondrav/SwiftAdapter
Thank You

Wednesday, 1 June 2016

Loading Styles in Android Apllication click to get Source code on below link

Profile Image Choosing with cropping

Java:

import android.app.ActionBar; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.provider.MediaStore; import android.view.MenuItem; import android.view.View; import com.android.framework.utils.Constants; import com.android.theme.activity.AdminBaseActivity; import com.creatah.employeeattendance.R; import com.theartofdev.edmodo.cropper.CropImageView; import java.io.File; import java.util.ArrayList; import java.util.List; public class ImageCropperActivity extends AdminBaseActivity { private CropImageView mCropImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_cropper); setTitle("Image Cropping"); mCropImageView = (CropImageView) findViewById(R.id.CropImageView); startActivityForResult(getPickImageChooserIntent(), 200); } public void onCropImageClick(View view) { Bitmap cropped = mCropImageView.getCroppedImage(ActionBar.LayoutParams.WRAP_CONTENT, 
ActionBar.LayoutParams.WRAP_CONTENT); if (cropped != null) { Constants.bitmap = cropped; setResult(RESULT_OK); finish(); } else { startActivityForResult(getPickImageChooserIntent(), 200); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { Uri imageUri = getPickImageResultUri(data); mCropImageView.setImageUriAsync(imageUri); Constants.ImagePath = String.valueOf(imageUri); } } public Intent getPickImageChooserIntent() { Uri outputFileUri = getCaptureImageOutputUri(); List<Intent> allIntents = new ArrayList<>(); PackageManager packageManager = getPackageManager(); Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); for (ResolveInfo res : listCam) { Intent intent = new Intent(captureIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(res.activityInfo.packageName); if (outputFileUri != null) { intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); } allIntents.add(intent); } // collect all gallery intents Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); galleryIntent.setType("image/*"); List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0); for (ResolveInfo res : listGallery) { Intent intent = new Intent(galleryIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(res.activityInfo.packageName); allIntents.add(intent); } // the main intent is the last in the list (fucking android) so pickup the useless one Intent mainIntent = allIntents.get(allIntents.size() - 1); for (Intent intent : allIntents) { if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) { mainIntent = intent; break; } } allIntents.remove(mainIntent); Intent chooserIntent = Intent.createChooser(mainIntent, "Select source"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()])); return chooserIntent; } private Uri getCaptureImageOutputUri() { Uri outputFileUri = null; File getImage = getExternalCacheDir(); if (getImage != null) { outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg")); } return outputFileUri; } /** * Get the URI of the selected image from {@link #getPickImageChooserIntent()}.<br/> * Will return the correct URI for camera and gallery image. * * @param data the returned data of the activity result */ public Uri getPickImageResultUri(Intent data) { boolean isCamera = true; if (data != null) { String action = data.getAction(); isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE); } return isCamera ? getCaptureImageOutputUri() : data.getData(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; default: break; } return super.onOptionsItemSelected(item); } }

xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.theartofdev.edmodo.cropper.CropImageView android:id="@+id/CropImageView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" custom:cropAspectRatioX="5" custom:cropAspectRatioY="5" custom:cropFixAspectRatio="true" custom:cropScaleType="fitCenter" custom:cropShape="rectangle" android:layout_margin="10dp"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/actionbar_admin" android:onClick="onCropImageClick" android:padding="@dimen/activity_horizontal_margin" android:textAllCaps="false" android:text="Apply" android:textColor="@color/white" /> </LinearLayout>

gradle:

    compile 'com.theartofdev.edmodo:android-image-cropper:1.2.+'

Thursday, 19 May 2016

How to avoid black screen while invoking another activity in android?



Please check the flags you are setting in your intent.

If you have a finish(); or FLAG_ACTIVITY_CLEAR_TASK - a blank screen may show up on
 pre ICS devices as the current activity has been cleared before another activity is started.

code:

Intent intent = new Intent(getApplicationContext(), Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition (0, 0);

Saturday, 2 April 2016

Draw text on bitmap using Canvas.drawText() (Android Watermark in ImageView)

Output :



MainActivity.java

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 Button btnLoadImage1;
 TextView textSource1;
 EditText editTextCaption;
 Button btnProcessing;
 ImageView imageResult;

 final int RQS_IMAGE1 = 1;

 Uri source1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  btnLoadImage1 = (Button)findViewById(R.id.loadimage1);
  textSource1 = (TextView)findViewById(R.id.sourceuri1);
  editTextCaption = (EditText)findViewById(R.id.caption);
  btnProcessing = (Button)findViewById(R.id.processing);
  imageResult = (ImageView)findViewById(R.id.result);
  
  btnLoadImage1.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    Intent intent = new Intent(Intent.ACTION_PICK,
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, RQS_IMAGE1);
   }});
  
  btnProcessing.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    
    if(source1 != null){
     Bitmap processedBitmap = ProcessingBitmap();
     if(processedBitmap != null){
      imageResult.setImageBitmap(processedBitmap);
      Toast.makeText(getApplicationContext(), 
        "Done", 
        Toast.LENGTH_LONG).show();
     }else{
      Toast.makeText(getApplicationContext(), 
        "Something wrong in processing!", 
        Toast.LENGTH_LONG).show();
     }
    }else{
     Toast.makeText(getApplicationContext(), 
       "Select both image!", 
       Toast.LENGTH_LONG).show();
    }
    
   }});
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(resultCode == RESULT_OK){
   switch (requestCode){
   case RQS_IMAGE1:
    source1 = data.getData();
    textSource1.setText(source1.toString());
    break;
   }
  }
 }

 private Bitmap ProcessingBitmap(){
  Bitmap bm1 = null;
  Bitmap newBitmap = null;
  
  try {
   bm1 = BitmapFactory.decodeStream(
     getContentResolver().openInputStream(source1));
   
   Config config = bm1.getConfig();
   if(config == null){
    config = Bitmap.Config.ARGB_8888;
   }
   
   newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
   Canvas newCanvas = new Canvas(newBitmap);
   
   newCanvas.drawBitmap(bm1, 0, 0, null);
   
   String captionString = editTextCaption.getText().toString();
   if(captionString != null){
    
    Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
    paintText.setColor(Color.BLUE);
    paintText.setTextSize(50);
    paintText.setStyle(Style.FILL);
    paintText.setShadowLayer(10f, 10f, 10f, Color.BLACK);
    
    Rect rectText = new Rect();
    paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
    
    newCanvas.drawText(captionString, 
      0, rectText.height(), paintText);
    
    Toast.makeText(getApplicationContext(), 
      "drawText: " + captionString, 
      Toast.LENGTH_LONG).show();
    
   }else{
    Toast.makeText(getApplicationContext(), 
      "caption empty!", 
      Toast.LENGTH_LONG).show();
   }
   
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return newBitmap;
 }

}

activity.xml

<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"
        android:layout_gravity="center_horizontal"
        android:autoLink="web" />

    <Button
        android:id="@+id/loadimage1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Image 1" />
    <TextView
        android:id="@+id/sourceuri1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/processing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Draw text on Bitmap" />
    <ImageView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
</LinearLayout>

Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...