Wednesday, September 29, 2021

Where am I ? Location Based Services @FusedLocationProviderClient

 "Jai Sarawati Maa"

Location Based Services 

The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, wrong-side-of-the-street detection, geofencing, and activity recognition. 

The API updates your app periodically with the best available location, based on the currently-available location providers such as WiFi and GPS (Global Positioning System). 

I am uploading how to find out your current location and address by using FusedLocationProviderClient. Which is the best way to deal with location based activities.  

Step-I: Open Android SDK Manager and check either Google Play Services Installed or not. if not please install google play services. See the below pic. 


  

Step-II: After installation kindly add below dependencies in module level gradle file. 

implementation 'com.google.android.gms:play-services-location:18.0.0'

Step-III: Add meta data in between application tag and required permission in Manifest file.

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

<uses-permission android:name="android.permission.
                              ACCESS_FINE_LOCATION"/>
Step-IV: Your output will be like. 





See the code of MainActivity
package com.example.locationbasedservices2021;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
final int REQUEST_CODE_LOCATION=123;
int locationRequestCode;
TextView lat_text,long_text,add_text;
FusedLocationProviderClient fusedLocationClient;
double lat, longi;
String addres;
Button button;
Boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat_text = findViewById(R.id.textLat);
long_text = findViewById(R.id.textLong);
add_text = findViewById(R.id.textCity);
button = findViewById(R.id.btn_location);
fusedLocationClient = LocationServices.
getFusedLocationProviderClient(this);

locationRequestCode =
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
 button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag)
{
finLoc();

}
}
});
}

@Override
protected void onStart() {
super.onStart();

if(locationRequestCode == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Already Given ",
                        Toast.LENGTH_LONG).show();
flag = true;
}
else
{
askforPermission();
}
}
private void askforPermission() {

if(locationRequestCode != PackageManager.PERMISSION_GRANTED)
{
if(!ActivityCompat.shouldShowRequestPermissionRationale
      (MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
return;
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
        String[] permissions,int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
            grantResults);
if(requestCode == REQUEST_CODE_LOCATION)
{
if(grantResults.length>0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Granted",
                                Toast.LENGTH_LONG).show();
flag = true;
finLoc();
}
}
}
private void finLoc() {

fusedLocationClient.getLastLocation().addOnCompleteListener
                (new OnCompleteListener<Location>() {
        @Override
public void onComplete(Task<Location> task) {

Location location = task.getResult();
if(location!=null)
{
Geocoder geocoder = new Geocoder(MainActivity.this,
                                 Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation
                                        (location.getLatitude(),
             location.getLongitude(),1);
lat = location.getLatitude();
longi = location.getLongitude();
lat_text.setText("Latitide: " + lat);
long_text.setText("Longitude: " + longi);

StringBuilder sb = new StringBuilder();
if (address.size() > 0) {
Address addr = address.get(0);
for (int i = 0; i < addr.getMaxAddressLineIndex(); i++)
sb.append(addr.getAddressLine(i)).append("\n");
sb.append(addr.getLocality()).append("\n");
sb.append(addr.getPostalCode()).append("\n");
sb.append(addr.getCountryName());
}
addres = sb.toString();

} catch (IOException e) {
e.printStackTrace();
}
}
add_text.setText("Address:"+addres);
}
});
}
}

// Layout 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"
tools:context=".MainActivity"
android:orientation="vertical">

<Button
android:id="@+id/btn_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_marginTop="100dp"
android:text="Find Location" />

<TextView
android:id="@+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lattitude"
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude "
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>

<TextView
android:id="@+id/textCity"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:text="City"
android:textSize="30dp" />

</LinearLayout>


Friday, April 2, 2021

Broadcast Receiver in Android

Broadcast Receiver 

Android apps can send or receive broadcast messages from the Android system and other Android apps. These broadcasts are sent when an event of interest occurs. 

For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging. Apps can also send custom broadcasts, for example, to notify other apps of something that they might be interested in (for example, some new data has been downloaded).

Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast.

System Broadcast : The system automatically sends broadcasts when various system events occur, such as when the system switches in and out of airplane mode. System broadcasts are sent to all apps that are subscribed to receive the event.

Referenceshttps://developer.android.com/guide/components/broadcasts

Demo App which implement System Broadcast

Step-1: Create a Main Activity (No need to add any widget in Layout File)

Like: 

import androidx.appcompat.app.AppCompatActivity; // package name

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

