Friday, 26 July 2024

Basic Example of data binding with MVVM design pattern.

 1. Please make yout .gradle setting like below.

inside android in build.gradle.kts

android{

dataBinding {
enable = true
}

}

2. Put below line inside gradle.properties

android.databinding.enableV2=true

3. add below dependencies  build.gradle.kts(Module:app)

//coroutines
implementation(libs.androidx.coroutines.core.ktx)
implementation(libs.androidx.coroutines.ktx)

// Retrofit
implementation(libs.androidx.retrofit2.converter.gson)
implementation(libs.androidx.retrofit2)
implementation(libs.androidx.okhttp3.logging.interceptor)

//view model
implementation(libs.androidx.lifecycle.livedata.ktx)
implementation(libs.androidx.lifecycle.viewmodel.ktx)
//New Material Design
implementation(libs.androidx.android.material.ktx)
implementation(libs.androidx.arch.lifecycle.viewmodel)
4. Add below inside libs.versions.toml
[versions]
coroutinesVersion = "1.7.1"
retrofit = "2.9.0"
gson = "2.6.2"
okhttp3 = "4.5.0"
lifecycle_version = "2.8.4"
material_version = "1.12.0"

androidx-coroutines-core-ktx = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "coroutinesVersion" }
androidx-coroutines-ktx = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutinesVersion" }

androidx-retrofit2 = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
androidx-retrofit2-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "gson" }
androidx-okhttp3-logging-interceptor = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp3" }

androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle_version" }
androidx-lifecycle-livedata-ktx = { group = "androidx.lifecycle", name = "lifecycle-livedata-ktx", version.ref = "lifecycle_version" }
androidx-android-material-ktx={group="com.google.android.material",name="material",version.ref="material_version"}
androidx-arch-lifecycle-viewmodel={group="android.arch.lifecycle",name="viewmodel",version="1.1.1"}
5. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.example.basicmvvmdatabinding.viewModel.MainActivityViewModel" />
</data>

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinatorLay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".view.MainActivity">

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

<EditText
android:id="@+id/editTextTextEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:ems="10"
android:text="@={viewModel.email}"
android:hint="Enter Email"
android:inputType="textEmailAddress"
android:padding="20dp"
android:singleLine="true" />

<EditText
android:id="@+id/editTextNumberPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editTextTextEmailAddress"
android:layout_centerInParent="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:ems="10"
android:text="@={viewModel.password}"
android:hint="Enter Name"
android:inputType="numberPassword"
android:padding="20dp" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumberPassword"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:onClick="@{()->viewModel.onLoginBtnClick()}"
android:text="Login" />
</RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
6.MainActivity.kt
package com.example.basicmvvmdatabinding.view

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.example.basicmvvmdatabinding.R
import com.example.basicmvvmdatabinding.databinding.ActivityMainBinding
import com.example.basicmvvmdatabinding.viewModel.LoginListener
import com.example.basicmvvmdatabinding.viewModel.MainActivityViewModel

class MainActivity : AppCompatActivity(), LoginListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val dataBinding: ActivityMainBinding =
DataBindingUtil.setContentView(this, R.layout.activity_main)
val viewModel1 = ViewModelProvider(this)[(MainActivityViewModel::class.java)]
dataBinding.viewModel = viewModel1
viewModel1.listener = this
}

override fun started() {
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show()
}

override fun success() {
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()

}

override fun failed(message: String?) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()

}

}
7.MainActivityViewModel.kt
package com.example.basicmvvmdatabinding.viewModel

import androidx.lifecycle.ViewModel

class MainActivityViewModel : ViewModel() {
var email: String? = null
var password: String? = null
var listener: LoginListener? = null
fun onLoginBtnClick() {
listener?.started()
if (email.isNullOrEmpty() || password.isNullOrEmpty()) {
//show error message
listener?.failed("Invalid Email or Password")
return
}
//success message
listener?.success()
}
}
8.LoginListener.kt
package com.example.basicmvvmdatabinding.viewModel

interface LoginListener {
fun started()
fun success()
fun failed(message: String?)
}

Tuesday, 2 July 2024

Most Asking Java Question.

 1. Palindrome in JAVA in given integer.

