Thursday, May 30, 2019

Recycle listview with dynamic listview raw

Recycle listview is the listview better than a simple list view now here is the code to create Recycle listview with dynamic listview raw. 

First need to add Recycle listview library in build.gradle(Module:app) file


dependencies {

implementation 'com.android.support:recyclerview-v7:28.0.0'

}


Then in activity_main.xml file add below code


<android.support.v7.widget.RecyclerView
 android:id="@+id/rvalphabets"  
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

Then make new xml file recycleview_row.xml and add below code


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"    
 android:layout_height="wrap_content" 
 android:orientation="horizontal"
 android:padding="10dp"    
 android:layout_gravity="center"    
 android:gravity="center">

 <TextView android:id="@+id/tvandroidversionname"
  android:layout_width="match_parent"        
  android:layout_height="wrap_content"        
  android:layout_gravity="center"        
  android:gravity="center"        
  android:text=""        
  android:textSize="35sp"        
  android:textStyle="bold"        
  android:textColor="@color/colorPrimary"/>
    
 <ImageView android:id="@+id/imgview"
  android:layout_width="200dp"        
  android:layout_height="200dp"        
  android:layout_gravity="center"        
  android:gravity="center"        
  android:visibility="gone"/>
</LinearLayout>

Then make new xml file customdialog.xml and add below code


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"    
    android:layout_height="200dp"    
    android:padding="10dp"    
    android:background="@android:color/white">

    <FrameLayout android:id="@+id/frmcustom"
      android:layout_width="match_parent"        
      android:layout_height="200dp"        
      android:background="@color/colorPrimary">
    <ImageButton  android:id="@+id/closebtn"        
         android:layout_width="25dp"        
         android:layout_height="25dp"        
         android:layout_gravity="top|right"        
         android:layout_margin="10dp"
        android:background="@android:drawable/ic_menu_close_clear_cancel"/>

    <TextView  android:id="@+id/tvdialogName"        
       android:layout_width="match_parent"        
       android:layout_height="wrap_content"        
       android:layout_gravity="center"        
       android:gravity="center"        
       android:layout_below="@+id/closebtn"        
       android:text=""        
       android:textSize="25sp"        
       android:padding="10dp"        
       android:textStyle="bold"        
       android:layout_marginTop="20dp"        
       android:textColor="@android:color/white"/>
    </FrameLayout>
</RelativeLayout>

And then make one Adapter for recycle list view 
MyRecycleViewAdapter.java and add below code


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MyRecyclerViewAdapter extends 
RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    Context mContext;

    // data is passed into the constructor    
MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        mContext = context;
    }

    // inflates the row layout from xml when needed    
@Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row    
@Override    public void onBindViewHolder(ViewHolder holder, int position) {
        String alphabet = mData.get(position);
        holder.myTextView.setText(alphabet);
    }

    // total number of rows    @Override    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen    
public class ViewHolder extends RecyclerView.ViewHolder 
implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvAlphabetsName);
            itemView.setOnClickListener(this);

        }

        @Override        public void onClick(View view) {
            if (mClickListener != null) 
mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position    
String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught    
void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events    
public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

And final code in MainActivity.java


import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements 
MyRecyclerViewAdapter.ItemClickListener{

    Context mcontext;
    MyRecyclerViewAdapter adapter;
    String gettext;

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

        mcontext =  MainActivity.this;

        // data to populate the RecyclerView with       
 ArrayList<String> alphabetsNames = new ArrayList<>();
        alphabetsNames.add("Android Cupcake.");
        alphabetsNames.add("Android Donut.");
        alphabetsNames.add("Android Eclair.");
        alphabetsNames.add("Android Froyo.");
        alphabetsNames.add("Android Gingerbread.");
        alphabetsNames.add("Android Honeycomb.");
        alphabetsNames.add("Android Ice Cream Sandwich.");
        alphabetsNames.add("Android Jelly Bean.");

        alphabetsNames.add("Android KitKat");
        alphabetsNames.add("Android Lollipop");
        alphabetsNames.add("Android Marshmallow");
        alphabetsNames.add("Android Nougat");
        alphabetsNames.add("Android Oreo");
        alphabetsNames.add("Android Pie");

        // set up the RecyclerView       
 RecyclerView recyclerView = findViewById(R.id.tvandroidversionname);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new MyRecyclerViewAdapter(this, alphabetsNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);

    }
    @Override    public void onItemClick(View view, int position) {

        gettext = adapter.getItem(position);
        // custom dialog        final Dialog dialog = new Dialog(mcontext);
        dialog.setContentView(R.layout.customdialog);
        // set the custom dialog components - text, image and button        
TextView text = (TextView) dialog.findViewById(R.id.tvdialogName);
        ImageButton closebtn = (ImageButton)dialog.findViewById(R.id.closebtn);
        text.setText(gettext);
        closebtn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }
}