IntentFilter intentfilterAirplaneMode;

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

intentfilterAirplaneMode = new IntentFilter
                                    (Intent.ACTION_AIRPLANE_MODE_CHANGED);
}

}
Step-2: Create a java class (Define Broadcast Receiver) by                             
                Extending BroadcastReceiver  

 Like: 

package com.example.broadcastex1y2021;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AirModeChanged extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, " Airplane Mode Changed",
                                      Toast.LENGTH_LONG).show();
}
}
Step-3: Add the action in manifest file with the receiver (inside application tag)
 Like: 
<receiver android:name=".AirModeChanged">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>

Run your app and see the effect by changing Airplane Mode 

Demo App which implement User Defined Broadcast

Step-1: Create a Main Activity with Layout as


Add onClick on Button - I have added 
SendBroadCast

Now see the Main Activity Code 

import androidx.appcompat.app.AppCompatActivity; // package name

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

 intentFilter = new IntentFilter("MAIS");
    }
    public void SendBroadCast(View view) {
    intent = new Intent("MAIS");
intent.putExtra("BCA", "Hi How are you");
sendBroadcast(intent);
    }
}
Step-2: Create two or more  java classes which you want to respond after   
             Broadcasting (Define Broadcast Receiver) by                       
            Extending BroadcastReceiver  

 Like: 

   FirstReceiver
    package com.example.broadcastex1y2021;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;

    public class FirstReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, " Received Message in 1 " +
intent.getStringExtra("BCA"), Toast.LENGTH_LONG).show();
     }
    }

SecondReceiver
package com.example.broadcastex1y2021;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SecondReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received message in 2 " +
intent.getStringExtra("BCA"), Toast.LENGTH_LONG).show();
}
}

Step-3: Add the action in manifest file with the receiver (inside application tag) for                 both receiver 
 Like: 
<receiver android:name=".FirstReceiver">
<intent-filter>
<action android:name="MAIS"/>
</intent-filter>
</receiver>
<receiver android:name=".SecondReceiver">
<intent-filter>
<action android:name="MAIS"/>
</intent-filter>
</receiver>

Run your app and see the effect by clicking on Button 

Friday, April 21, 2017

Customized List View in Android with Optimization

Dear All

Please see the customized List View example in Android with Optimization.
I am using latest Android Studio 2.3.1
Please put 10 images in drawable folder

A. The output will be as


B.  XML files are
a. activity_main.xml is as
<?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.exam.ravi.listviewex1.MainActivity">


    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

b. single_row.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img4"
        android:layout_margin="10dp"
        android:id="@+id/imageView2"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/imageView2" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView2"
        android:layout_toEndOf="@+id/imageView2" />
</RelativeLayout>

C.  Java Code is as
a. ListFinal.java

package com.exam.ravi.listviewex1;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class ListFinal extends Activity {
    ListView list;
    String membTitles[]={"AUSTRALIA","CANADA","Contry-3","INDIA","NEW ZEALAND",
                    "PAKISTAN","NETHERLAND","Country-8","Country-9","Country-10"};
    String membDesc[]={"Description","Description","Description","Desc","Desc",
                        "Desc","Desc","Desc","Desc","Desc"};
    int images[] = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4,
                    R.drawable.img5, R.drawable.img6,R.drawable.img7, R.drawable.img8,
                    R.drawable.img9, R.drawable.img10};

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

        list = (ListView) findViewById(R.id.listView);
        MyAdapter adapter = new MyAdapter(this, membTitles, images, membDesc);
        list.setAdapter(adapter);
   }
}

b. MyAdapter.java is 

