Monday, 11 October 2021

Auto phone number read in android sample example

Manifest.xml


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

Layout xml file:
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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"
android:orientation="vertical">

<TextView
android:id = "@+id/phoneNumber"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "phone number"
android:layout_marginTop="@dimen/padding_40dp"/>
</LinearLayout>









Fragment:


 package com.example.questionpaper.Screens.mytest;


import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.example.questionpaper.Activity.ContainerActivity;
import com.example.questionpaper.Common.Utility;
import com.example.questionpaper.R;

import static android.Manifest.permission.READ_PHONE_NUMBERS;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.READ_SMS;

public class NotificationsScreenFragment extends Fragment {
private ProgressDialog pDialog;
private ContainerActivity activity;
TextView phoneNumber;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.notifications_screen_fragment,container,false);
this.activity=(ContainerActivity) getActivity();
pDialog= Utility.getProgressDialog(getActivity());
initViews(v);
return v;
}

private void initViews(View v) {
phoneNumber= v.findViewById(R.id.phoneNumber);

if (ActivityCompat.checkSelfPermission(getContext(), READ_SMS) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), READ_PHONE_NUMBERS) ==
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
TelephonyManager tMgr = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
phoneNumber.setText(mPhoneNumber);
return;
} else {
requestPermission();
}
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, 100);
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
TelephonyManager tMgr = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_SMS) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
String mPhoneNumber = tMgr.getLine1Number();
phoneNumber.setText(mPhoneNumber);
break;
}
}
}




Sunday, 4 December 2016

How to show notification with navigation to another Activity in android?

NotificationCompat.Builder b=new NotificationCompat.Builder(this);
b.setSmallIcon(R.drawable.ic_launcher); b.setContentTitle("My Notification"); b.setContentText("click here to navigate Activity2"); Date d=new Date(); long i=(long)d.getTime(); Intent notificationIntent=new Intent(this,Activity2.class); PendingIntent pintent=PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT); b.setContentIntent(pintent); NotificationManager nManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); nManager.notify((int)i,b.build());

Monday, 21 November 2016

AutoComepleteTextView example in android?

AutoCompleteTextView:
          Android AutoCompleteTextView is an editable text field, it displays a list of suggestions in a drop down menu automatically while the user is entering the characters from which user can select only one suggestion.
              To use AutoCompleteTextView you have to first create an AutoCompleteTextView field in the xml file. its syntax is given below.

<AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:id="@+id/actv"
        android:completionThreshold="1"
/>

After this now get the reference of AutoComepleteTextView as below.
AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.actv);

The next thing you need to do is to specify the list of suggestions items to be displayed. You can specify the list items as an ArrayList in java. Syntax is given below.

final ArrayList<String> list=new ArrayList<String>();
  list.clear();
  list.add("India");
  list.add("Pakistan");
  list.add("china");
  list.add("US");
 
ArrayAdapter<String> adp=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,list);
actv.setAdapter(adp);

The array adapter class is responsible for displaying the data as list in the suggestion box of the text field. The setAdapter method is used to set the adapter of the autoCompleteTextView. Apart from these methods, the other methods of Auto Complete are listed below.        

Sr.No
Method & description
1
getAdapter()
This method returns a filterable list adapter used for auto completion
2
getCompletionHint()
This method returns optional hint text displayed at the bottom of the the matching list
3
getDropDownAnchor()
This method returns returns the id for the view that the auto-complete drop down list is anchored to.
4
getListSelection()
This method returns the position of the dropdown view selection, if there is one
5
isPopupShowing()
This method indicates whether the popup menu is showing
6
setText(CharSequence text, boolean filter)
This method sets text except that it can disable filtering
7
showDropDown()
This method displays the drop down on screen.


Android AutoCompleteTextView Example:

Step1)  In order to use AutoCompleteTextView you have to first create an AutoCompletTextView Field in the xml. Its syntax is given below. Create activity.xml file in layout folder and write the below code.
activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"  tools:context="home.actvtest.MainActivity">  

    <AutoCompleteTextView    
         android:layout_width="match_parent" 
         android:layout_height="70dp"    
         android:id="@+id/actv"     
         android:completionThreshold="1"/>