Monday, May 27, 2019

Android TextToSpeech

Android Text to Speech is the proceed to speech the text which ever you want.
below is the code for Text to speech. 


public class MainActivity extends AppCompatActivity implements
TextToSpeech.OnInitListener{
TextToSpeech textToSpeech;
@Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);
    textToSpeech = new TextToSpeech(mcontext, MainActivity.this);
TextToSpeechFunction();
}
public void TextToSpeechFunction() {     String textholder = "Test the TextToSpeech";
    textToSpeech.speak(textholder, TextToSpeech.QUEUE_FLUSH, null);   //  Toast.makeText(MainActivity.this , textholder, Toast.LENGTH_LONG).show(); } @Override public void onDestroy() {     textToSpeech.shutdown();     super.onDestroy(); } public void onInit(int Text2SpeechCurrentStatus) {     if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {         textToSpeech.setLanguage(Locale.US);         TextToSpeechFunction();     } }
}

How to get Device IME Number in Android Programmatically


Need to add require permission in AndroidMenifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Now need to Allow user permission at run time in your AppCompatActivity

public void FindIME() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // your READ_PHONE_STATE permission yet not granted.
            DevicePermission();
        } else {
            // your READ_PHONE_STATE permission is already been granted.
            ActivityCompat.requestPermissions(FlashScreen.this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
            GetIME();
        }
    }

//Here we need to ask for user  permission

private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private void DevicePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
   
       new AlertDialog.Builder(FlashScreen.this)
                    .setTitle("Permission Request")
                    .setMessage(getString(R.string.permission_read_phone_state_rationale))
                    .setCancelable(false)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //re-request
                            ActivityCompat.requestPermissions(FlashScreen.this,
                                    new String[]{Manifest.permission.READ_PHONE_STATE},
                                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
                        }
                    })
                    .setIcon(R.drawable.ic_login)
                    .show();
        } else {
            // READ_PHONE_STATE permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }
 }

public void GetIME() {
        String deviceUniqueIdentifier = null;
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (null != tm) {
            deviceUniqueIdentifier = tm.getDeviceId();
        }
        if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
            deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        }

        IME_Device = deviceUniqueIdentifier;
        Log.i("Device Ime", "Value--------->" + IME_Device);
     
    }

@Override
 public void onRequestPermissionsResult(int requestCode,
 String permissions[], int[] grantResults) {
        switch (requestCode) {

            case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted!
                 
                    GetIME();
                } else {
                    // permission denied
                    Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
                }
            }
            break;

            case PERMISSION_READ_STATE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted!
                 
                } else {
                    // permission denied
                    Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
                }

            }
            break;
        }

    }

Saturday, May 25, 2019

Apply Multiple Permissions RunTime

How to  give and apply run time multiple permissions in android,

First yo have to add permissions in Manifest file like below.

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Then, you have to code for the check permissions,add button in activitymain.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    
xmlns:android="http://schemas.android.com/apk/res/android"    
android:id="@+id/root_layout"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:padding="16dp"    
android:orientation="vertical"    
android:background="#e5ead3"   
android:gravity="center" >
    
<Button        
android:id="@+id/btn_do_task"        
android:layout_width="wrap_content"        
android:layout_height="wrap_content"        
android:text="Check Permissions"        
android:layout_gravity="center"/>
</LinearLayout>

After add button in xml file now add code in MainActivity.java file

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private Button btn_checkpermi;

    private static final int MY_PERMISSIONS_REQUEST_CODE = 123;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();
        mActivity = MainActivity.this;
        
        btn_checkpermi = findViewById(R.id.btn_checkpermi);

        btn_checkpermi.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    checkPermission();
                }
            }
        });
    }

    protected void checkPermission(){
        if(ContextCompat.checkSelfPermission(mActivity,Manifest.permission.CAMERA)
                + ContextCompat.checkSelfPermission(
                mActivity,Manifest.permission.READ_CONTACTS)
                + ContextCompat.checkSelfPermission(
                mActivity,Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){

            // when permissions not granted            
             if(ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.CAMERA)
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.READ_CONTACTS)
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    mActivity,Manifest.permission.READ_EXTERNAL_STORAGE)){
                // If we should give explanation of requested permissions
                // Show an alert dialog for request explanation                
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setMessage("Camera, Read Contacts and Read External" +
                        " Storage permissions are required to do the task.");
                builder.setTitle("Please grant those permissions");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
                {
                    @Override                    
                public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(
                                mActivity,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_CONTACTS,
                                        Manifest.permission.READ_EXTERNAL_STORAGE },
                                MY_PERMISSIONS_REQUEST_CODE  );
                    }
                });
                builder.setNeutralButton("Cancel",null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }else{
                //  request directly required permissions                
                        ActivityCompat.requestPermissions(
                        mActivity,
                        new String[]{
                                Manifest.permission.CAMERA,
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_CODE );
            }
        }else {
            // Do your stuff here, permissions are already granted            
     Toast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show();
        }
    }

    @Override    
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CODE:{
                // When request is cancelled, the results array are empty                
                    if(
                        (grantResults.length >0) &&
                                (grantResults[0]
                                        + grantResults[1]
                                        + grantResults[2]
                                        == PackageManager.PERMISSION_GRANTED                                )
                ){
                    // Permissions are granted                    
                    Toast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show();
                }else {
                    // Permissions are denied                    
                   Toast.makeText(mContext,"Permissions denied.",Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}

Yeah , you have done with code and below is the result of checking permissions run time.



Thursday, May 23, 2019

Camera Permission Programatically

Android newer version need permissions on run time so late's learn one of the Camera permission how we can implement on run time in android pro grammatically.

First you need to add permission in Android Manifest file



<uses-permission android:name="android.permission.CAMERA" />

Then you have to add below code where you want to give permission for Camera.


ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA},

1);