package com.exam.ravi.listviewex1;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/** * Created by Ravi on 2/12/2016. */class MyAdapter extends ArrayAdapter<String> {
    Context context;
    String titleArray[];
    int imgs[];
    String descArray[];

    MyAdapter(Context cob, String titles[], int img[], String desc[]) 
    {
        super(cob, R.layout.single_row, R.id.textView2, titles);
        context = cob;
        imgs = img;
        titleArray = titles;
        descArray = desc;
    }

    class MyViewHolder
    {
        ImageView myImage;
        TextView myTitle;
        TextView myDescription;
        MyViewHolder(View view)
        {

            myImage = (ImageView) view.findViewById(R.id.imageView2);
            myTitle = (TextView) view.findViewById(R.id.textView2);
            myDescription = (TextView) view.findViewById(R.id.textView3);
        }


    }
    @Override    public View getView(int position, View convertView, ViewGroup parent) 
    {
        View row=convertView;
        MyViewHolder myViewHolder=null;
      if(row==null) {
            LayoutInflater inflator = (LayoutInflater) context.getSystemService
                                      (Context.LAYOUT_INFLATER_SERVICE);
            row = inflator.inflate(R.layout.single_row, parent, false);
            myViewHolder  = new MyViewHolder(row);
            row.setTag(myViewHolder);
      }
      else      {
          myViewHolder = (MyViewHolder) row.getTag();
      }
        myViewHolder.myImage.setImageResource(imgs[position]);
        myViewHolder.myTitle.setText(titleArray[position]);
        myViewHolder.myDescription.setText(descArray[position]);
        return row;
    }
}

Friday, March 31, 2017

CRUD Operations using SQLite - Mini App

Dear All

I am uploading a Mini App by which we can Register New user , View All registered user , Login , Update and Delete.
Database is done by using SQLite.
See  the app behavior through images
A.
a. Main Screen


b.  Registration Screen


c. Login Screen
 

d. View All

e. Update
     It will search first on the base of User Name

   
    If Search Successful it will show Username and Password for update
     

 


f. Delete
     For delete it will again search  - Delete Button disabled


     After User found Delete Button Enabled


 Hope you will manage xml files for Layout
B. Java Code is as
1. MainActivity.java
package com.example.bca_mobile_iv_18.sqlex1;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    Context con=MainActivity.this;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void register(View v)
    {
        Intent registr=new Intent(con,RegistrationActivity.class);
        startActivity(registr);
    }
    public void viewuser(View v)
    {
        Intent usr=new Intent(con,Viewuser_activity.class);
        startActivity(usr);
    }
    public void login(View v)
    {
        startActivity(new Intent(con,Loginactivity.class));
    }
    public void delete(View v)
    {
        startActivity(new Intent(con,Deleteuseractivity.class));
    }
    public void update(View v)
    {
        startActivity(new Intent(con,Updateuseractivity.class));
    }
}

2. Helper class for Handling SQLite 

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** * Created by BCA-MOBILE-IV-18 on 3/28/2017. */
public class DbHelper extends SQLiteOpenHelper {
   public static final String key_id="_id";
   public static final String user_name="user_name";
   public static final String user_pass="user_pass";
   public static final String tab_name="myinfo";
   public static final String db_name="mynew.db";
    private static final int db_version=1;
    private static final String sql_query="create table "+ tab_name +" ( " + key_id +
                          " integer primary key autoincrement, " + user_name +
                          " text not null , " + user_pass + " text not null );";
        public DbHelper(Context con)
    {
        super(con,db_name,null,db_version);
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql_query);
        Log.d("rrrr","oncreate");

    }

    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, 
                                        int newVersion) {
        db.execSQL("DROP TABLE IF EXIST " +tab_name);
        Log.d("hello","onupgrade");
        onCreate(db);
    }
    public void putinfo(DbHelper mob,String name,String pass)
    {
        SQLiteDatabase sq=mob.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(user_name,name);
        cv.put(user_pass,pass);
        sq.insert(tab_name,null,cv);
    }
    public Cursor getALlRows(DbHelper mob)
    {
        SQLiteDatabase sq=mob.getReadableDatabase();
        Cursor cob=sq.query(tab_name,null,null,null,null,null,null);
        if(cob!=null)
        {
            cob.moveToFirst();
        }
        return cob;
    }
    public Cursor getuserinfo(DbHelper mob)
    {
        SQLiteDatabase sq=mob.getReadableDatabase();
        String columns[]={user_name,user_pass};
        Cursor cur=sq.query(tab_name,columns,null,null,null,null,null);
        return cur;
    }
    public Cursor getuserpass(DbHelper mob,String uname)
    {
        SQLiteDatabase sq=mob.getReadableDatabase();
        String columns[]={user_pass};
        String selection=user_name + " LIKE ? ";
        String args[]={uname};
        Cursor cur=sq.query(tab_name,columns,selection,args,null,null,null);
        return cur;
    }
    public void deleteuser(DbHelper mob,String uname,String upwd)
    {
        String selection=user_name + " LIKE ? AND " + user_pass + " LIKE ? ";
        String args[]={uname,upwd};
        SQLiteDatabase sq=mob.getWritableDatabase();
        sq.delete(tab_name,selection,args);
    }
    public void update(DbHelper mob,String uname,String upwd,
                                         String newuname,String newupwd)
    {
        String selection=user_name + " LIKE ? AND " + user_pass + " LIKE ? ";
        String args[]={uname,upwd};
        SQLiteDatabase sq=mob.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(user_name,newuname);
        cv.put(user_pass,newupwd);
        sq.update(tab_name,cv,selection,args);
    }
}