</RelativeLayout>


Step 2) Create MainActivity.java in java folder and write the below code.
MainActivity.java

package home.actvtest;
import
android.app.Activity;
import
android.os.Bundle;
import
android.widget.ArrayAdapter;
import
android.widget.AutoCompleteTextView;
import
java.util.ArrayList;

public class
MainActivity extends Activity
{
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
setContentView(R.layout.activity_main);


       
AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.actv);

        final
ArrayList<String> list=new ArrayList<String>();
       
list.clear();

       
list.add("India");
       
list.add("Pakistan");
       
list.add("china");
       
list.add("US");
       
list.add("Banglaedesh");
       
list.add("Barma");
       
list.add("Rashya");
       
list.add("Iran");
       
list.add("Iraq");
       
list.add("Itali");
       
list.add("Brezil");
       
list.add("Srilanka");

       
ArrayAdapter<String> adp=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,list);

       
actv.setAdapter(adp);

   
}
}
 
 
Step3) write the below code in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="home.actvtest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>



Output:










Monday, 14 November 2016

Java Interview questions and Answers?

Q: What is the difference between Abstract class and interface?

Ans:


Abstract Class
Interface
1) Abstract class can have abstract and non- abstract methods. 1) Interface can have only abstract methods.
2) It doesn't support Multiple Inheritance. 2) Interface Supports Multiple Inheritance
3) Abstract keyword is used to declare Abstract class 3) interface keyword is used to declare an interface.
4) Abstract class can contain static,non-static, final, non-final variables. 4) by default Interface variables are only static & final.
5) Abstract class can have static methods, main method. 5) Interface can't contain static method , main method.
6) Abstract class can contains Constructors 6) Interface can't contain Constructors.
7) Abstract class methods can be declared with public and non-public 7) By default all interface methods are public & abstract.
8) A abstract class can provide implement of interface. 8) A interface can't provide implementation of abstract class.
9) A abstract class can extends only one class. 9) A interface can extends any number of interfaces.
10) Object class is super class to all classes. 10) There is no super class for interface.
Ex:


public abstract class B
{
      public abtract void fun1();
      void fun2();
}


public class A extends B
{
    public void fun1()
    {
           System.out.println("fun1 of class A is    calling");
    }


    public void fun2()
   {
        System.out.println("fun2 of class A is calling");
    }




   public static void main(String[] a)
   {
          A a1=new A();
          a1.fun1();
          a1.fun2();
   }


}




O/P:
fun1 of class A is calling
fun2 of class A is calling




Ex:


interface B
{
     int x=10;
     void fun1();
}


public class A  implements  B
{


     public void fun1()
     {
         System.out.println("fun1 of class A is calling");
     }









   public static void main(String[] a)
  {
         A a1=new A();
         a1.fun1();

   }


}




O/P:
fun1 of class A is calling

Friday, 11 November 2016

RecyclerView with CardView in android example?

RecyclerView:

    RecyclerView is more advanced and flexible alternative for ListView. In ListView custom adapter every time it will create new object for UI binding. where as coming to RecyclerView it won't create multiple times. View will created only once.





   In order to implement RecyclerView, first of all we need to decide the Layout Manager for RecyclerView.

LayoutManager type:
1) LinearLayoutManager               :  It shows the items in vertical or horizontal scrolling list.
2) GridLayoutManager                  :  Shows items in a grid.
3) StaggeredGridLayoutManager  :  Shows items in a staggered grid.


CardView
       CardView is used to show the information inside a card which is consistent. By using this we can apply shadow effect, rounded corner etc. To show shadow effect there is a property called card_view:cardElevetion attribute. in order to show rounded corners card_view:cardCornerRadius property.

Example Sample project to display names & initials names of friends.

Step 1: For Accessing RecyclerView & CardView, First we need to import few libraries in build.gradle file of app.


compile 'com.android.support:appcompat-v7:23.0+'
compile 'com.android.support:recyclerview-v7:23.0+'
compile 'com.android.support:cardview-v7:23.0+'


