Friday, 23 April 2021

In Android EditText, how to force writing uppercase?

In Android EditText, how to force writing uppercase? 

@Override

public void setFilters(InputFilter[] filters) {
try {
InputFilter[] oldFilter = filters;
InputFilter[] newFilters = new InputFilter[oldFilter.length + 1];
System.arraycopy(oldFilter, 0, newFilters, 0, oldFilter.length);
newFilters[newFilters.length - 1] = new InputFilter.AllCaps();
super.setFilters(newFilters);
} catch (Exception e) {
e.printStackTrace();
FirebaseCrashlytics.getInstance().recordException(e);
}

}

Disabling Android O auto-fill service for an application

So I have my own class which is extends the android.support.v7.widget.AppCompatEditText
 and all I did is overwrote the following method with the following value:


@Override
public int getAutofillType() {
return AUTOFILL_TYPE_NONE;
}

no other solutions worked, not even android:importantForAutofill="no".

getAutofillType() comes from the View class, so it should work for every other
class such as TextInputEditText too!

Monday, 12 April 2021

Firebase : -Firestore Live Location

FIRESTORE Live Location 

AUTHENTICATION:-






EDIT RULES :-

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /dev/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
match /LiveData/{userId} {
allow read, update, delete,create: if request.auth.uid != null;

}
}
}

}

ANDROID CODE:

String token;
FirebaseAuth authref;
private FirebaseFirestore db;
<string name="FIREBASE_DATABASE_NAME">dev</string>
<string name="FIREBASE_DATABASE_NODE_NAME">LiveData</string>
<string name="FIREBASE_EMAIL_DB">amitrawat@gmail.com</string>
<string name="FIREBASE_PASS_DB">123456789</string>
@Override
public void onCreate() {
super.onCreate();

try {
        setup();
notificationToken();
loginFirebase();
} catch (Exception e) {
e.printStackTrace();

}


}
public void setup() {

db = FirebaseFirestore.getInstance();

}
private void notificationToken() throws Exception {
try {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
return;
}
token = task.getResult().getToken();

Log.e("token", token);
}
});
} catch (Exception e) {
throw new Exception(e);
}
}


  private void loginToFirebase() {
//Authenticate with Firebase, using the email and password we created earlier//
String email = getString(R.string.FIREBASE_EMAIL_DB);
String password = getString(R.string.FIREBASE_PASS_DB);
//Call OnCompleteListener if the user is signed in successfully//
authref = FirebaseAuth.getInstance();
authref.signInWithEmailAndPassword(
email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
try {
requestLocationUpdates();
} catch (Exception e) {

}

} else {
Log.d(TAG, "Firebase authentication failed");
}
}
});
}


 private void requestLocationUpdates() {

LocationRequest request = new LocationRequest();
request.setInterval(60000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
//If the app currently has access to the location permission...//
if (permission == PackageManager.PERMISSION_GRANTED) {
//...then request location updates//
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
//Get a reference to the database, so your app can perform read and write operations//
if (isNullOrEmpty(token)) {
try {
notificationToken();
} catch (Exception e) {
e.printStackTrace();
Util.Crash(e);
}
} else {
try {

Location location = locationResult.getLastLocation();
if (location != null) {
FirebaseDTO locdto = new FirebaseDTO ();
locdto.setLatitude(location.getLatitude());
locdto.setLongitude(location.getLongitude());

locdto.setLastUpdatedOn(String.valueOf(new Timestamp(System.currentTimeMillis())));
Log.e("loc1", String.valueOf(location.getLatitude()));
Log.e("loc2", String.valueOf(location.getLongitude()));


// Add a new document with a generated ID\

db.collection(getResources().getString(R.string.FIREBASE_DATABASE_NAME)).
document(authref.getUid()).
collection(getResources().getString(R.string.FIREBASE_DATABASE_NODE_NAME)).
document(token).
set(locdto)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});

}


} catch (Exception e) {
Util.Crash(e);
}

}

}
}, null);
}
}
public class FirebaseDTO {
private double latitude;
private double longitude
private String lastUpdatedOn;

}

 

Monday, 5 April 2021

Alert Dialog in flutter

 Alert Dialog in flutter

 new IconButton(
icon: new Icon(Icons.cloud_download_rounded),
highlightColor: Colors.orange,
iconSize: 30,
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return getDialogBox();
});
},
),

method of AlertDialog 
AlertDialog getDialogBox() {
return AlertDialog(
title: Row(children: [
new IconButton(
icon: new Icon(Icons.warning_amber_outlined),
color: Colors.black45,
highlightColor: Colors.orange,
iconSize: 30,
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return getDialogBox();
});
},
),
/* Image.network(
'https://flutter-examples.com/wp-content/uploads/2019/12/android_icon.png',
width: 50,
height: 50,
fit: BoxFit.contain,
),*/
Text(' Download ')
]),
content: Text("Are You Sure Want To Proceed?"),
actions: <Widget>[
TextButton(
child: Text("YES"),
onPressed: () {
//Put your code here which you want to execute on Yes button click.
Navigator.of(context).pop();
},
),
TextButton(
child:
Text("CANCEL"),
onPressed: () {
//Put your code here which you want to execute on Cancel button click.
Navigator.of(context).pop();
},
),
],
);
}

