Wednesday, September 27, 2017

Sunday, September 24, 2017

Android Share Action Provider

Welcome to my Blog.
In this post, I am going to talk about android share action provider.

android shareActionProvider tutorial @androidSketchPad


What is Share Action Provider?
Share action provider is just a provider for share some action. we just create a that enable data sharing and also to show a submenu with sharing activities if the hosting item is placed on the overflow menu.

In this post, I will show you how can you add this feature in your app. Let's start What we need to do for adding share action provider? It's very simple step. We just need to create a view on menu.xml file add reference it from the java class. That's it.

First, create an XML file on res -> menu folder
<item android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="ifRoom"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>


Code analysis:
1. android:id -> we need an id for the call this view
2. android:title -> set a title, for this view3. app:showAsAction -> here I use "If room". Also available some other action too.
here a short list of action and their work

  • If room -> if there is enough space on action bar then it will 
  • show always -> it will show this view always in the action bar 
  • never -> for this action, this view will never show
  • collapseActionView -> This item's action view collapses to a normal menu item. 
  • with text -> this will show the icon with text that defines on android: title on the XML file.
4. actionProviderClass -> here we need to set action provider class. We are working on Share action provider, so we need to set-
android.support.v7.widget.ShareActionProvider

Time for java code-
Create a global variable of Share action Provider Class;
ShareActionProvider myShareActionProvider;
Now come on onCreateOptionsMenu() method initializes this by using getActionProvider() method class of MenuItemCompat
myShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
set a share intent
myShareActionProvider.setShareIntent(createShareIntent());
Creta a method that's return Intent
private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        String s = "welocme to android sketchPad";
        shareIntent.putExtra(Intent.EXTRA_TEXT, s);

        return shareIntent;
    }
Now we create another method that name update share action provider: note: don't forget to cheek shareActionProvider is not null
private void resetShareActionProvider(String word) {
        if (myShareActionProvider != null) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, word);

            myShareActionProvider.setShareIntent(shareIntent);
        }
    }
Now you can use this method anywhere you want and update intent for this share action provider.

we just finished all code for adding share action prover. But ...

we can do this also various way, here is another one,
Create a global Variable of ShareActionProvider and initialize it on the on Create menu option (same as previous) now create an Intent where you have data and bind your data on and set this intent to ShareActionProvider variable
see the code:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String s = "welome to Android SketchPad";
shareIntent.putExtra(Intent.EXTRA_TEXT, s);

if (myShareActionProvider != null) {
    myShareActionProvider.setShareIntent(shareInten);
}
       
If you are using loader manager then do this task on the onLoadFinished() method

Fix app crashing: 
If you use proguard in your project, then your app will be crashed on release mode. To fix this you need to add below line on the proguard-project.txt
-keep class android.support.v7.widget.ShareActionProvider { *; }

Final screen shot:
share action provider @android SketchPad


Another One:
Share action Provider 2@android SketchPad


That's it:
That's the ending of today code. now you can add this option to your app. In this post, I just show you a basic tutorial about share action provider. In share action provider I just share text, but you can share image, document, video, audio and much more.

Thanks for reading this post.
Happy coding.

Monday, September 18, 2017

Android Splash Screen right way

Welcome to this post. In this post, I am going to discuss on Android Splash Screen.

splash Screen @androidSketchPad


In this whole post, I gonna cover those topics
1. How to create android Splash Screen
2. How to override default color when app launching (windows background)

When you click app icon, the app takes some time to start. To overcome this option android by default show a color until the activity is launched. By default, it is white in color. So later in this post, I will show you how to overcome this situation and how to change this default color.

Let's start-

Create an Activity named it as your choice

creating an activity android SketchPad


now design your layout file. I just provide my XML code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.blogspot.shudiptotrafder.soilscience.SplashActivity"
    tools:showIn="@layout/activity_splash"
    android:background="?attr/colorPrimary">

    <ImageView
        android:id="@+id/splash_imageView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:srcCompat="@drawable/ic_lover"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        android:contentDescription="app icon"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="80dp"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/splash_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="App Name"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="16dp"
        android:textSize="30sp"
        app:layout_constraintTop_toBottomOf="@+id/splash_imageView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/splash_app"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="16dp"
        android:id="@+id/splash_appAbout"
        android:text="This is a complete app"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