3. DeleteUserActivity

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Deleteuseractivity extends AppCompatActivity {
    EditText etuser,etpass;
    Button clear,validate,delete;
    String username,password;
    DbHelper myhelper;
    Context con=Deleteuseractivity.this;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deleteuseractivity);
        myhelper=new DbHelper(con);
        etuser=(EditText)findViewById(R.id.editText1);
        etpass=(EditText)findViewById(R.id.editText2);
        clear=(Button)findViewById(R.id.buttonclear);
        validate=(Button)findViewById(R.id.buttonvalidate);
        delete=(Button)findViewById(R.id.buttonupdate);
        delete.setEnabled(false);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                etuser.setText("");
                etpass.setText("");
            }
        });
        validate.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                username=etuser.getText().toString();
                password=etpass.getText().toString();
                boolean checkflag=false;
                Cursor cur=myhelper.getuserinfo(myhelper);
                if(cur!=null) {
                    cur.moveToFirst();
                    do {
                        if (cur.getString(0).equalsIgnoreCase(username) &&
                                 cur.getString(1).equals(password)) {
                            checkflag = true;
                            username = cur.getString(0);
                            break;
                        }
                    } while (cur.moveToNext());
                    if (checkflag == true) {
                        Toast.makeText(con, "Validation success..!! \n Now press delete
                          user button to delete your account", Toast.LENGTH_SHORT).show();
                        delete.setEnabled(true);
                        checkflag = false;
                    } else {
                        Toast.makeText(con, "Validation failed.!! \n Invalid \
                             username/password", Toast.LENGTH_SHORT).show();
                        delete.setEnabled(false);
                    }
                }
                else                {
                    Toast.makeText(con, "Validation failed.!! \n Invalid username/
                     password \nNOTE: Database iS empty", Toast.LENGTH_SHORT).show();
                    delete.setEnabled(false);
                }
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                myhelper.deleteuser(myhelper,username,password);
                Toast.makeText(con,username+" account successfully Deleted...!!",
                               Toast.LENGTH_SHORT).show();
                delete.setEnabled(false);
                startActivity(new Intent(con,MainActivity.class));
            }
        });
    }
}