Monday, 29 June 2020

A non-null String must be provided to a Text widget in Flutter

A non-null String must be provided to a Text widget in Flutter

you can check null safe .
new Text(cart_prod_qty!=null?cart_prod_qty:'Default Value'),

Sunday, 28 June 2020

How to change Package name in Flutter?

FOR ANDROID APP NAME

change the label name in your AndroidManifes.xml

 <application

    android:name="io.flutter.app.FlutterApplication"
android:label="TheNameOfYourApp"

FOR PACKAGE NAME

Change the package name in your AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="your.package.name">

Also in your build.gradle file inside app folder

 defaultConfig {

    applicationId "your.package.name"
minSdkVersion 16
targetSdkVersion 28
resConfigs "en"
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

finally change the package in your MainActivity.java 
class(if the MainActivity.java is not 
avaiable ,check the MainActivity.kt

 package your.package.name;


import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
public class MainActivity extends FlutterActivity {}

Change the directory name:

From

 android\app\src\main\java\com\example\name


To.

 android\app\src\main\java\your\package\name


IOS

in ios the package name is the bundle identifier in Info.plist

 <key>CFBundleIdentifier</key>

<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

which is found in Runner.xcodeproj/project.pbxproj

 PRODUCT_BUNDLE_IDENTIFIER = com.example.appname;



Monday, 15 June 2020

Flutter custom listview with cardview and icon android studio

                      

                  Flutter custom listview with cardview and icon android studio


programmingcodetech

1.Add dependencies fluttertoast: ^4.0.1 in pubspec.yaml

 dependencies:

  flutter:
sdk: flutter



cupertino_icons: ^0.1.3
fluttertoast: ^4.0.1

 

2.Create lib/main.dart 

 import 'package:flutter/material.dart';

import 'package:listviewdemo/listview_activity.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.purple,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ListViewActivity(title: 'EmailPageList'),
);
}
}

 

3.Create lib/email_data.dart model 

class EmailData {
EmailData({this.name, this.email, this.phonenumber});

final String name;
final String email;
final String phonenumber;
}

List<EmailData> allEmail = [
EmailData(
name: 'Amit Rawat',
email: 'amit.rawat@me.com',
phonenumber: '+109938388380'),
EmailData(
name: 'John Ricciardi',
email: 'John.ricciardi@me.com',
phonenumber: '+109938388380'),
EmailData(
name: 'David Smith ',
email: 'David.Smith@me.com',
phonenumber: '+109938388380'),
EmailData(
name: 'Michael Hassinger',
email: 'Michael.hassinger@me.com',
phonenumber: '+109938388380'),
EmailData(
name: 'Chris Cupps',
email: 'Chris.cupps@me.com',
phonenumber: '+1099383-08380'),
EmailData(
name: 'Mike Nantz',
email: 'Mike.nantz@me.com',
phonenumber: '+10993838-8380'),
EmailData(
name: 'Mark Primus',
email: 'Mark.primus@me.com',
phonenumber: '+1099383-88380'),
EmailData(
name: 'Muriel Lewellyn',
email: 'muriel.lewellyn@me.com',
phonenumber: '+1099-38388380'),
EmailData(
name: 'Hunter Giraud',
email: 'Hunter.giraud@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Corina Whiddon',
email: 'corina.whiddon@me.com',
phonenumber: '+10993838-8380'),
EmailData(
name: 'Meaghan Covarrubias',
email: 'meaghan.covarrubias@me.com',
phonenumber: '+10993838-8380'),
EmailData(
name: 'Daniel Severson',
email: 'Daniel .severson@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Maria Baxter',
email: 'Maria .baxter@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Alessandra Kahn',
email: 'alessandra.kahn@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'James Saari',
email: 'James .saari@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Valeria Salvador',
email: 'valeria.salvador@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Fredrick Folkerts',
email: 'fredrick.folkerts@me.com',
phonenumber: '+109938388-380'),
EmailData(
name: 'Delmy Izzi',
email: 'delmy.izzi@me.com',
phonenumber: '+09938388-380'),
EmailData(
name: 'Leann Klock',
email: 'leann.klock@me.com',
phonenumber: '+09938388-380'),
EmailData(
name: 'Rhiannon Macfarlane',
email: 'rhiannon.macfarlane@me.com',
phonenumber: '+09938388-380'),
];

4.Create lib/listview_activity.dart

 import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';
import 'package:listviewdemo/email_data.dart';

import 'listview_title.dart';

class ListViewActivity extends StatelessWidget {
ListViewActivity({Key key, this.title}) : super(key: key);

final String title;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Container(
child: _buildList(),
),
);
}

Widget _buildList() {
return ListView.builder(
itemCount: allEmail.length,
itemBuilder: (BuildContext context, int index) {
EmailData data = allEmail[index];
return Card(
elevation: 8.0,
child: Container(
child: EmailListTile(data),
),
);
});
}
}