and ic_lover.xml it as vector drawable, code here
<vector android:height="24dp"
    android:viewportHeight="512.0"
    android:viewportWidth="512.0"
    android:width="24dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:fillColor="#FF6464"
        android:pathData="M0,173.5C0,96 62.9,33.1 140.4,33.1c34.4,0 65.9,12.4 90.3,32.9c14.7,12.3 36,12.3 50.7,0c24.4,-20.5 55.9,-32.9 90.3,-32.9C449.1,33.1 512,96 512,173.5v-4.1c0,136.1 -165.6,258.9 -230.4,301.8c-15.5,10.3 -35.7,10.3 -51.2,0C165.6,428.3 0,305.5 0,169.4" />
    <path
        android:fillColor="#D2555A"
        android:pathData="M0,173.5c0,-0.6 0.1,-1.2 0.1,-1.8C0.1,171 0,170.2 0,169.4V173.5z" />
    <path
        android:fillColor="#D2555A"
        android:pathData="M114.8,182.7c-0,0.6 -0.1,1.3 -0.1,1.9v-4.5C114.8,181 114.8,181.9 114.8,182.7c0.5,-66.9 29.4,-123.3 69.2,-142.5c-13.7,-4.5 -28.4,-7.1 -43.6,-7.1c-76.9,0 -139.3,61.9 -140.3,138.6c1.9,135.2 165.9,256.8 230.3,299.4c6.6,4.4 14.1,6.8 21.6,7.4C198.9,418.8 116,306 114.8,182.7z" />
    <path
        android:fillColor="#FF8B8B"
        android:pathData="M449.5,153.9m-32,0a32,32 0,1 1,64.1 0a32,32 0,1 1,-64.1 0" />
    <path
        android:fillColor="#FFC1C1"
        android:pathData="M408.4,92.8m-20,0a20,20 0,1 1,40.1 0a20,20 0,1 1,-40.1 0" />
</vector>

We finished our design option, see the preview
splash screen android SketchPad

it contains an ImageView and two TextView

now time for java coding, SplashScreen.java
public class SplashScreen extends AppCompatActivity {

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

    }

now create an instance of Thread class and in the run methods call sleep methods and pass value 1000 (1000 for 1s, the value of Mille seconds). Don't forget to put this sleep method on try-catch block. and finally, block on try-catch, create an Intent that brings us to MainActivity. At list call finish() method and this activity will be destroyed.
See the code-
Thread checkForData = new Thread(){
      @Override
      public void run() {
            super.run();
            try{
            sleep(1000);

         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             startActivity(new Intent(SplashActivity.this,
                            MainActivity.class));
             finish();
         }
     }
};
start this thread by calling start method
checkForData.start();
That's it. Splash Screen is created successfully. You can run a test for see result.

oh! Your app is not working. I forget one thing that we are using vector drawable. If your app minimum API is 21 then you have no headache. but if you targeting lower API you need to use support library to support vector drawable for lower API. To do that add below line in your build.gradle file
compile 'com.android.support:support-vector-drawable:25.3.1'
Note: change the version according to you compile SDK version. See mine-
compileSdkVersion 25
buildToolsVersion "25.0.3"
One more thing to go. add below code in your activity class
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
ok, run the app again.

Screen Short:
Splash Screen @android SketchPad

Note: Don't be confused I use another app splash screen. Both are used the same code.

Now come on the last topics of this post, create a new theme on style.xml and add windows background color
<style name="splashTheme" parent="AppTheme.NoActionBar">
        <item name="android:windowBackground">@color/colorPrimary</item>
</style>
use this theme on the splash screen activity. Open manifest file and override below code-
<activity
       android:name=".SplashScreen"
       android:label="@string/app_name"
       android:theme="@style/splashTheme">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
</activity>
and my color code is
<color name="colorPrimary">#3F51B5</color>
rerun your app and see the change.

See Screen Short:
Splash Screen2 @android SketchPad


A Bonus for you
I also show you how to animate this splash screen. This is the pretty basic animation example.
Let's do this
create an XML file on res -> anim folder.
splash_screen_animation.xml
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0"
    android:toAlpha="1"
    android:duration = "1000" />
Now load this animation, see code-
Animation set = AnimationUtils.loadAnimation(this,
                R.anim.splash_screen_animation);
In the upper activity code, we don't create view variable, because we don't need that time. But now we need those views add set this animation with those views. Create view and assign it by calling findViewById()
ImageView imageView = (ImageView) findViewById(R.id.splash_imageView);
TextView app = (TextView) findViewById(R.id.splash_app);
TextView appAbout = (TextView) findViewById(R.id.splash_appAbout);
set animation with those views and also start the animation
//set animation
imageView.setAnimation(set);
app.setAnimation(set);
appAbout.setAnimation(set);

//start animation
set.start();
That's it now run the app again and see the animation on your splash screen.

Are you confused about this class SplashScreen.java code?
See all the call code below:
public class SplashScreen extends AppCompatActivity {

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

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

        ImageView imageView = (ImageView) findViewById(R.id.splash_imageView);
        TextView app = (TextView) findViewById(R.id.splash_app);
        TextView appAbout = (TextView) findViewById(R.id.splash_appAbout);


        Animation set = AnimationUtils.loadAnimation(this,
                R.anim.splash_screen_animation);

        //set animation
        imageView.setAnimation(set);
        app.setAnimation(set);
        appAbout.setAnimation(set);

        //start animation
        set.start();

        Thread checkForData = new Thread(){
            @Override
            public void run() {
                super.run();
                try{
                    sleep(1000);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    startActivity(new Intent(SplashActivity.this,
                            MainActivity.class));
                    finish();
               }
             }
         };
        checkForData.start();

    }
}