4. Login Activity 

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Loginactivity extends AppCompatActivity {
    EditText etuser,etpass;
    Button clear,login;
    String username,password;
    Context con=Loginactivity.this;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginactivity);
        etuser=(EditText)findViewById(R.id.editText1);
        etpass=(EditText)findViewById(R.id.editText2);
        clear=(Button)findViewById(R.id.buttonclear);
        login=(Button)findViewById(R.id.buttonupdate);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                etuser.setText("");
                etpass.setText("");
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                username=etuser.getText().toString();
                password=etpass.getText().toString();
                boolean checkflag=false;
                DbHelper myhelper=new DbHelper(con);
                Cursor cur=myhelper.getuserinfo(myhelper);
                if(cur!=null) {
                    cur.moveToFirst();
                    do {
                        if (cur.getString(0).equalsIgnoreCase(username) &&
                               cur.getString(1).equals(password)) {
                            checkflag = true;
                            username = cur.getString(0);
                            break;
                        }
                    } while (cur.moveToNext());
                    if (checkflag == true) {
                        Toast.makeText(con, "Login success..!! \n Welcome: " + 
                              username, Toast.LENGTH_SHORT).show();
                        checkflag = false;
                    } else {
                        Toast.makeText(con, "Login failed.!! \n Invalid username/password",
                                   Toast.LENGTH_SHORT).show();
                    }
                }
                else                {
                    Toast.makeText(con, "Login failed.!! \n Invalid username/password
                            \nNOTE: Database iS empty", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

5. Registration Activity 

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegistrationActivity extends AppCompatActivity {
        EditText etname,etpass,etconformpass;
        String uname,upass,uconfirmpass;
        Context con=RegistrationActivity.this;
        Button buttonrgstr;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        buttonrgstr=(Button)findViewById(R.id.buttonregister);
        etname=(EditText)findViewById(R.id.editText);
        etconformpass=(EditText)findViewById(R.id.editText3);
        etpass=(EditText)findViewById(R.id.editText2);
      buttonrgstr.setOnClickListener(new View.OnClickListener() {
          @Override          public void onClick(View v) {
              uname=etname.getText().toString();
              upass=etpass.getText().toString();
              uconfirmpass=etconformpass.getText().toString();
              if(upass.equals(uconfirmpass)) {
                  DbHelper myob = new DbHelper(con);
                  myob.putinfo(myob, uname, upass);
                  Toast.makeText(getBaseContext(), "Registered Successfully...!!", 
                           Toast.LENGTH_LONG).show();
                  finish();
                  startActivity(new Intent(con, MainActivity.class));
              }
              else              {  Toast.makeText(getBaseContext(), "Password does not match...!!", 
                  Toast.LENGTH_LONG).show();  }
          }
      });
    }
} 

6. Update Activity 

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Updateuseractivity extends AppCompatActivity {
    EditText etuser,etpass;
    Button clear,search,update;
    String username,password,newusername,newpassword;
    DbHelper myhelper;
    Context con=Updateuseractivity.this;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_updateuseractivity);
        myhelper=new DbHelper(con);
        etuser=(EditText)findViewById(R.id.editText1);
        etpass=(EditText)findViewById(R.id.editText2);
        clear=(Button)findViewById(R.id.buttonclear);
        search=(Button)findViewById(R.id.buttonsearch);
        update=(Button)findViewById(R.id.buttonupdate);
        update.setEnabled(false);
        etpass.setEnabled(false);

        clear.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                etuser.setText("");
                etpass.setText("");
            }
        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                username=etuser.getText().toString();
                boolean checkflag=false;
                Cursor cur=myhelper.getuserpass(myhelper,username);
                if(cur!=null) {
                    cur.moveToFirst();
                    password = cur.getString(0);
                    etpass.setEnabled(true);
                    etpass.setText(password);
                    update.setEnabled(true);
                }
                else                {
                    Toast.makeText(con,"User: "+username+" Not Found...!!",
                      Toast.LENGTH_SHORT).show();
                    update.setEnabled(true);
                }
            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                newusername=etuser.getText().toString();
                newpassword=etpass.getText().toString();
               myhelper.update(myhelper, username, password, newusername, newpassword);
              Toast.makeText(con, "Updation successful...!!\n updated details:-
                       \n username: " + newusername + "\n password: " + newpassword,
                       Toast.LENGTH_LONG).show();
                    update.setEnabled(false);
                    startActivity(new Intent(con, MainActivity.class));
            }
        });
    }
}

7. View All User 

package com.example.bca_mobile_iv_18.sqlex1;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class Viewuser_activity extends AppCompatActivity {
        Context con=Viewuser_activity.this;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewuser_activity);
        showListView();
    }
    public void showListView()
    {
    DbHelper myhelper =new DbHelper(con);
        Cursor cursorOB=myhelper.getALlRows(myhelper);
        String[] fromDB=new String[]{DbHelper.key_id,DbHelper.user_name,
                      DbHelper.user_pass};
        int toShow[]=new int[]{R.id.textView1,R.id.textView2,R.id.textView3};
        SimpleCursorAdapter simpleCursorAdapter=new SimpleCursorAdapter
                  (getBaseContext(),R.layout.onerow,cursorOB,fromDB,toShow,0);
        ListView listView=(ListView)findViewById(R.id.listview);
        listView.setAdapter(simpleCursorAdapter);
    }
}


Layout for single row onerow.xml

<?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"    android:weightSum="3">

    <LinearLayout        android:orientation="horizontal"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:layout_weight="1"

        android:weightSum="3">

    <TextView        android:text="TextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAlignment="center"

        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"

        android:id="@+id/textView1"

        android:layout_weight="0.70" />

    <TextView        android:text="TextView"

        android:layout_width="98dp"        android:layout_height="wrap_content"
\        android:textAlignment="center"

        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"

        android:id="@+id/textView2"

        android:layout_weight="1"/>
    <TextView        android:text="TextView"

        android:layout_width="98dp"

        android:layout_height="wrap_content"

        android:textAlignment="center"

        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"

        android:id="@+id/textView3"

        android:layout_weight="1"        />
    </LinearLayout>
</LinearLayout>