Monday, 9 September 2019

Android Data Binding Updates

Hello Guys i m updating regarding Data Binding features given in  Android Jetpack libraries

Here how we can implement Data Binding in Android its given.

-> This Library allows bind Layouts components with data in xml declaration instead of bind data and ui controls programmatically.

->  Example use the Data Binding  to assign textView in Xml layout.

->  No need to call other Java code

->  use this syntax @{} in assignment of control

Like

<TextView
    android:text="@{pojomodel.userName}" />

do in build.gradle file

android {
...
dataBinding {
    enabled = true}
}

->  in Details under stand like below
-> Create Pojo class.

package com.t.databinding;

public class Pojomodel {

    private String mid;
    private String strname;


    public String getMid() {
        return mid;
    }

    public void setMid(String mid) {
        this.mid = mid;
    }

    public Pojomodel(String id, String name) {
        this.mid = id;
        this.strname = name;
    }

    public String getName() {
        return strname;
    }

    public void setName(String name) {
        this.strname = name;
    }

}


-> Create Layout file like


<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <!--Step 1-->
    <data>
        <!--Step 2-->
        <variable
            name="Pojomodel"
            type="com.t.databinding.Pojomodel" />
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp"
        tools:context="com.androidbytes.databindingdemo.MainActivity">
        <!--Step 3-->
        <TextView
            android:id="@+id/text_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{Pojomodel.mid}"
            android:textColor="@android:color/black"
            android:textSize="26sp" />
        <TextView
            android:id="@+id/text_view_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{Pojomodel.name}"
            android:textColor="@android:color/black"
            android:textSize="18sp" />
    </LinearLayout>
</layout>

-> Create  MainActivity

package com.t.databinding;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.t.databinding.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

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

        //        After Data Binding
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        Pojomodel personVO = new Pojomodel("#1","Abc ");
        binding.setPojomodel(personVO);

    }
}


-> Data Binding  Use in  Application improve app performance , handle null pointer exception,  
    prevent from memory leak
-> Thanks this detail will help full to you for understand about Data Binding usage in Android Application.





Saturday, 7 September 2019

About WorkManager

      Hello guy's here i m going to update some short important points about §  Work Manager will help to understand easily 

§  To perform single and multiple task with enqueue process manage using  Work Requests

§   Now Work Manager with Android Architecture Component and Its comes with Android Jetpack to handle  like  background work thread, and its  guaranteed to  execute to take care of perform Logic within it. It will do your background task  as it can.
      
      What benefits to be use of Work Manager

Its Support for asynchronous one and periodic tasks


Its Support for constraints like network conditions, storage space, and charging status

Its can Chaining of complex work requests, with  running work in parallel   

From one work request Get Output and Its used as input for the next

Compatibility back to API level supports Android 4.0+ (API 14+).

Works with or without Google Play services

Follows system health best practices

       Live Data support to easily display work request state in UI

When need to be use Work Manager

The Work Manager library is a good choice for perform long running tasks that are need to complete, even if the user navigates away from a particular Applications screen
Like below some tasks for good use of Work Manager
  • Applying filtration  to images and save image
  • On Particular Interval time  syncing local data with the network Data
  • Uploading Logs, Data

What you will  need to handle in Work Manager library 


  •  Worker -> You need to get subclass, to perform the task,  that will run in the background.

  •   Work Request -> Its  represents the request of the task that will run. Need to set the task through                                      the Worker subclass. Also You can specify constraints Like, only run the task if                                  the  device has Internet connectivity. There are two main types of work requests: 

  • One Time Work Request -> which can be executes the task just one time,


  • Periodic Work Request -> which can be executes your task periodically. 

                                         This Periodic Work Request can be customized 
                                          as per your needed interval.
  •  Work Status  ->    Whenever you want to know the status of  your  
                            work Request task, running, enqueued, finished etc,

                                 you can ask its to the Work Manager for it. 
                                So It will  provide a Live Data object containing 
                                one or more Work Status objects.

What you will  learn from Work Manager library

  • Passing data Input and output parameters
  • Multiple works request Chaining work
  • Unique work
  • Displaying work status in the UI
  • Adding Work Manager into your project
  • Scheduling a simple Single task execution
  • Cancelling work by Id





Saturday, 27 July 2019

How to make window full screen in android

To make window full screen we have to define one line code in onCreate method,


@Overrideprotected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
  setContentView(R.layout.activity_main);

Done , above one line code in bold font we have to declare for window full screen.

Wednesday, 10 July 2019

Android VideoView with Multimedia controls

Here is the code for play any video using VideoView and with Media Controller

Add below code in your main_activity.xml

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"    
android:layout_alignParentBottom="true"    
android:layout_centerHorizontal="true"    
android:layout_gravity="center"    
android:layout_marginTop="@dimen/d_10dp"    
android:layout_marginBottom="@dimen/d_10dp">

<VideoView    
android:id="@+id/videoview"    
android:layout_width="match_parent"    
android:layout_height="200dp"   />

</RelativeLayout>




Now add below code in MainActivity.java

define your variable first


VideoView videoView;
MediaController mediaControls;

in onCreateView method add below code
videoView = (VideoView)view.findViewById(R.id.videoview);

add below code where you want to play video

String FullVideopath = "Here is your video path";

videoView.setVideoPath(FullVideopath);
mediaControls = new MediaController(mcontext);
mediaControls.setAnchorView(videoView);
videoView.setMediaController(mediaControls);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override    public void onPrepared(MediaPlayer mp) {
        mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
            @Override  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {

                videoView.setMediaController(mediaControls);
                mediaControls.setAnchorView(videoView);
            }
        });
    }
});

viewvideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override    public void onCompletion(MediaPlayer mp) {
        Toast.makeText(mcontext, "Video over...!!!", Toast.LENGTH_LONG).show();
    }
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    @Override    public boolean onError(MediaPlayer mp, int what, int extra) {
        Toast.makeText(mcontext, "Oops An Error Occur While Playing Video...!!!", 
Toast.LENGTH_LONG).show(); 
return false;
    }
});}

Wednesday, 3 July 2019

Android Json response parsing method with Gson

Hello guy's here i  m sharing Json response parsing method to do parse in particular pojo class.
here you need to get your Json response in your String variable before start parsing it.


do this process in Your Class

String result = "Your Json Resonse" ;

List<MUsers> mUsers = null;
                try {
    Gson gson = new Gson();
    Type type = new TypeToken<List<MUsers>>(){}.getType();
    mUsers = gson.fromJson(result, type);
} catch (JsonSyntaxException e) {
    e.printStackTrace();
}

Here  in Your MUsers Class need to contain all require keys to parse it based on your Json response contains no of keys . here explaining with single key value parsing class as below it would be like.

public class MUsers{

    @SerializedName("USR")
    @Expose
    private String usr;

    public void setUSR(String usern) {
        this.usr = usern;
    }

    public String getUSR() {
        return usr;
    }
}



Here  in your build.gradle file need to add supportive library to parse this data

Friday, 28 June 2019

Android Spinner background customize using xml Selector

Here sharing to customize background design of Spinner item  with costume xml file to put in resource drawable  folder and set it in xml Spinner item.

create this xml file in res/drawable folder with name spinner_background.xml
do code for it like as below


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
      <layer-list>
        <item>
          <shape>
            <stroke android:width="1dp" android:color="#dddddd" />
            <padding  android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
            <solid android:color="#FFFFFF" />
        </shape>
       </item>
        <item ><bitmap android:gravity="right|center" android:src="@mipmap/ic_downarrow" />
        </item>
    </layer-list></item>
</selector>


here you need to set ic_downarrow image in mipmap folder as per you need design. will look in Spinner 
right side this image.


Now in your layout,xml file with Spinner item do set this xml file to display costume spinner background 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Spinner
        android:id="@+id/spnitem"
        android:layout_width="200dp"
        android:layout_gravity="center_horizontal"
        android:layout_height="@dimen/editext_size"
        android:overlapAnchor="false"
        android:textSize="@dimen/reg_text_size"
        android:background="@drawable/spinner_background"        />

</LinearLayout> 

Thursday, 27 June 2019

Android updated Api features for Camera to Text detection Example

Here sharing Android  updated Api Features for Optical character recognition(OCR).  with using Camera pictures able to read character for it and can share that read Character to other apps.
To create Application in Android studio follow below steps

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="yourpackageName">
    <uses-permission android:name="android.permission.CAMERA"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" 
        android:value="ocr"/>        
    </application>
</manifest>

build.gradle

dependencies {
    compile 'com.google.android.gms:play-services-vision:11.0.4'}

activity_main.xml

Here we also use Button to share character to other apps.

<?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="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    tools:context="Yourpackage.MainActivity">
    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"
        android:background="@drawable/mboarder"
        android:text="@string/txt_message"
        android:textColor="@android:color/black"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btnShare"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share"
        android:textAllCaps="false"
        android:background="@color/colorAccent"
        android:layout_marginBottom="5dp"
        android:textColor="@android:color/white"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>


MainActivity.java


package your.packageNamehere;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    SurfaceView mCameraView;
    TextView mTextView;
    CameraSource mCameraSource;

    private static final String TAG = "MainActivity";
    private static final int requestPermissionID = 101;
    Button btnShare;
    String ReadString;

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

        mCameraView = findViewById(R.id.surfaceView);
        mTextView = findViewById(R.id.text_view);
        btnShare = findViewById(R.id.btnShare);

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

                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT,ReadString);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);

            }
        });

        startCameraRead();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != requestPermissionID) {
            Log.d(TAG, "Got permission result" + requestCode);
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            try {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mCameraSource.start(mCameraView.getHolder());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void startCameraRead() {
        final TextRecognizer ReadText = new TextRecognizer.Builder(getApplicationContext()).build();
        if (!ReadText.isOperational()) {
            Log.w(TAG, "Detector yet not allow ");
        } else {
            mCameraSource = new CameraSource.Builder(getApplicationContext(), ReadText)
                    .setFacing(CameraSource.CAMERA_FACING_BACK)
                    .setRequestedPreviewSize(1280, 1024)
                    .setAutoFocusEnabled(true)
                    .setRequestedFps(2.0f)
                    .build();
            mCameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override                public void surfaceCreated(SurfaceHolder holder) {
                    try {

                        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.CAMERA},
                                    requestPermissionID);
                            return;
                        }
                        mCameraSource.start(mCameraView.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    mCameraSource.stop();
                }
            });

            ReadText.setProcessor(new Detector.Processor<TextBlock>() {
                @Override                
                public void release() {
                }
               @Override
                public void receiveDetections(Detector.Detections<TextBlock> detections) {
                    final SparseArray<TextBlock> items = detections.getDetectedItems();
                    if (items.size() != 0 ){

                        mTextView.post(new Runnable() {
                            @Override                            public void run() {
                                StringBuilder stringBuilder = new StringBuilder();
                                for(int i=0;i<items.size();i++){
                                    TextBlock item = items.valueAt(i);
                                    stringBuilder.append(item.getValue());
                                    stringBuilder.append("\n");
                                }
                                mTextView.setText(stringBuilder.toString());
                                ReadString  =  stringBuilder.toString();
                            }
                        });
                    }
                }
            });
        }
    }
}

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...