5.Create lib/listview_title.dart

 import 'package:flutter/material.dart';

import 'package:fluttertoast/fluttertoast.dart';
import 'package:listviewdemo/email_data.dart';

class EmailListTile extends ListTile {
EmailListTile(EmailData data)
: super(
title: Text(data.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(data.email),
new Text(data.phonenumber)
],
),
leading: CircleAvatar(child: Text(data.name[0])),
dense: false,
trailing: Icon(
Icons.arrow_forward,
size: 24.0,
color: Colors.deepPurple,
),
onTap: () {
Fluttertoast.showToast(
msg: data.email,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.grey,
textColor: Colors.white,
fontSize: 14.0);
});
}


Create First Flutter Application: Flutter Dart Tutorial

                                    Create First Flutter Application: Flutter Dart Tutorial


ProgrammingCodeTech

1.Add dependencies google_fonts: ^1.1.0 in pubspec.yaml

 dependencies:

  flutter:
sdk: flutter


cupertino_icons: ^0.1.3
google_fonts: ^1.1.0

 

2.Create main.dart

 import 'package:flutter/material.dart';

import 'my_home_page.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Home Page'),
);
}
}

 

3.Create my_home_page.dart

 import 'package:flutter/material.dart';

import 'package:flutter/widgets.dart';
import 'package:google_fonts/google_fonts.dart';

class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: Text(
'ProgrammingCodeTech',
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.red[800],
fontWeight: FontWeight.bold,
fontSize: 30,
fontStyle: FontStyle.italic)),
),
),
);
}
}

Tuesday, 28 April 2020

Monitor the Battery Level and Charging State


Get Battery Percentage
 
private float getBattery_percentage() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    float batteryPct = level / (float) scale;
    float p = batteryPct * 100;
    Log.d("Battery percentage", String.valueOf(Math.round(p)));
    return p;
}

Get Phone is charging /charged

private boolean getIsCharging() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = this.registerReceiver(null, ifilter);
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
            status == BatteryManager.BATTERY_STATUS_FULL;
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    // How are we charging?    boolean  usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean   acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    return isCharging;
}


Tuesday, 30 July 2019

How to Debug android App over WIFI(without Root) in android studio Adb

1.you need to connect your device to your computer via USB cable .Make sure Debugging is working .you can check if it shows up when running    adb devices.

C:\Users\Developer\AppData\Local\Android\Sdk\platform-tools>adb devices
        List of devices attached
        S980601711B01366        device


2.Run adb tcpip 5555

C:\Users\Developer\AppData\Local\Android\Sdk\platform-tools>adb tcpip 5555  
      restarting in TCP mode port: 5555

2.Disconnect your device(remove the usb )

4.Go to the settings ->About phone ->status view the IP address of your phone .

5.Run adb connect <IP address of uour device here>:5555

C:\Users\Developer\AppData\Local\Android\Sdk\platform-tools>adb connect 192.168.1.100:5555   
     connected to 192.168.1.100:5555

6.If you run adb devices again ,you should see your device.
C:\Users\Developer\AppData\Local\Android\Sdk\platform-tools>adb devices
        List of devices attached
        192.168.1.100:5555       device

Now you can execute adb command or use IDE for android .

Friday, 10 May 2019

Fix MTP driver Installation on Windows 10

Fix MTP driver Installation on Windows 10

C:\Windows\INF\wpmdmtp.inf

wpmdmtp.inf is a file related to MTP and installing it manually can possibly 
resolve your issues is a file related to MTP and installing it manually can 
possibly resolve your issues

Right-click on the wpmdmtp.inf file and select Install
now the problem solved.

Thursday, 9 May 2019

How to get string if length is more than 50 after 50 it split into another string ?

String st = "A string is a data type used in programming,
 such as an integer and floating point unit,
but is used to represent text rather than numbers";
if (st.length() > 50) {
    int comma = st.indexOf(',', 50);
    if (comma >= 0) {

        //Bit before comma        String partOne = st.substring(0, comma);

        //Bit after comma        String partTwo = st.substring(comma);
        Log.e("string partOne", partOne);
        Log.e("string partTwo", partTwo);
    }
}

Parses a specific value from string against a specific key for xml format data l̥

 Parses a specific value from string against a specific key for xml format data l̥

private String getValueFromString(String key, String input) {
    if (!AppUtility.isNullOrEmpty(input)) {
        try {
            String match = key.toLowerCase() + "=\"";
            String[] dataArray1 = input.split(match);
            String[] dataArray2;
            if (dataArray1 != null && (dataArray1.length > 0)) {
                int size = dataArray1.length;
                if (size > 1) {
                    dataArray2 = dataArray1[1].split("\"");
                    return dataArray2[0].trim();
                } else {
                    match = key.toUpperCase() + "=\"";
                    dataArray1 = input.split(match);
                    if (dataArray1 != null && (dataArray1.length > 0)) {
                        size = dataArray1.length;
                        if (size > 1) {
                            dataArray2 = dataArray1[1].split("\"");
                            return dataArray2[0].trim();
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return " ";/*empty string*/
}