Sunday, May 26, 2019

Recyclerview

Recycler view is much better than listview because the data is called only at runtime so it is much faster and useable the code to get recyclerview is given below


Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.apkglobal.recyclerview">

    <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>
    </application>

</manifest>

MainActivity.java

package com.vishal.recyclerview;

import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
    List<Data> list;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recyclerview);
        //to add linear layout to recycler view 
       recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // to add gridview layout 
     //  recyclerView.setLayoutManager(new GridLayoutManager(this,2));
        Myadapter myadapter=new Myadapter();
        recyclerView.setAdapter(myadapter);

    }

    private class Myadapter extends RecyclerView.Adapter<MyHolder> {
public  Myadapter(){

   list= new ArrayList<>();
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sab tv",R.mipmap.ic_launcher));
    list.add(new Data("aap tv",R.mipmap.ic_launcher));
    list.add(new Data("& tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));
    list.add(new Data("sony tv",R.mipmap.ic_launcher));

}
// to attach the design Xml 
       @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view= LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.item,viewGroup,false);
            MyHolder myHolder=new MyHolder(view);

            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
    Data data=list.get(i);
    myHolder.textView.setText(data.getName());
    myHolder.imageView.setImageResource(data.getImage());

        }

        @Override        public int getItemCount() {
            return list.size();
        }
    }

    private class MyHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            imageView=itemView.findViewById(R.id.image);
            textView=itemView.findViewById(R.id.name);
        }
    }
}

activitymain.xml

<?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" 
   tools:context=".MainActivity">

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


    </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

POJO class

package com.vishal.recyclerview;

class Data {
    String name;
    int image;

    public Data(String name, int image) {
        this.name = name;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public int getImage() {
        return image;
    }
}

item.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"  
      android:layout_height="250dp"
        android:scaleType="center" />

    <TextView 
       android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3200BCD4" 
       android:padding="5dp" 
       app:layout_constraintBottom_toBottomOf="@+id/image" />

</android.support.constraint.ConstraintLayout>

Saturday, May 25, 2019

Splash screen

Splash screen are used in android apps in the beginning of app when the user open the app.they are used to give app a little time to load data from server at beginning for for loading app content and providing user better UI interface.

NOTE:keep the image in your drawable and then access it in your xml file.


Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
package="com.apkglobal.splashscreen">

    <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>
    </application>

</manifest>

Java file

package com.splashscreen;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
private  static  int splash_time_out=4000;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Handler().postDelayed(new Runnable() {
            @Override            public void run() {
                Intent intent=new Intent(MainActivity.this,HomeActivity.class);
                startActivity(intent);
                finish();
            }
        },splash_time_out);

    }
}

XML file

<?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"    
 tools:context=".MainActivity">

    <LinearLayout      
   android:layout_width="match_parent"       
   android:layout_height="match_parent"        
   android:background="#8BC34A"      
   android:gravity="center"     
   android:orientation="vertical">

        <ImageView          
  android:id="@+id/logo"          
  android:layout_width="200dp"          
  android:layout_height="200dp"          
  android:src="@drawable/sample" />

        <TextView           
 android:layout_width="wrap_content"           
 android:layout_height="wrap_content"           
 android:text="Splash screen"           
 android:textSize="50sp"
            />

    </LinearLayout>
</android.support.constraint.ConstraintLayout>

Sunday, May 19, 2019

progressbar

Progress bar are used at the time of loading data from the server it is very simple to apply progress bars.The code for the same is given below


Xml code


<ProgressBar  
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"  
  android:id="@+id/progress"   
  app:layout_constraintTop_toTopOf="parent"  
  app:layout_constraintLeft_toLeftOf="parent"  
  app:layout_constraintRight_toRightOf="parent"  
  app:layout_constraintBottom_toBottomOf="parent"/>


Javacode

Intialization

ProgressBar progressBar;


Typecating

progressBar=findViewById(R.id.progress);

Setting visibility

progressBar.setVisibility(View.VISIBLE);



Webview