public void palindrome(int input) {
int data = input;
int temp = 0;
int rem;
while (input > 0) {
rem = input % 10;
temp = temp * 10 + rem;
input = input / 10;
}
if (temp == data) {
System.out.println("No is Palindrome");
} else {
System.out.println("No. is not Palindrome");
}
}
2.Palindrome in JAVA in given String.
public void palindromeString(String str) {
String s=str;
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
temp = temp + str.charAt(i);
}
if (s.equalsIgnoreCase(temp)) {
System.out.println("String is Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
3.Count character repetition in a given string using HashMap.
public void countCharRep(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
} else {
map.put(str.charAt(i), 1);
}
}
for (Map.Entry<Character, Integer> e : map.entrySet()) {
System.out.print(" " + e.getKey() + "-" + e.getValue());
}
}

4.Reverse a String using inbuilt function.//ex:raja=ajar

public void revStr(String str){
StringBuilder stringBuilder= new StringBuilder(str);
str=stringBuilder.reverse().toString();
System.out.println(str);
}
5. Reverse a String without using inbuilt function.//ex:Supriya =ayirpus
public void revString(String str) {
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
temp = temp + str.charAt(i);
}
System.out.println("revString==" + temp);
}
6.Count number of word in given string.// //ex:world is world i am world i =world3 is1 i2 am1
public void countWord(String str) {
String[] arr = str.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i])) {
map.put(arr[i], map.get(arr[i]) + 1);
} else {
map.put(arr[i], 1);
}
}
for (Map.Entry<String, Integer> e : map.entrySet()) {
System.out.println(e.getKey() +" "+ e.getValue());
}
}
7.Iterate HashMap using while loop.
public void itrMap() {
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 12);
map.put(2, 98);
map.put(3, 21);
map.put(4, 54);
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> entry = (Map.Entry) iterator.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
8. Check Prime. //2, 3, 5, 7, 11
 public boolean checkPrime(int num){
  for (int i=2;i<num/2;i++){
if(num%i==0) {
return false;
}
}
return true;
}
9. Fibonacci series.//0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
public void fibonacci(int range) {
int a = 0;
int b = 1;
int sum = 0;
for (int i = 0; i <= range; i++) {
System.out.println(a);
sum = a + b;
a = b;
b = sum;
}
}

10.Iterate ArrayList using while loop and for-each loop.

public void itrList(){
List<Integer> list=new ArrayList<>();
list.add(12);
list.add(43);
list.add(78);
list.add(98);
list.add(123);
//using while loop
System.out.println("Using While Loop");
Iterator<Integer> iterator=list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}

System.out.println("using For each loop");
for (int i:list){
System.out.println(i);
}
}
11.Find Dublicate Character in a given String.
public void findDublicate(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), map.get(str.charAt(i))+1);
} else {
map.put(str.charAt(i), 1);
}
}
for (Map.Entry<Character, Integer> e : map.entrySet()) {
if (e.getValue() > 1) {
System.out.println(e.getKey());
}
}
}
12. Check Armstrong Number in java.//Armstrong Number :-153 = 1*1*1 + 5*5*5 + 3*3*3 = 153
public void armstrongNum(int num) {
int rem = 0;
int temp = num, result=0;
while (num > 0) {
rem = num % 10;
result = result+(rem * rem * rem);
num = num / 10;
}
if (temp == result) {
System.out.println("Armstrong");
} else {
System.out.println("not Armstrong");
}
}
13.Replace all white space in a given string.ex: "sd cf ww e" output= "sdcfwwe"
public void replaceSpace(String str){
str=str.replace(" ","");
System.out.println(str);

}

14. Factorial in JAVA Factorial using Recursion :- //ex: 5!=120.6!=720

public int fact(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * fact(num - 1);
}
}

15. WAP in JAVA to find run length encoding if the input is"wwwaadxxxw"

then output should be :- w3a2d1x3w1.

public void lengthEncoding(String str) {
int count = 1;
String result="";
for (int i = 0; i < str.length(); i++) {
while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
result=result+str.charAt(i)+count;
count=1;
}
System.out.println(result);
}
16. In  a given alphanumeric string return sum of the digit 0-9 
that appears in the string ignoring all other character. 
public void sumOfDigit(String str) {
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
sum = sum + Character.getNumericValue(str.charAt(i));
}
}
System.out.println("Sum::=="+sum);
}

17. Find peak element in an array. A peak element is an element if it is not smaller

than its neighbours./Ex:{10,80,15,2,23,90,67,120,3,134,7} output :- 80,90.120,134.

