Monday, 27 August 2018

How to Create Map and Show Current Location And Custom Location

Step 1:

AndroidStudio/New/MapActivity


activty_map.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorLiteGreen">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="center|left"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/im_arrow"
                android:layout_width="25dp"
                android:layout_height="20dp"
                android:background="@drawable/arrow_left"/>
            <ImageView
                android:layout_width="150dp"
                android:layout_height="30dp"
                android:layout_marginLeft="30dp"
                android:background="@drawable/logo_white"/>
        </LinearLayout>

    </android.support.v7.widget.Toolbar>
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    tools:context="com.a2aonlinemart.MapsActivity" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:background="@color/colorLiteGreen">
        <Button
            android:id="@+id/but_loc"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:text="Location"
            android:background="@color/colorAccent"/>
    </LinearLayout>
</LinearLayout>


Step 2:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    ImageView im_arrow;

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

        im_arrow = (ImageView) findViewById(R.id.im_arrow);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if(locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitute=location.getLatitude();
                    double longitude=location.getLongitude();
                    LatLng latLng=new LatLng(latitute,longitude);
                    Geocoder geocoder=new Geocoder(getApplicationContext());
                    try {
                        List<Address> arList=geocoder.getFromLocation(latitute,longitude, 1);
                        String str=arList.get(0).getLocality()+" , ";
                        str+=arList.get(0).getCountryName();


                        mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.
                                defaultMarker(BitmapDescriptorFactory.HUE_AZURE)).title(str));

                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));


                        //another mark
                        LatLng la1 = new LatLng(9.9252,78.1198);
                        LatLng la2 = new LatLng(13.0827,80.2707);
                        LatLng la3 = new LatLng(11.0168,76.9558);

                        List<Address> arList2=geocoder.getFromLocation(9.9252,78.1198, 1);
                        String str2=arList2.get(0).getLocality()+" , ";
                        str2+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la1).title(str2));

                        List<Address> arList3=geocoder.getFromLocation(13.0827,80.2707, 1);
                        String str3=arList3.get(0).getLocality()+" , ";
                        str3+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la2).title(str3));

                        List<Address> arList4=geocoder.getFromLocation(11.0168,76.9558, 1);
                        String str4=arList4.get(0).getLocality()+" , ";
                        str4+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la3).title(str4));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
        }
        else if (locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitute=location.getLatitude();
                    double longitude=location.getLongitude();
                    LatLng latLng=new LatLng(latitute,longitude);
                    Geocoder geocoder=new Geocoder(getApplicationContext());
                    try {
                        List<Address> arList=geocoder.getFromLocation(latitute,longitude, 1);
                        String str=arList.get(0).getLocality()+", ";
                        str+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));

                        //another mark
                        LatLng la1 = new LatLng(15.664861, 77.134940);
                        LatLng la2 = new LatLng(9.816625, 77.811000);
                        LatLng la3 = new LatLng(8.454931, 77.708947);
                        mMap.addMarker(new MarkerOptions().position(la1).title("Hello World"));
                        mMap.addMarker(new MarkerOptions().position(la2).title("Hello World"));
                        mMap.addMarker(new MarkerOptions().position(la3).title("Hello World"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });

        }


        im_arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

       /* LatLng la1 = new LatLng(15.664861, 77.134940);
        LatLng la2 = new LatLng(9.816625, 77.811000);
        LatLng la3 = new LatLng(8.454931, 77.708947);
        mMap.addMarker(new MarkerOptions().position(la1).title("Hello World"));
        mMap.addMarker(new MarkerOptions().position(la2).title("Hello World"));
        mMap.addMarker(new MarkerOptions().position(la3).title("Hello World"));*/
       /* mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney2));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney3));*/

    }}


Step :3

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

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

    <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.NoActionBar">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Step 4:

Insert your Map Access Key

res/values/google_map_api.xml