See full video:

Note: in this video, you can also see the app intro. Link is here: Create Android Material App Intro

That's it 
now you can create a splash screen and also override the loading screen. In this example, I use just the only color but you can also use drawable in the loading time. So it's your choice what you used un your project.

That finished this post.
Why you wasting your time, create an awesome splash screen for your existing or next project?

Thank you for reading this post.
Happy coding.

Android text to speech tutorial

Welcome to this post. In this post, we are going to discuss android text to speech.
Before the start, check the official documentation of Android text to speech.

In my case, I use this option with a fab (Floating action button). When the user clicks on this fab button this text to speech is triggered and user heard the speech.
Let's start,
Implement TextToSpeech.OnIntListener on your activity class.
public class DetailsActivity extends AppCompatActivity implements
        TextToSpeech.OnInitListener {
}

Create an instance of TextToSpeech Class
private TextToSpeech toSpeech;

override onIint() methods and follow below steps:
 1. First, we need to check if Text to speech engine is installed or not
if (status != TextToSpeech.ERROR) {
}
2. If the status is not erroring then we set a default language, we set here the US as default.
int result = toSpeech.setLanguage(Locale.US);
3. now check language data is missing or not supported or not installed then we start for install this text to speech engine.
if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED ||
    result == TextToSpeech.ERROR_NOT_INSTALLED_YET) {

      Intent installIntent = new Intent();
      installIntent.setAction(
              TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
      startActivity(installIntent);

}
if you missing something check the full code of onInit() method
@Override
    public void onInit(int status) {

        if (status != TextToSpeech.ERROR) {

            int result = toSpeech.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA ||
                    result == TextToSpeech.LANG_NOT_SUPPORTED ||
                    result == TextToSpeech.ERROR_NOT_INSTALLED_YET) {

                Intent installIntent = new Intent();
                installIntent.setAction(
                        TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);

            }

        }
    }
Create a method and add a single parameter, word as String. In my case, I named it as setTTS() and parameter is word as String,
setTTS(String selectedWord)
private void setTTS(String selectedWord) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toSpeech.speak(selectedWord, TextToSpeech.QUEUE_FLUSH, null, null);

        } else {
            toSpeech.speak(selectedWord, TextToSpeech.QUEUE_FLUSH, null);
        }

    }
Note: below methods is deprecated. So check if the device is lollipop and higher then use utterance as an extra parameter.

One more thing to go.
We need to shut down this TextToSpeech engine when the activity is destroyed. but before we need to check textToSpeech is null or not to avoid any error. If it is not null the call stop and shutdown method. see the code
@Override
protected void onDestroy() {
   super.onDestroy();
   if (toSpeech != null) {
       toSpeech.stop();
       toSpeech.shutdown();
    }
}

That's it 
you finished writing coding. Now call setTTS() method from anywhere in your project. You can use it as Button onClick or TextView onClick. Just pass a string parameter and call the method. As I told you, at the beginning of this post I am using this option in a fab button. you can that code by the following link. But don't be confused. This is the full activity code, so there is a lot of things with TextToSpeech. Click GitHub link.

Now you can use this code. Hope you understand this TextToSpeech logic. and you will be you use this option in your next or existing project.

Thanks for reading this post.
Happy coding.

Tuesday, September 5, 2017

How to connect firebase directly from android studio

welcome to firebase series.

In this post, we are going to learn about how to connect firebase from the android studio. This is the easiest methods ever.
we can directly connect firebase through the android studio.
Let's start-
open any project or create the new project
I am going throw picture by picture. Follow picture to picture for completing this process.

In android studio click tool and select firebase.
firebase1-androidSketchpad

after click that it will open this window
firebase2-androidSketchpad

Now click any option. In my case, I use analytics
firebase3-androidSketchpad


click log on any event. After it will open this window
firebase4-androidSketchpad

Click connect to firebase
firebase5-androidSketchpad


after the process is finished it will open this window.
firebase6-androidSketchpad

Edit project name (this is for firebase project. it will show in the firebase only)  change your location.
firebase7-androidSketchpad


click on connect to the firebase
firebase8-androidSketchpad

after the finish of this  process, it will show will connect firebase
firebase9-androidSketchpad


succesfully connected now click add analytics to your app
firebase10-androidSketchpad

click accept. it will change your gradle file
firebase11-androidSketchpad

wait for finishing the gradle build.
firebase12-androidSketchpad


after gradle finish, this will show Dependices set up correctly.
firebase13-androidSketchpad

you can add more function by clicking the same process.
firebase14-androidSketchpad

Now go to the firebase console
firebase15-androidSketchpad

this is our newly created process.
firebase15-androidSketchpad

That's it:
we successfully connected our project to firebase. This is the easiest methods ever. you don't need to add JSON file manually. All the file automatically add to your project.

Thank you for reading this post.
Happy coding.