public void findPeakNumber(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 2 && arr[i] < arr[i + 1] && arr[i + 1] > arr[i + 2]){
System.out.println(arr[i+1]);
}
}
}
18. WAP leader in an array. An element is leader  if it is greater than its its 
right side of all element.Ex:{16,17,4,3,5,2} output:- 2,5,17.
public void leaderInArray(int[] arr) {
int leader = arr[arr.length - 1];
System.out.println(arr[arr.length - 1]);
for (int i = arr.length - 2; i >= 0; i--) {
if (leader < arr[i]) {
System.out.println(arr[i]);
leader = arr[i];
}
}
}
19. Array of 0's and 1sin random order.Segregate 0s

on left side and 1s on right side of the array.Traverse array only once.
input {0,1,1,0,0,1,0,1,0,1,1}
output{0,0,0,0,0,1,1,1,1,1,1}

public void separateZeroOne(int[] arr) {
int l = 0, r = arr.length - 1;
int temp;
while (l < r) {
while (arr[l] == 0 && l < r) {
l++;
}
while (arr[r] == 1 && l < r) {
r--;
}
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
for (int i : arr) {
System.out.print(i);
}
}
20. Given array {5,2,1,7,3,4,6} and another Y=7. Find
all the pairs whose sum is Y.
public void findPairs(int[] arr,int sum){
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]+arr[j]==sum){
System.out.println(arr[i] +","+arr[j]);
}
}
}
}

21. Binary Search .

public int binarySearch(int[] arr, int item) {
int l = 0;
int r = arr.length - 1;
int mid ;
while (l <= r) {
mid = l + (r - l) / 2;
if (arr[mid] == item) {
return mid;
} else if (item < arr[mid]) {
r = mid - 1;
} else if (item > arr[mid]) {
l = mid + 1;
}
}
return -1;

}
22. In Binary search if duplicate item is available than

search the item at very first position.Ex:- {21,100, 100, 100, 100, 100, 401, 453, 588, 789, 890};

than print the position of 100 at very first position.

public int findItem(int[] arr, int item) {
int l = 0, r = arr.length - 1;
int mid;
while (l <= r) {
mid = l + (r - l) / 2;
if (item == arr[mid]) {
if (item == arr[mid - 1]) {
l = l - 1;
}else {
return mid;
}
} else if (item < arr[mid]) {
r = mid - 1;
} else if (item > arr[mid]) {
l = mid + 1;
}
}
return -1;
}
23. WAP Write a Java
program to check if a vowel is present in a string.
public void checkVowel(String str){
boolean b=str.matches(".*[aeiou].*");
if (b) {
System.out.println("vowel present");
} else {
System.out.println("Vowel not present");
}
}

24. WAP to Roated the string at there place ex :- {"my","name","is","supriya"}o/p:-{"ym","eman","si","ayirpus"}

public void rotateString(String[] str) {
String s = "";
for (int i = 0; i < str.length; i++) {
for (int j = str[i].length() - 1; j >= 0; j--) {
s = s + str[i].charAt(j);
}

str[i]=s;
s="";
}
for (String item:str){
System.out.println(item);
}

}

25. WAP to find second Largest from an array.

public void secondLargest(int[] arr) {
  int largest = arr[0];
int largest2 = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest2 = largest;
largest = arr[i];
}
}
System.out.println(largest2);
}

26. WAP to remove all space from a string.

public void removeSpace(String str){

  str=str.replace(" ","");
System.out.println(str);
}
27.Check if array has duplicate elements or not?
public boolean  findDuplicate(int[] arr){
Map<Integer,Integer> map=new HashMap<>();
for (int i=0;i<arr.length;i++){
if(map.containsKey(arr[i])){
return true;
}else {
map.put(arr[i],1);
}
}
return false;
}// TC: O(n) and SC: o(n)

28. Give an algorithm for finding the element which appears maximum number of times in array.

public void findMaxRepNum(int[] arr){
Map<Integer,Integer> map=new HashMap<>();
for (int i=0;i< arr.length;i++){
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i])+1);
}else {
map.put(arr[i],1);
}
}
for (Map.Entry<Integer,Integer> entry:map.entrySet()){
System.out.println(entry.getKey()+"-"+entry.getValue());
}
}
29. In array find the first element in the array which is repeated.
public int firstRep(int[] arr){
Map<Integer,Integer> map=new HashMap<>();
for (int i=0;i<arr.length;i++){
if (map.containsKey(arr[i])){
return arr[i];
}else {
map.put(arr[i],1);
}
}
return -1;
}
30. Given an array of n element, find two elements
in the array such that their sum is equal to given element K
public void fun(int[] arr,int k){
for (int i=0;i<arr.length;i++){
for (int j=1;j<arr.length;j++){
if(arr[i]+arr[j]==k){
System.out.println(arr[i]+","+arr[j]);
}
}
}
}
31. Find three element in the array such that their sum is equal to given element K.
public void fun(int[] arr,int sum){
for (int i=0;i<arr.length;i++){
for (int j=i+1;j<arr.length;j++){
for (int k=j+1;k<arr.length-1;k++){
if(arr[i]+arr[j]+arr[k]==sum){
System.out.println(arr[i]+","+arr[j]+","+arr[k]);
}
}
}
}
}
input: int[] a={8,5,14,10,2,7,1,5}; output:- 8,7,1 and 5,10,1 where sum=16 32. Given a sorted array of n integer that has been rotated an unknown