<resources>
    <!--    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:
    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6%3Bcom.a2aonlinemart
    You can also add your credentials to an existing key, using these values:
    Package name:    A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6
    SHA-1 certificate fingerprint:    A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6
    Alternatively, follow the directions here:    https://developers.google.com/maps/documentation/android/start#get-key
    Once you have your key (it starts with "AIza"), replace the "google_maps_key" 
   string in this file.    -->   
 <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
       xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   <<<google map access key>>>
    </string>
</resources>





Blue Mark My Current Location
Red Mark Custom Location

Android How to Create Local DataBase in SQL

Step 1:

<?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.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorOrange">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="40dp"
                android:layout_gravity="center"
                android:layout_height="40dp"
                android:background="@drawable/logo"/>
            <TextView
                android:id="@+id/toolbar_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Biling and Storing"
                android:textSize="16dp"
                android:layout_marginLeft="10dp"
                android:fontFamily="serif"
                android:textColor="@android:color/white"/>
        </LinearLayout>
    </android.support.v7.widget.Toolbar>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="8"
        android:background="@color/colorOrange"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/text_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center"
            android:text="Today Date"
            android:textColor="@android:color/white"
            android:textSize="18dp"
            android:textStyle="bold" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorOrange"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2.2"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tvNoRecordsFound"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="15dp"
                android:gravity="center"
                android:textColor="@android:color/black"
                android:text="No Records Found"
                android:textSize="15dp" />

            <ListView
                android:id="@+id/list_product"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="8dp"
                android:background="@android:color/white"
                android:divider="@android:color/white"
                android:dividerHeight="10dp"
                android:scrollbars="none"></ListView>

            <ImageView
                android:id="@+id/add_item"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_gravity="bottom|right"
                android:layout_marginBottom="70dp"
                android:layout_marginRight="30dp"
                android:background="@drawable/add" />
        </FrameLayout>
    </LinearLayout>
</LinearLayout>

Step 2:

public class MainActivity extends AppCompatActivity {
    TextView text_date;
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog.Builder alertDialogBuilder2;
    ImageView im_add;
    String sdfString,sdfString2;
    Date mDate,mDate2;
    EditText input_name;
    EditText input_price;
    private String name;
    private String price;
    ListView listView;

    private CustomAdapter customAdapter;
    Cursor cursor;
    StudentRepo studentRepo ;
    private final static String TAG= MainActivity.class.getName().toString();

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

        valid();