So build.gradle file of app level looks like this.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.example.srikanthp.rctest"       
        minSdkVersion 15        
        targetSdkVersion 23        
        versionCode 1        
        versionName "1.0"    
    }
    buildTypes {
        release 
         {
            minifyEnabled false            
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'    
    compile 'com.android.support:appcompat-v7:23.0+'   
    compile 'com.android.support:recyclerview-v7:23.0+'    
    compile 'com.android.support:cardview-v7:23.0+'
}




Steps 2: Create a xml file in layout folder with the name of activity_main.xml and paste the below code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
       tools:context="com.example.srikanthp.rctest.MainActivity">

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

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

</RelativeLayout>


Step 3: Now create a class with the name of MainActivity.java and paste the below code.

package com.example.srikanthp.rctest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends Activity
{
    ArrayList<String> first_names,initials_names;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager lManager;

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

        getData();

        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
        lManager=new LinearLayoutManager(this);

        recyclerView.setLayoutManager(lManager);
        adapter=new MyAdapter(first_names,initials_names);

        recyclerView.setAdapter(adapter);
    }



    public void getData()
    {
        first_names=new ArrayList<String>();
        first_names.clear();
        first_names.add("SrikanthP");
        first_names.add("Mahesh");
        first_names.add("Naveen");
        first_names.add("Srinivas");
        first_names.add("Pawan");
        first_names.add("SrikanthK");
        first_names.add("Ramakanth");
        first_names.add("Sathish");
        first_names.add("Sridhar");
        first_names.add("Vishwanath");

        initials_names=new ArrayList<String>();
        initials_names.clear();
        initials_names.add("Patel");
        initials_names.add("Thippal");
        initials_names.add("Veerabattini");
        initials_names.add("Vanka");
        initials_names.add("Motkuri");
        initials_names.add("Kadari");
        initials_names.add("Kota");
        initials_names.add("Gangishetty");
        initials_names.add("Metraskar");
        initials_names.add("Kota");
    }

}
 
Note : for creating adapter class we need to create mydapter.xml(in layout folder) & MyAdapter.java(in java folder) .

Step 4: Now create myadaper.xml file in layout folder and paste the below code.
 


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"   
    android:orientation="horizontal"
    android:layout_width="match_parent"  
    android:layout_height="match_parent"   
    android:layout_margin="10dp"   
    xmlns:app="http://schemas.android.com/apk/res-auto">
        <android.support.v7.widget.CardView            
          android:layout_width="match_parent"          
          android:layout_height="match_parent"          
          app:cardCornerRadius="10dp"   
          android:elevation="10dp">

           <LinearLayout      
               android:layout_width="match_parent"   
               android:layout_height="match_parent"
               android:orientation="horizontal">

                  <TextView 
                    android:id="@+id/tvNames"
                    android:layout_width="0dp"
                    android:layout_weight="0.6"
                    android:layout_height="wrap_content"
                    android:text="Names.."
                    android:textSize="30sp"
                    android:textStyle="bold"/>

                <TextView 
                    android:id="@+id/tvInitials"
                    android:layout_width="0dp"
                    android:layout_weight="0.6"
                    android:layout_height="wrap_content"
                    android:text="Initial names.."
                    android:textSize="30sp"
                    android:textStyle="bold"/>

            </LinearLayout>

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

</LinearLayout>



Step 5: Create a class with the name of MyAdapter.java and paste below code.

package com.example.srikanthp.rctest;

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

import java.lang.reflect.Array;
import java.util.ArrayList;

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

    ArrayList<String> names,initials;


    public MyAdapter(ArrayList<String> nm,ArrayList<String> nt)
    {
        this.names=nm;
        this.initials=nt;
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder
    {
        TextView tvNames,tvInitials;

        public ViewHolder(View v)
        {
            super(v);
            tvNames=(TextView)v.findViewById(R.id.tvNames);
            tvInitials=(TextView)v.findViewById(R.id.tvInitials);
        }
    }

    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.myadapter,parent,false);

        ViewHolder hold=new ViewHolder(v);

        return hold;
    }

    @Override    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.tvNames.setText(names.get(position));
        holder.tvInitials.setText(initials.get(position));
    }

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

}