number of times, find how many time array has been rotated.

public void findNoOfRotation(int[] arr) {
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min > arr[i]) {
System.out.println("Array is rotated by " + i);
return;
}
}
}

33.Given a sorted array A of n element, possibly with duplicates. Find the index of the first occurrence of a number in O(logn) time.

public int fun(int[] arr, int num) {
  int l = 0;
int r = arr.length - 1;
int mid;
while (l <= r) {
mid = l + (r - l) / 2;
if (num == arr[mid]) {
while (num == arr[mid - 1]) {
mid = mid - 1;
}
return mid;
} else if (num > arr[mid]) {
l = mid + 1;
} else if (num < arr[mid]) {
r = mid - 1;
}
}
return -1;
}

34. Separate even and odd number in array. Put all even number first and then odd number.

public void seperateEvenOdd(int[] arr) {
int l = 0;
int temp;
int r = arr.length - 1;
while (l < r) {
while (l < r && arr[l] % 2 == 0) {
l++;
}
while (l < r && arr[r] % 2 != 0) {
r--;
}
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
}
input:-{15, 18,18, 21, 33, 33,64, 121}; output:-64 18 18 21 33 33 15 121

35. WAP to illustrate merge sort.

public void fun(int[] nums) {

  int[] aux = nums.clone();
mergeSort(nums, aux, 0, nums.length - 1);
for (int r : nums) {
System.out.println(r);
}
}

private void mergeSort(int[] nums, int[] aux, int start, int end) {
if (start == end) {
return;
}
int mid = start + (end - start) / 2;
mergeSort(aux, nums, start, mid);
mergeSort(aux, nums, mid + 1, end);
doMerge(aux, nums, start, mid, end);
}

private void doMerge(int[] aux, int[] nums, int start, int mid, int end) {
int mainIndex = start;
int left = start;
int right = mid + 1;

while (left <= mid && right <= end) {
if (aux[left] <= aux[right]) {
nums[mainIndex++] = aux[left++];
} else {
nums[mainIndex++] = aux[right++];
}
}
while (left <= mid) {
nums[mainIndex++] = aux[left++];
}
while (right <= end) {
nums[mainIndex++] = aux[right++];
}
}

36. An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero
public static void findClosest(int[] arr) {
int lowestSum = arr[0] + arr[1];
int sum = 0;
int k = 0, l = 0;
for (int i = 1; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
sum = arr[i] + arr[j];
if (Math.abs(lowestSum) > Math.abs(sum)) {
lowestSum = sum;
k = i;
l = j;
}
}

}
System.out.println("Result==" + arr[k] + " , " + arr[l]);

}
Output:-
int[] arr = {1, -3, 2, -8, -12}; // Result==-3 , 2
int[] arr1 = {-8, 5, 2, -6}; // Result==5 , -6
int[] arr2 = {0, -8, -6, 3}; // Result==-6 , 3
findClosest(arr);
findClosest(arr1);
findClosest(arr2)

36. Rotated the array list by given position Input: nums = [1,2,3,4,5,6,7,8], k = 3
Output: [5,6,7,1,2,3,4]
*/

private static void rotateArray(int[] arr, int k) {
int[] result = reverseUtility(arr, 0, arr.length-k-1);
int[] result1 = reverseUtility(result, arr.length-k, arr.length - 1);
rev(result1);
}

static void rev(int[] arr) {
int[] temp = new int[arr.length];
int j = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
temp[j] = arr[i];
j--;
}
System.out.println("arr = " + Arrays.toString(temp));
}

private static int[] reverseUtility(int[] arr, int l, int h) {
int temp;
for (int i = l; i < h; i++) {
while (l < h) {
temp = arr[l];
arr[l] = arr[h];
arr[h] = temp;
l++;
h--;
}
}
return arr;
}