Then the below code you have to put.
@Overridepublic void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {

            // If request is cancelled, the result are empty.            
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted,  Do the code
               
            } else {

                // permission denied, 
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }

    }
}

You have done the code for Camera permission.

Tuesday, May 7, 2019

Bitmap Compress reduce size and Compress format

Here you can reduce Bitmap Size and Compress in specific file format

//Bitmap bitmap = your Bitmap

File file = new File(Environment.getExternalStorageDirectory(),"test1.jpg");
String filename = file.getAbsolutePath();
try (FileOutputStream out = new FileOutputStream(filename)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// bmp is your Bitmap instance
// PNG format using for compression factor (100) is ignored
} catch (IOException e)
{
e.printStackTrace();
}

Saturday, May 4, 2019

Android on Button click take Camera Picture in Fragment and Save on ExternalStorage

Fragment 
do with below Button Click code

mCamerabtn.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());


        if (checkPermission(wantCameraPermission)) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory(),"test.jpg");

            outputFileUri = Uri.fromFile(file);

            Log.d("TAG", "outputFileUri intent" + outputFileUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, 111);

        } else {

            requestPermission(wantCameraPermission, PERMISSION_REQUEST_CODE_Camera);
        }

        dialog.cancel();

    }

});

Check for require permission above 6.0

private boolean checkPermission(String permission) {
    if (Build.VERSION.SDK_INT >= 23) {
        int result = ContextCompat.checkSelfPermission(mcontext, permission);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {

            return false;
        }
    } else {
        return true;
    }
}

private void requestPermission(String permission, int permission_requestcode) {

        requestPermissions(new String[]{permission}, permission_requestcode);
}

@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grants) {
    List<Fragment> fragments = getChildFragmentManager().getFragments();

    //==================Start
    switch (requestCode) {

        case PERMISSION_REQUEST_CODE_Camera:


            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory(),

                    "test.jpg");

            outputFileUri = Uri.fromFile(file);
            Log.d("TAG", "outputFileUri intent" + outputFileUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            getActivity().startActivityForResult(intent, 111);

            break;
        case PERMISSION_REQUEST_CODE:
            if (grants.length > 0 && grants[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(mcontext, "Permission Granted. Now you can Read data.",
                        Toast.LENGTH_LONG).show();

                ImageLoad();
            } else {
                Toast.makeText(mcontext, "Permission Denied. You cannot Read data.",
                        Toast.LENGTH_LONG).show();
            }
            break;
    }

    //================End
    if (fragments != null) {
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                fragment.onRequestPermissionsResult(requestCode, permissions, grants);


            }
        }
    }
}


After Intent pass, we can Create Bitmap from Uri Code within onActivityResult

@Overridepublic void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {

        case 111:
if (resultCode == RESULT_OK) {

    Log.d("TAG", "outputFileUri RESULT_OK" + outputFileUri);

    if (outputFileUri != null) {

    Bitmap bitmap = decodeSampledBitmapFromUri(outputFileUri300400);

      // Now this Bitmap you can set as per need in Imageview  imagePhoto
    imagePhoto.setImageBitmap(bitmap);

 break;
}
}


Here in below function we  need to pass Uri, int reqWidth, int reqHeight

public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
        Bitmap bm = null;

        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options);
            // Calculate inSampleSize            
           options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            // Decode bitmap with inSampleSize set            
            options.inJustDecodeBounds = false;

            bm = BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mcontext, e.toString(), Toast.LENGTH_LONG).show();
        }
        return bm;

    }
      

Hope this code will help you .