Monday, 18 October 2021

Interface java Example Interview

 //interface Only public, static and final are allowed.

//No. Interfaces can’t have constructors.
interface Test{

static int s=2;
final int d=4;
void get();
int getmultiple();

}


// initializers not allowed in interfaces
/*interface demoStatic(){
{ System.out.println("empty implemented");}

static{
System.out.println("static implemented");
}
}*/


interface B{
int getdivide(int i);
// int getadd();//implementation is required in Class A
}

class A implements B{

public int getdivide(int i ){
return i*i;
}
}


class p{

interface Q{
int i=111;
}
}

interface NextTest extends Test{
int t=5;
void get();

int getadd();

// int getValue();//Demo is not abstract and does not override abstract method getValue() in NextTest
}

class Demo implements Test, NextTest {

public int getadd(){
return d+t;
}

public int getmultiple(){
return d*t;
}
public void get(){
System.out.println("demo get method implemented");
}


}
class XDemo extends Demo{

}

/*class XXDemo implements NextTest{
void methodD(){
i=4;
//No, because interface fields are static and
//final by default and you can’t change
//their value once they are initialized. In the above code, methodB()
//is changing value of interface field A.i. It shows compile time error.
}
}*/


public class MyClass {
public static void main(String args[]) {

System.out.println("Interface");

Test s=new XDemo();
s.get();
// System.out.println("sum : "+ s.getadd());//it will check in Test interface error not found

System.out.println("multiple : "+ s.getmultiple());
NextTest st=new XDemo();
System.out.println("add : "+ st.getadd());

// XDemo s=new NextTest();//NextTest is abstract; cannot be instantiated
XDemo sp=new XDemo();
System.out.println("addd : "+ sp.getadd());
System.out.println("multiple : "+ sp.getmultiple());



B newS=new A();

System.out.println("divide : "+ newS.getdivide(12));
// p ps=new Q();
B bs=new B(){
public int getdivide(int i){
return i*i; }

};

System.out.println("divide : "+ bs.getdivide(12));
}
}

Find the character element which appears maximum number of times in an String

 //Find the element which appears maximum number of times in an array


import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {

String name="amitrawat";

char[] word=name.toCharArray();

for(int i=0;i<word.length;i++){

for(int j=i+1;j<word.length;j++){
char first=word[i];
char second=word[j];
char temp;

if(first>second){
temp=first;
word[i]=second;
word[j]=temp;
}
}

}

System.out.println("max number : " + String.valueOf(word));


//getting max character and times
char maxchar=word[0];
int times=0;
for(int i=0;i<word.length;i++){

char w=word[i];

if(maxchar==w){
times++;

}else if(maxchar<w){
times=1;
maxchar=w;

}
}

System.out.println("char max : " + maxchar);
System.out.println("char times: " + times);
}
}
OUTPUT
max number : aaaimrttw
char max  : w
char times: 1

Find the element which appears maximum number of times in an array

import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int max = 0, count = 0;
int[] a={1,2,3,4,8,8,9,8,3,3,5,3,4,5,6,8};

//sorting array
for(int i=0;i<a.length;i++){

for(int j=i+1;j<a.length;j++){
int first=a[i];
int second=a[j];
int temp=0;

if(first>second){

temp=first;
a[i]=second;
a[j]=temp;

}
}
}
// Arrays.sort(a);
//finding highest number with times
for(int i=0;i<a.length;i++){
int num=a[i];

if(max==num){
count++;
}else if(max<num){
max=num;
count=1;

}
}

System.out.println("max number : " + max);
System.out.println("times: " + count);

}
}

OUTPUT
max number : 9
times: 1

Monday, 11 October 2021

Overloading and overriding Interview Example Code

 class Test {


static int s = 4;
final int d = 5;

static void sit() {
System.out.println(" sit method of test class ");
}

void get() {
System.out.println(" get method test class");

}
}

class Test1 extends Test {
static int s = 6;
static int a = 2;
final int d = 3;

static void sit() {
System.out.println("sit method test1 class");
}

void get() {

System.out.println("get method get test1 class");
}
}

class Test2 extends Test1 {
static int s = 7;

static void sit() {
System.out.println("sit method test2 class");
}

void get() {
System.out.println("get method get test2 class");
}

}

class Demo {
}

public class HelloWorld {
public static void main(String[] args) {
System.out.println("1 : test2 class instance of test2 class.......... ");
System.out.println();
Test2 obj2 = new Test2();
//class c inherit static
System.out.println("static varialble : " + obj2.a); // 2
System.out.println();

System.out.println("final varibale : " + obj2.d); //3
System.out.println();

obj2.sit();//print method of test2 class

System.out.println();
System.out.println();

System.out.println("2 : test1 class instance of test2 class.......... ");
System.out.println();
Test1 obj1 = new Test2();

obj1.sit();// print method of class test1 : static method
System.out.println();


obj1.get();//print method of class test2 :non static method
System.out.println();


//testing the type cast
Test objtrail1 = new Test1();//correct
Test objtrail2 = new Test2();//correct

// Test1 cannot be converted to Test2
// Test2 objtrail3=new Test1();//incorrect type cast error

// incompatible types: Test cannot be converted to Test2
// Test2 objtrail3=new Test();//incorrect type cast error


// Test1 obje=new Test();//error: incompatible types: Test cannot be converted to Test1

System.out.println();
System.out.println();
System.out.println("3 : test class instance of test1 class.......... ");

Test obje = new Test1();//the instance of test1 but print the static and final variable and static method of test
System.out.println();

System.out.println("print the static variable of test class " + obje.s);//4
System.out.println();

System.out.println("print the final variable of test class " + obje.d);//5
System.out.println();

obje.sit();//print the method of static test class
System.out.println();

obje.get();//print method of non static test1 class

System.out.println();


// System.out.println("3 : test2 class instance of test class.......... ");


// Test2 objet=new Test();

// objet.sit();//error: incompatible types: Test cannot be converted to Test2
// Test2 objet=new Test1();//error: incompatible types: Test1 cannot be converted to Test2


// Test s=new Demo();//error: incompatible types: Demo cannot be converted to Test
}
}



output :  

1 : test2 class instance of test2 class.......... 

static varialble : 2

final varibale : 3

sit method test2 class


2 : test1 class instance of test2 class.......... 

sit  method test1 class

get  method get test2 class



3 : test class instance of test1 class.......... 

print the static  variable of test class  4

print the final  variable of test  class 5

 sit method of  test class 

get  method get test1 class

Monday, 20 September 2021

LocaleHelper for language change

 import android.content.Context;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.preference.PreferenceManager;

import java.util.Locale;

public class LocaleHelper {

private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}

public static Context setNewLocale(Context mContext, String language) {
persist(mContext, language);
return updateLocale(mContext, getLanguage(mContext));
}

public static Context setLocale(Context context) {
persist(context, getLanguage(context));

return updateLocale(context, getLanguage(context));
}

private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();

editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}


private static Context updateLocale(Context context, String lang) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();

Locale localeToSwitchTo = new Locale(lang);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

configuration.setLocale(localeToSwitchTo);

LocaleList localeList = new LocaleList(localeToSwitchTo);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);

} else {

Locale.setDefault(localeToSwitchTo);
configuration.locale = localeToSwitchTo;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}

return context;
}
}

//Activity class 
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.setLocale(base));
}
private void setNewLocale(Context mContext, String language) {
try {
LocaleHelper.setNewLocale(this, language);
         recreate();
//recreate activity
} catch (Exception e) {
e.printStackTrace();
FirebaseCrashlytics.getInstance().recordException(e);
}

}

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);
});
}


Popular Posts