Web view is used in android development to convert a website into application.It is used when we have no control of database therefore  functionality  is controlled by website. the code to make a web view application is below.



Manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  package="com.vishal.mimitmalout">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <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>
    </application>

</manifest>

MainActivity.java

package com.vishal.mimitmalout;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AlertDialogLayout;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
WebView web;
ProgressBar progressBar;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        web=findViewById(R.id.web);
        progressBar=findViewById(R.id.progress);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("https://mimitmalout.ac.in/");
        web.setWebViewClient(new WebViewClient());
        web.setWebViewClient(new Myclient());



    }

    @Override    public void onBackPressed() {
        if (web.canGoBack()){
            web.goBack();
        }
        else{
            AlertDialog.Builder ab=new AlertDialog.Builder(this);
            ab.setTitle("Exit");
            ab.setMessage("Do you want to close  application");
            ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override                public void onClick(DialogInterface dialog, int which) {
                   MainActivity.super.onBackPressed();
                }
            });
            ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            ab.setCancelable(false);
            ab.create();
            ab.show();
        }


    }

    private class Myclient extends WebViewClient {

        @Override        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            progressBar.setVisibility(View.VISIBLE);
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }
    }
}

activity_main.xml

<?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"    
tools:context=".MainActivity">

 <WebView       
 android:layout_width="match_parent"      
 android:layout_height="match_parent"      
 android:id="@+id/web">
</WebView>
<ProgressBar   
 android:layout_width="wrap_content"   
 android:layout_height="wrap_content"
 android:id="@+id/progress"   
 app:layout_constraintTop_toTopOf="parent"  
 app:layout_constraintLeft_toLeftOf="parent"  
 app:layout_constraintRight_toRightOf="parent"    
 app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>





Wednesday, May 15, 2019

Check internet connection



In android we  have to build applications which require internet therefore there is need to check whether the internet in connected to device or not. I have written a simple example to check the internet connection the code is given below:



when internet is OFF
when internet is ON









































Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  package="com.apkglobal.blog_connection">

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

    <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>
    </application>

</manifest>

MainActivity.java
public class MainActivity extends AppCompatActivity {
    Context _context;


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


        ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {

                        Toast.makeText(this, "Internet is connected", Toast.LENGTH_SHORT).show();

                    }
                    else {
                        Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
                    }
                }
            }

  }
 else {
            Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
        }
    }
}
       

activitymain.xml


<?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" 
   tools:context=".MainActivity">

    <TextView       
    android:layout_width="wrap_content"     
    android:layout_height="wrap_content"   
    android:text="Hello World!"        
       app:layout_constraintBottom_toBottomOf="parent"  
       app:layout_constraintLeft_toLeftOf="parent" 
       app:layout_constraintRight_toRightOf="parent" 
       app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>




Tuesday, May 14, 2019

Runtime permissions in android

Run time permissions were launched in Android marshmallow  and greater versions of android. The run time permissions are very necessary and must be provided by user to access the critical information of mobile like location, contacts, gallery,etc

The description and code to build run time permission is given below.

1.To check whether  the version of mobile is  greater than marshmallow or not
   
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)

2.To check whether  the permissions are given in manifest file

   if (checkSelfPermission(Manifest.permission.READ_CONTACTS) !=

  PackageManager.PERMISSION_GRANTED)

3.To show the dialog box  to request permission from user

   if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
         requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},1);
        }

4. Now we need to call the override method outside on create and write its content

   @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 1) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show();


        }

    }
}
5. Now provide uses permission in manifest for the permission e.g
    
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>


 Here every thing is done for run time permission

Below is the example for permission for reading contacts



Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.apkglobal.blog_runtime_permission">
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <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>
    </application>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //to check mobile permission          
  if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                // to display               
 if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {

                    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 1);
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
                }
            }
        } else {
        }

    }
 @Override 
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show();


            }

        }
    }
}
activity_main.xml

<?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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Alert Dialog Box

Alert Dialog Box Android AlertDialog   can be used to display the dialog message with OK and Cancel buttons. It can be used to inter...