        im_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                click_add();
            }
        });

 
    }

    public void valid(){
        alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
        alertDialogBuilder2 = new AlertDialog.Builder(MainActivity.this);
        im_add=(ImageView)findViewById(R.id.add_item);
        listView=(ListView)findViewById(R.id.list_product);
        text_date = (TextView) findViewById(R.id.text_date);

        studentRepo = new StudentRepo(this);
        cursor=studentRepo.getStudentList();
        customAdapter = new CustomAdapter(MainActivity.this,  cursor, 0);
        listView.setAdapter(customAdapter);

        bill=(LinearLayout)findViewById(R.id.layout_bill);
        sale=(LinearLayout)findViewById(R.id.layout_sale);
        detail=(LinearLayout)findViewById(R.id.layout_detail);
        hellp=(LinearLayout)findViewById(R.id.layout_help);
        setting=(LinearLayout)findViewById(R.id.layout_setting);

        mDate=new Date();
        mDate2=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
        SimpleDateFormat sdf2 = new SimpleDateFormat("ddMMyyyy", Locale.US);
        sdfString = sdf.format(mDate);
        sdfString2 = sdf2.format(mDate2);
        text_date.setText(sdfString);
    }
    public  void click_add(){
        alertDialogBuilder.setTitle("Meteirial Name");
        alertDialogBuilder2.setTitle("Meteirial Price");

        alertDialogBuilder.setMessage("Enter Meteirial Name");
        alertDialogBuilder2.setMessage("Enter Meteirial Price");

        input_name = new EditText(MainActivity.this);
        input_price = new EditText(MainActivity.this);

        int maxLength = 10;
        int maxLength2 = 4;

        input_name.setInputType(InputType.TYPE_CLASS_TEXT);
        input_price.setInputType(InputType.TYPE_CLASS_NUMBER);

        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(maxLength);

        InputFilter[] FilterArray2 = new InputFilter[1];
        FilterArray2[0] = new InputFilter.LengthFilter(maxLength2);

        input_name.setFilters(FilterArray);
        input_price.setFilters(FilterArray2);

        alertDialogBuilder.setView(input_name);
        alertDialogBuilder2.setView(input_price);

        alertDialogBuilder.setIcon(R.drawable.logo);
        alertDialogBuilder2.setIcon(R.drawable.logo);

        alertDialogBuilder.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {

                        name=input_name.getText().toString();
                        if(name.length()>=2){
                            dialog.cancel();
                            AlertDialog dialog_price = alertDialogBuilder2.create();
                            dialog_price.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                            dialog_price.show();
                        }
                        else {
                            Toast.makeText(getApplicationContext(),"Enter Correct Value",Toast.LENGTH_SHORT).show();                        }
                    }
                });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {

                        dialog.cancel();

                    }
                });

        alertDialogBuilder2.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog2,int which) {

                        price=input_price.getText().toString();

                        if(price.length()>=2){

                            insertDummy();
                        }
                        else {
                            Toast.makeText(getApplicationContext(),"Enter Correct Value",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        alertDialogBuilder2.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog2,int which) {

                        dialog2.cancel();

                    }
                });
        alertDialogBuilder.setCancelable(true);
        alertDialogBuilder2.setCancelable(true);

        AlertDialog dialog_name = alertDialogBuilder.create();
        dialog_name.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        dialog_name.show();

    }
    private void insertDummy(){

        Student student=new Student();
        student.age= Integer.parseInt(sdfString2);
        student.email=""+price;
        student.name=""+name;
        studentRepo.insert(student);
        cursor=studentRepo.getStudentListByKeyword("");
        if (cursor==null){
            Toast.makeText(MainActivity.this,"No records found!",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(MainActivity.this, cursor.getCount() + " records found!",Toast.LENGTH_LONG).show();
        }
        customAdapter.swapCursor(cursor);

    }
}

Step 3:

CustomAdapter .java

public class CustomAdapter extends CursorAdapter {
    TextView txtId,txtName,txtEmail;
    private LayoutInflater mInflater;

    public CustomAdapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View   view    =    mInflater.inflate(R.layout.list_item, parent, false);
        ViewHolder holder  =   new ViewHolder();
        holder.txtId    =   (TextView)  view.findViewById(R.id.txtId);
        holder.txtName    =   (TextView)  view.findViewById(R.id.txtName);
        holder.txtEmail   =   (TextView)  view.findViewById(R.id.txtEmail);
        view.setTag(holder);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //If you want to have zebra lines color effect uncomment below code
        /*if(cursor.getPosition()%2==1) {
             view.setBackgroundResource(R.drawable.item_list_backgroundcolor);
        } else {
            view.setBackgroundResource(R.drawable.item_list_backgroundcolor2);
        }*/

        ViewHolder holder  =   (ViewHolder)    view.getTag();
        holder.txtId.setText(cursor.getString(cursor.getColumnIndex(Student.KEY_ID)));
        holder.txtName.setText(cursor.getString(cursor.getColumnIndex(Student.KEY_name)));
        holder.txtEmail.setText(cursor.getString(cursor.getColumnIndex(Student.KEY_email)));

    }

    static class ViewHolder {
        TextView txtId;
        TextView txtName;
        TextView txtEmail;
    }
}

Step 4:

list_item.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="com.instinctcoder.zipunzip.MainActivity">

    <LinearLayout android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"
        android:layout_marginRight="5dip"
        android:layout_alignParentRight="true">

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="25dip"
            android:layout_height="25dip"
            android:src="@drawable/logo" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="email@instinctcoder.com"
        android:id="@+id/txtEmail"
        android:layout_weight="90"
        android:layout_alignBottom="@+id/txtName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/txtId"
        android:visibility="gone"
        android:text="1"
        android:layout_weight="50" />

    <TextView
        android:layout_width="318dp"
        android:layout_height="40dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/txtName"
        android:text="ten"
        android:textStyle="bold"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>


Step 5:

DBHelper .java

public class DBHelper extends SQLiteOpenHelper {
    //version number to upgrade database version
    //each time if you Add, Edit table, you need to change the
    //version number.
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "searchwidget.db";

    public DBHelper(Context context ) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //All necessary tables you like to create will create here

        String CREATE_TABLE_STUDENT = "CREATE TABLE " + Student.TABLE  + "("
                + Student.KEY_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + Student.KEY_name + " TEXT, "
                + Student.KEY_age + " INTEGER, "
                + Student.KEY_email + " TEXT )";

        db.execSQL(CREATE_TABLE_STUDENT);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed, all data will be gone!!!
        db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE);

        // Create tables again
        onCreate(db);

    }


}

Step 6:

Student .java

public class Student {
    // Labels table name
    public static final String TABLE = "Student";

    // Labels Table Columns names
    public static final String KEY_ROWID = "_id";
    public static final String KEY_ID = "id";
    public static final String KEY_name = "name";
    public static final String KEY_email = "email";
    public static final String KEY_age = "age";

    // property help us to keep data
    public int student_ID;
    public String name;
    public String email;
    public int age;
}

Step 7:

StudentRepo .java

public class StudentRepo {
    private DBHelper dbHelper;

    public StudentRepo(Context context) {
        dbHelper = new DBHelper(context);
    }

    public int insert(Student student) {

        //Open connection to write data
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Student.KEY_age, student.age);
        values.put(Student.KEY_email,student.email);
        values.put(Student.KEY_name, student.name);

        // Inserting Row
        long student_Id = db.insert(Student.TABLE, null, values);
        db.close(); // Closing database connection
        return (int) student_Id;
    }
    public Cursor  getStudentList() {
        //Open connection to read only
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  rowid as " +
                Student.KEY_ROWID + "," +
                Student.KEY_ID + "," +
                Student.KEY_name + "," +
                Student.KEY_email + "," +
                Student.KEY_age +
                " FROM " + Student.TABLE;


        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list

        if (cursor == null) {
            return null;
        } else if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }
        return cursor;


    }


    public Cursor  getStudentListByKeyword(String search) {
        //Open connection to read only
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT  rowid as " +
                Student.KEY_ROWID + "," +
                Student.KEY_ID + "," +
                Student.KEY_name + "," +
                Student.KEY_email + "," +
                Student.KEY_age +
                " FROM " + Student.TABLE +
                " WHERE " +  Student.KEY_name + "  LIKE  '%" +search + "%' "
                ;


        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list

        if (cursor == null) {
            return null;
        } else if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }
        return cursor;


    }

    public Student getStudentById(int Id){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery =  "SELECT " +
                Student.KEY_ID + "," +
                Student.KEY_name + "," +
                Student.KEY_email + "," +
                Student.KEY_age +
                " FROM " + Student.TABLE
                + " WHERE " +
                Student.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string

        int iCount =0;
        Student student = new Student();

        Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );

        if (cursor.moveToFirst()) {
            do {
                student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID));
                student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name));
                student.email  =cursor.getString(cursor.getColumnIndex(Student.KEY_email));
                student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age));

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return student;
    }

}











How to Create BarCode and QRCode Scanner inside Fragment

Need file :

1.BarcodeActivity.java
2.compile 'me.dm7.barcodescanner:zxing:1.9'
3.BarcodeFragment.java
4.res/layout/fragment_barcode.xml

Step 1:

compile 'me.dm7.barcodescanner:zxing:1.9'


Step 2:

res/layoput/fragment_barcode.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:app="http://schemas.android.com/apk/res-auto"    
android:id="@+id/activity_main"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:orientation="vertical">
    <LinearLayout   
     android:layout_width="match_parent"    
      android:layout_height="match_parent"  
      android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:src="@drawable/logo" />

        <View
            android:layout_width="match_parent"
            android:layout_height="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="BarCode and QRCode Scaner"
            android:textColor="@color/colorDarkGreen"
            android:textSize="20dp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/text_scan" 
           android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="50dp"
            android:textSize="15dp"
            android:textColor="@android:color/black" 
           android:text="Scan" />


        <Button    
        android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"  
          android:ems="15"       
     android:layout_gravity="center|bottom"  
          android:background="@drawable/button_selector"
            android:text="Scan QR Code"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"
            android:textColor="@android:color/white"
            android:textSize="13dp" />

    </LinearLayout>


</LinearLayout>



Step 3:

BarcodeActivity.java

public class BarcodeActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{

    private ZXingScannerView mScannerView;

    @Override    public void onCreate(Bundle state) {
        super.onCreate(state);
        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view       
        setContentView(mScannerView);                // Set the scanner view as the content view    }

    @Override    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.  
        mScannerView.startCamera();          // Start camera on resume    }

    @Override    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause    }

    @Override    public void handleResult(Result rawResult) {

        BarcodeQrcodeFragment.tx_scan.setText("Scan Result : "+rawResult.getText());
        onBackPressed();

    }
}


Step 4:

BarcodeQrcodeFragment .java

public class BarcodeQrcodeFragment extends Fragment{
    public static TextView tx_scan;
    Button bt_scan;
    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_bar_qr_code, container, false);

        bt_scan=(Button)view.findViewById(R.id.buttonScan);
        tx_scan=(TextView)view.findViewById(R.id.text_scan);

        bt_scan.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),BarcodeActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }
    }

Step 5 :

Manifests

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




How To Create Animation Splash Activity


Need File:

1.SplashActivity.java
2.activity_splash.xml
3.res/anim/translate.xml
4.res/anim/alpha.xml

Step 1:

res/anim/alpha.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="8000" />


Step 2:

res/anim/translate.xml


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

    <translate        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXDelta="0%" 
       android:toXDelta="0%"    
    android:fromYDelta="200%"    
    android:toYDelta="0%"    
    android:duration="3000"   
     android:zAdjustment="bottom" />
</set>

Step 3:

res/layout/activity_splash.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:id="@+id/layout_anim"
    android:background="@android:color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
        <ImageView
            android:id="@+id/image_logo"
            android:layout_width="150dp"
            android:layout_height="100dp"
            android:background="@drawable/logo"/>
    </LinearLayout>
</LinearLayout>

Step 4:

public class SplashActivity extends Activity {

    Animation anim;
    private static int SPLASH_TIME_OUT = 5000;
    ImageView im_logo;
    LinearLayout lay_anim;
public void onAttachedToWindow() { super.onAttachedToWindow(); Window window = getWindow(); window.setFormat(PixelFormat.RGBA_8888); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); im_logo=(ImageView)findViewById(R.id.image_logo);
        lay_anim=(LinearLayout)findViewById(R.id.layout_anim);
StartAnimations(); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i=new Intent(SplashActivity.this,LoginActivity.class); startActivity(i); finish(); } }, SPLASH_TIME_OUT); } private void StartAnimations() {
        
        anim = AnimationUtils.loadAnimation(this, R.anim.translate);
        anim.reset();
        lay_anim.clearAnimation();
        lay_anim.startAnimation(anim );

        anim = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
        anim.reset();
        im_logo.clearAnimation();
        im_logo.startAnimation(anim);


    }
}


HOW TO CREATE CIRCLE IMAGE VIEW

Step 1: implementation 'de.hdodenhof:circleimageview:3.0.0' Step 2: <de.hdodenhof.circleimageview.CircleImageView xmlns:ap...