Friday, October 18, 2024

hiti android

 implementation 'com.squareup.retrofit2:retrofit:2.9.0'

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'


public class AndroidApp {
    private String name;
    private String app_url;
    private String logo;
    private String banner;
    private String pkg;
    private String scheme;
    private String publisher;
    private String subtitle;

    // Getters and Setters
}



import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> {

    private List<AndroidApp> appList;

    public AppAdapter(List<AndroidApp> appList) {
        this.appList = appList;
    }

    @Override
    public AppViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_app, parent, false);
        return new AppViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AppViewHolder holder, int position) {
        AndroidApp app = appList.get(position);

        // Bind the decrypted data to the views
        holder.nameTextView.setText(app.getName());
        holder.subtitleTextView.setText(app.getSubtitle());
        // Load images (e.g., using Glide or Picasso)
        // Glide.with(holder.itemView.getContext()).load(app.getLogo()).into(holder.logoImageView);
    }

    @Override
    public int getItemCount() {
        return appList.size();
    }

    public static class AppViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        TextView subtitleTextView;
        ImageView logoImageView;

        public AppViewHolder(View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.app_name);
            subtitleTextView = itemView.findViewById(R.id.app_subtitle);
            logoImageView = itemView.findViewById(R.id.app_logo);
        }
    }
}







import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> {

    private List<AndroidApp> appList;

    public AppAdapter(List<AndroidApp> appList) {
        this.appList = appList;
    }

    @Override
    public AppViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_app, parent, false);
        return new AppViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AppViewHolder holder, int position) {
        AndroidApp app = appList.get(position);

        // Bind the decrypted data to the views
        holder.nameTextView.setText(app.getName());
        holder.subtitleTextView.setText(app.getSubtitle());
        // Load images (e.g., using Glide or Picasso)
        // Glide.with(holder.itemView.getContext()).load(app.getLogo()).into(holder.logoImageView);
    }

    @Override
    public int getItemCount() {
        return appList.size();
    }

    public static class AppViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView;
        TextView subtitleTextView;
        ImageView logoImageView;

        public AppViewHolder(View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.app_name);
            subtitleTextView = itemView.findViewById(R.id.app_subtitle);
            logoImageView = itemView.findViewById(R.id.app_logo);
        }
    }
}













import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AppAdapter appAdapter;
    private List<AndroidApp> appList = new ArrayList<>();

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

        // Set up RecyclerView
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Set up the adapter with an empty list initially
        appAdapter = new AppAdapter(appList);
        recyclerView.setAdapter(appAdapter);

        // Fetch the data from the API
        fetchData();
    }

    private void fetchData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://d1vzrdgjzuhzv7.cloudfront.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);

        Call<ApiResponse> call = apiService.getAndroidApps();
        call.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                if (response.isSuccessful()) {
                    List<AndroidApp> androidApps = response.body().getAndroidApps();

                    // Decrypt the data here
                    for (AndroidApp app : androidApps) {
                        try {
                            String secretKey = "TestHashKey";
                            app.setName(BlowfishDecryptor.decrypt(app.getName(), secretKey));
                            app.setApp_url(BlowfishDecryptor.decrypt(app.getApp_url(), secretKey));
                            // Repeat for other fields
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    // Update the RecyclerView with the new data
                    appList.clear();
                    appList.addAll(androidApps);
                    appAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                Log.e("API Error", "Failed to fetch data: " + t.getMessage());
            }
        });
    }
}






import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiService {

    @GET("fullscreen/bundle/779363139b5863e7865adb8b925a2ce18ad.json")
    Call<ApiResponse> getAndroidApps();
}






import java.util.List;

public class ApiResponse {
    private List<AndroidApp> androidApps;

    public List<AndroidApp> getAndroidApps() {
        return androidApps;
    }

    public void setAndroidApps(List<AndroidApp> androidApps) {
        this.androidApps = androidApps;
    }
}





item_app

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <ImageView
        android:id="@+id/app_logo"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginEnd="8dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_foreground"
        android:contentDescription="App Logo"/>

    <TextView
        android:id="@+id/app_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="App Name"
        android:textStyle="bold"
        android:layout_toEndOf="@id/app_logo"/>

    <TextView
        android:id="@+id/app_subtitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="App Subtitle"
        android:layout_toEndOf="@id/app_logo"/>
</androidx.constraintlayout.widget.ConstraintLayout>




main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>







Sunday, August 4, 2024

Hint of kotlin mvvmApi

 interface ApiInterFace {


@POST("Login/Login")
fun login(@Body loginRequest: LoginRequest): Call<LoginResponse>



@POST("Home/SyncAllData")
fun syncAll(@Body syncRequest:SyncAllRequest,
@Header("Authorization") authToken: String):Call<List<SyncAllReesponse>>
}


&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&    (Repository))

class LoginRepository(private val apiInterface: ApiInterFace) {

fun login(loginRequest: LoginRequest, onResult: (Result<LoginResponse>) -> Unit) {

apiInterface.login(loginRequest).enqueue(object : Callback<LoginResponse> {
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {

if (response.isSuccessful) {

response.body()?.let {
onResult(Result.success(it))
} ?: onResult(Result.failure(Exception("Response body is null")))
} else {
onResult(Result.failure(Exception("Failed to login")))
}
}

override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
onResult(Result.failure(t))
}
})
}




fun syncAll(syncAllRequest: SyncAllRequest, token:String , onResult: (Result<List<SyncAllReesponse>>) -> Unit) {

apiInterface.syncAll(syncAllRequest , "Bearer " +token).enqueue(object : Callback<List<SyncAllReesponse>> {
override fun onResponse(call: Call<List<SyncAllReesponse>>, response: Response<List<SyncAllReesponse>>) {

if (response.isSuccessful) {

response.body()?.let {
onResult(Result.success(it))
Log.i("checkcheck",response.message())
} ?: onResult(Result.failure(Exception("Response body is null")))
} else {
onResult(Result.failure(Exception("Failed to login")))
}
}

override fun onFailure(call: Call<List<SyncAllReesponse>>, t: Throwable) {
onResult(Result.failure(t))
}
})
}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& viewModel

class LoginViewModel : ViewModel() {

private val loginResponseLiveData: MutableLiveData<LoginResponse?> = MutableLiveData()
val syncResponseLiveData: MutableLiveData<List<SyncAllReesponse?>> = MutableLiveData()

val getHomeCollectionDataLiveData: MutableLiveData<List<SyncAllReesponse?>> = MutableLiveData()

private val loginRepository: LoginRepository = LoginRepository(ApiClient().getInstance().create(ApiInterFace::class.java))

fun getLoginResponseLiveData(): LiveData<LoginResponse?> {
return loginResponseLiveData
}

fun getSyncAllDataResponseLiveData(): LiveData<List<SyncAllReesponse?>> {
return syncResponseLiveData
}
fun GetHomeCollectionDataLiveData(): LiveData<List<SyncAllReesponse?>> {
return getHomeCollectionDataLiveData
}

fun login(loginRequest: LoginRequest) {

loginRepository.login(loginRequest) { result ->
result.fold(
onSuccess = { loginResponseLiveData.postValue(it) },
onFailure = { loginResponseLiveData.postValue(null) }
)
}
}


fun syncAllData(syncAllRequest: SyncAllRequest , token:String) {

loginRepository.syncAll(syncAllRequest , token) { result ->
result.fold(
onSuccess = { syncResponseLiveData.postValue(it) },
onFailure = { syncResponseLiveData.postValue(null) }
)
}
}

// fun GetHomeCollectionData(syncAllRequest: SyncAllRequest , token:String) {
//
// loginRepository.GetHomeCollectionData(syncAllRequest , token) { result ->
// result.fold(
// onSuccess = {getHomeCollectionDataLiveData.postValue(it) },
// onFailure = { getHomeCollectionDataLiveData.postValue(null) }
// )
// }
// }


fun GetHomeCollectionData(syncAllRequest: SyncAllRequest, token: String) {
loginRepository.GetHomeCollectionData(syncAllRequest, token) { result ->
result.fold(
onSuccess = { response ->
// Log the response here
//Log.d("Response", "GetHomeCollectionData response: ${response.getHomeCollectionDataLiveData}")
getHomeCollectionDataLiveData.postValue(response)
},
onFailure = {
// Log failure if needed
Log.e("Response", "GetHomeCollectionData failed: $it")
getHomeCollectionDataLiveData.postValue(null)
}
)
}
} &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& call mainActivity
loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java) /// oncreate mai

private fun setUpOserber() {

loginViewModel!!.getSyncAllDataResponseLiveData().observe(this) { response ->
response?.let {
if (response.isEmpty()) {

startActivity(Intent(this, LoginActivity::class.java))
Toast.makeText(this, "Prem is here", Toast.LENGTH_SHORT).show()
Log.i("alldatalisttt", it.toString())
setupRecyclerViewNew(it)

} else {
Toast.makeText(this, "prem where r u", Toast.LENGTH_SHORT).show()

}
private fun setupRecyclerViewNew(syncAllReesponses: List<SyncAllReesponse?>) {

binding.rvSyncData.setHasFixedSize(true);
binding.rvSyncData.setLayoutManager(LinearLayoutManager(getApplicationContext()))
binding.rvSyncData.setAdapter(SyncAllDataAdapter(getApplicationContext(), syncAllReesponses))


}
}
}
binding.btnGetCollectionData.setOnClickListener {

var syncAllRequest = SyncAllRequest(
22,
"22",
"22.3333",
"33.4455",
"701",
11,
"4er4",
"",
"15-March-2024"
)
loginViewModel.GetHomeCollectionData(syncAllRequest, token) }

} &&&&&&&&&&&&&&&&&&& retrofit ClientClass
package com.example.selfapimvvmkotlin

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class ApiClient {

private val baseUrl = "http://uatlims.apollohl.in/homecollection/api/"

fun getInstance(): Retrofit {
val httpClient = OkHttpClient.Builder()

// Add logging interceptor
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY // Set your desired log level
httpClient.addInterceptor(loggingInterceptor)

// Add your other interceptors here
httpClient.addInterceptor { chain ->
val original = chain.request()

val requestBuilder = original.newBuilder()
.header("Your-Header-Name", "Your-Header-Value")

val request = requestBuilder.build()
chain.proceed(request)
}

return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build()) // Set the custom OkHttpClient
.build()
}
} &&&&&&
  // retrofit

implementation ("com.squareup.retrofit2:retrofit:2.9.0")

// GSON

implementation ("com.squareup.retrofit2:converter-gson:2.9.0")

// coroutine

implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1")

implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")

implementation ("com.squareup.okhttp3:logging-interceptor:4.11.0")
implementation ("com.google.android.gms:play-services-location:20.0.0") // Check for the latest version
implementation ("androidx.biometric:biometric:1.1.0") &&&&&&& Adapter

class SyncAllDataAdapter(var context: Context, var doctorList: List<SyncAllReesponse?>) :
RecyclerView.Adapter<SyncAllDataAdapter.ViewHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(context).inflate(R.layout.layout_sync_data, parent, false)
return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

holder.binding.pName.setText(doctorList[position]?.syncAllReesponse?.get(position)?.pName)
holder.binding.tvSampleTypeName.setText(doctorList[position]?.syncAllReesponse?.get(position)?.city)

}

override fun getItemCount(): Int {
return doctorList.size
}

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var binding: LayoutSyncDataBinding

init {
binding = LayoutSyncDataBinding.bind(itemView)
}
}
}

Saturday, April 13, 2024

webviewjava

 package com.example.adsdekho;




import android.annotation.SuppressLint;

import android.graphics.Bitmap;

import android.net.http.SslError;

import android.os.Bundle;

import android.view.KeyEvent;

import android.view.View;

import android.webkit.JsPromptResult;

import android.webkit.JsResult;

import android.webkit.SslErrorHandler;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;


public class WebViewActivity extends AppCompatActivity {

    WebView webView;


    @SuppressLint("SetJavaScriptEnabled")

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_web_view);


        webView = findViewById(R.id.web);


        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);

        String urlViewPayment = "https://itd-saas04-cl.ondgni.com/CDMobileApp/Pages/login.aspx";

//        String urlViewPayment = "http://pandora.yilstaging.com/writable/uploads/20210127/1611811599_2ac19cd41e8387119d7e.\n" +

//                "mp3\n";

        getPaymentLinkOpenView(urlViewPayment);

}


    private void getPaymentLinkOpenView(String urlViewPayment) {


        webView.loadUrl(urlViewPayment);

        webView.setWebViewClient(new myWebViewclient());

        webView.setWebChromeClient(new myWebChromeClient());


    }


    public class myWebViewclient extends WebViewClient {


        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);


            return true;

        }


        @Override

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();

            webView.loadUrl("file:///android_asset/lost.html");

        }


        @Override

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

            super.onReceivedSslError(view, handler, error);

            handler.cancel();

        }


        @Override

        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);

        }


        @Override

        public void onPageFinished(WebView view, String url) {


            super.onPageFinished(view, url);


        }

    }



    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {

            webView.goBack();

            return true;

        }

        return super.onKeyDown(keyCode, event);

    }



    private class myWebChromeClient extends WebChromeClient {

        @Override

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsAlert");

            System.out.println(message+"onJsAlert");


            return super.onJsAlert(view, url, message, result);

        }


        @Override

        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsBeforeUnload");

            return super.onJsBeforeUnload(view, url, message, result);


        }


        @Override

        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsConfirm");


            return super.onJsConfirm(view, url, message, result);


        }


        @Override

        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {

            System.out.println(url+"onJsPrompt");


            return super.onJsPrompt(view, url, message, defaultValue, result);

        }

    }

}

webviewKotlin

 package com.example.medionndoctorapproval


import android.annotation.SuppressLint

import android.content.ContentValues.TAG

import android.content.Intent

import android.content.res.Configuration

import android.graphics.Bitmap

import android.net.Uri

import android.os.Build


import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.os.Environment

import android.os.Parcelable

import android.os.StrictMode

import android.provider.MediaStore

import android.util.Base64

import android.util.Log

import android.view.View


import android.webkit.*

import android.widget.Toast

import androidx.core.app.ActivityCompat

import java.io.File

import java.io.FileOutputStream

import java.io.IOException

import java.io.OutputStream

import java.lang.ref.WeakReference

import java.text.SimpleDateFormat

import java.util.Date


class MainActivity : AppCompatActivity() {


    private val permissions =

        arrayOf("android.permission.CAMERA", "android.permission.RECORD_AUDIO", "android.permission.MODIFY_AUDIO_SETTINGS")

    private val permissionsAll = 1

    private lateinit var webView: WebView // Declare webView as a global variable


    private var mFilePathCallback: ValueCallback<Array<Uri>>? = null

    private var mCameraPhotoPath: String? = null

    private val INPUT_FILE_REQUEST_CODE = 1

    private val FILECHOOSER_RESULTCODE = 1

    private var mUploadMessage: ValueCallback<Uri?>? = null

    private var mCapturedImageURI: Uri? = null



    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

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

            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {

                super.onActivityResult(requestCode, resultCode, data)

                return

            }

            var results: Array<Uri>? = null

            // Check that the response is a good one

            if (resultCode == RESULT_OK) {

                if (data == null) {

                    // If there is not data, then we may have taken a photo

                    if (mCameraPhotoPath != null) {

                        results = arrayOf(Uri.parse(mCameraPhotoPath))

                    }

                } else {

                    val dataString = data.dataString

                    if (dataString != null) {

                        results = arrayOf(Uri.parse(dataString))

                    }

                }

            }

            mFilePathCallback!!.onReceiveValue(results)

            mFilePathCallback = null

        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {

            if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {

                super.onActivityResult(requestCode, resultCode, data)

                return

            }

            if (requestCode == FILECHOOSER_RESULTCODE) {

                if (null == mUploadMessage) {

                    return

                }

                var result: Uri? = null

                try {

                    if (resultCode != RESULT_OK) {

                        result = null

                    } else {

                        // retrieve from the private variable if the intent is null

                        result = if (data == null) mCapturedImageURI else data.data

                    }

                } catch (e: Exception) {

                    Toast.makeText(

                        applicationContext, "activity :$e",

                        Toast.LENGTH_LONG

                    ).show()

                }

                mUploadMessage!!.onReceiveValue(result)

                mUploadMessage = null

            }

        }

        return

    }



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        webView = (findViewById(R.id.webView))


        //if (Utils.hasPermissions(this, permissions)) {

            joinVideo(findViewById(R.id.webView))

        //}


//        else {

//            ActivityCompat.requestPermissions(this, permissions, permissionsAll)

//        }


    }


    @SuppressLint("SetJavaScriptEnabled")

    private fun joinVideo(webView: WebView) {

        webView.run {

            scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY

            setLayerType(WebView.LAYER_TYPE_HARDWARE, null)

            val webSettings = webView.settings




            webSettings.setDomStorageEnabled(true);

            webSettings.setDatabaseEnabled(true);

            webSettings.setSupportMultipleWindows(true);

            webSettings.setMixedContentMode(0);




            webSettings.javaScriptEnabled = true

            webSettings.allowFileAccess = true

            webSettings.loadWithOverviewMode = true

            webSettings.javaScriptCanOpenWindowsAutomatically = true

            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)

            webSettings.loadsImagesAutomatically = true

            webSettings.mediaPlaybackRequiresUserGesture = false

            webView.loadUrl("http://103.30.72.57/MedionnMobileApp/Pages/login.aspx")

            webView.webViewClient = (WebClient(this@MainActivity))

            webView.webChromeClient = MyChromeClient()


            if (Build.VERSION.SDK_INT >= 19) {

                webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

            }

            else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {

                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

            }

            CookieManager.getInstance().setAcceptCookie(true);

            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);



            webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->

                if (url.startsWith("data:")) {  //when url is base64 encoded data

                    val path = createAndSaveFileFromBase64Url(url)

                    val builder = StrictMode.VmPolicy.Builder()

                    StrictMode.setVmPolicy(builder.build())

                    return@DownloadListener

                }

            })


        }

    }


    inner class MyChromeClient() : WebChromeClient() {

        override fun onPermissionRequest(request: PermissionRequest?) {

            request?.let { it.grant(it.resources) }

        }

        // For Android 5.0

        override fun onShowFileChooser(

            view: WebView,

            filePath: ValueCallback<Array<Uri>>,

            fileChooserParams: FileChooserParams

        ): Boolean {

            // Double check that we don't have any existing callbacks

            if (mFilePathCallback != null) {

                mFilePathCallback!!.onReceiveValue(null)

            }

            mFilePathCallback = filePath

            var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent!!.resolveActivity(packageManager) != null) {

                // Create the File where the photo should go

                var photoFile: File? = null

                try {

                    photoFile = createImageFile()

                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath)

                } catch (ex: IOException) {

                    // Error occurred while creating the File

                    Log.e(TAG, "Unable to create Image File", ex)

                }

                // Continue only if the File was successfully created

                if (photoFile != null) {

                    mCameraPhotoPath = "file:" + photoFile.absolutePath

                    takePictureIntent.putExtra(

                        MediaStore.EXTRA_OUTPUT,

                        Uri.fromFile(photoFile)

                    )

                } else {

                    takePictureIntent = null

                }

            }

            val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)

            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)

            contentSelectionIntent.type = "image/*"

            val intentArray: Array<Intent?>

            if (takePictureIntent != null) {

                intentArray = arrayOf(takePictureIntent)

            } else

            {

                intentArray = arrayOfNulls(0)

            }

            val chooserIntent = Intent(Intent.ACTION_CHOOSER)

            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)

            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")

            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE)

            return true

        }


        @JvmOverloads

        fun openFileChooser(uploadMsg: ValueCallback<Uri?>?, acceptType: String? = "") {

            mUploadMessage = uploadMsg

            // Create AndroidExampleFolder at sdcard

            // Create AndroidExampleFolder at sdcard

            val imageStorageDir = File(

                Environment.getExternalStoragePublicDirectory(

                    Environment.DIRECTORY_PICTURES

                ), "AndroidExampleFolder"

            )

            if (!imageStorageDir.exists()) {

                // Create AndroidExampleFolder at sdcard

                imageStorageDir.mkdirs()

            }

            // Create camera captured image file path and name

            val file = File(

                imageStorageDir.toString() + File.separator + "IMG_"

                        + System.currentTimeMillis().toString() + ".jpg"

            )

            mCapturedImageURI = Uri.fromFile(file)

            // Camera capture image intent

            val captureIntent = Intent(

                MediaStore.ACTION_IMAGE_CAPTURE

            )

            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI)

            val i = Intent(Intent.ACTION_GET_CONTENT)

            i.addCategory(Intent.CATEGORY_OPENABLE)

            i.type = "image/*"

            // Create file chooser intent

            val chooserIntent = Intent.createChooser(i, "Image Chooser")

            // Set camera intent to file chooser

            chooserIntent.putExtra(

                Intent.EXTRA_INITIAL_INTENTS, arrayOf<Parcelable>(captureIntent)

            )

            // On select image call onActivityResult method of activity

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE)

        }


        //openFileChooser for other Android versions

        fun openFileChooser(

            uploadMsg: ValueCallback<Uri?>?,

            acceptType: String?,

            capture: String?

        ) {

            openFileChooser(uploadMsg, acceptType)

        }

    }


    @Throws(IOException::class)

    private fun createImageFile(): File {

        // Create an image file name

        val timeStamp =

            SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())

        val imageFileName = "JPEG_" + timeStamp + "_"

        val storageDir = Environment.getExternalStoragePublicDirectory(

            Environment.DIRECTORY_PICTURES

        )

        return File.createTempFile(

            imageFileName,  /* prefix */

            ".jpg",  /* suffix */

            storageDir /* directory */

        )

    }


    fun createAndSaveFileFromBase64Url(url: String): String {

        val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

        val filetype = url.substring(url.indexOf("/") + 1, url.indexOf(";"))

        val filename = System.currentTimeMillis().toString() + "." + filetype

        val file = File(path, filename)

        try {

            if (!path.exists()) path.mkdirs()

            if (!file.exists()) file.createNewFile()

            val base64EncodedString = url.substring(url.indexOf(",") + 1)

            val decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT)

            val os: OutputStream = FileOutputStream(file)

            os.write(decodedBytes)

            os.close()

        } catch (e: IOException) {

            Log.w("ExternalStorage", "Error writing $file", e)

            Toast.makeText(applicationContext, "", Toast.LENGTH_LONG).show()

        }

        return file.toString()

    }



    fun showLog(message: String?) {

        Log.i(KEY_TAG, "$message")

    }


//    class MyChromeClient : WebChromeClient() {

//

//        override fun onPermissionRequest(request: PermissionRequest?) {

//            request?.let { it.grant(it.resources) }

//        }

//

////code for adding attachment

//

//

//    }



    class WebClient(activity: MainActivity) : WebViewClient() {

        private val reference = WeakReference(activity)

        override fun onLoadResource(view: WebView?, url: String?) {

            super.onLoadResource(view, url)

            reference.get()?.showLog("onLoadResource $url")

        }



        override fun onPageFinished(view: WebView?, url: String?) {


            if(url.equals("https://his-mobile-vv.c-care.mu")) {

                println("Exit")


                // i want to jump on MyAppointmentFragment in this method

                //with bundle.putString("type", "Teleconsultation")



            }


            super.onPageFinished(view, url)

            reference.get()?.showLog("onPageFinished $url")

            println(url)


        }


        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {

            super.onPageStarted(view, url, favicon)

        }


    }


    override fun onConfigurationChanged(newConfig: Configuration) {

        super.onConfigurationChanged(newConfig)

        // Do nothing here to prevent reloading WebView on orientation change

    }


    override fun onBackPressed() {

//        val builder = AlertDialog.Builder(this)

//        builder.setTitle("Kindly Logout From The Video Conference !")

//        builder.setMessage("")

//        builder.show()

//        builder.setCancelable(true)

//        Toast.makeText(this, "Please Press Exit From Video ", Toast.LENGTH_LONG).show()


        webView.destroy()

        super.onBackPressed()


    }


    companion object {

        const val KEY_TAG = "MainActivity"

    }


}

RootedDevice

 Step->(1)      // rooted library

    implementation 'com.scottyab:rootbeer-lib:0.0.9'


Step->(2)*********************************************** 

public class RootDetectionUtil {


    public static boolean isDeviceRooted(Context context) {

        // Check for root access using RootBeer

        RootBeer rootBeer = new RootBeer(context);

        if (rootBeer.isRooted()) {

            return true;

        }


        // Check for the presence of known root-related files and binaries

        if (checkForRootFiles() || checkForRootBinaries()) {

            return true;

        }


        return false;

    }


    private static boolean checkForRootFiles() {

        // Check for the presence of known root-related files

        String[] rootFiles = {"/system/app/Superuser.apk", "/system/xbin/su", "/system/bin/su"};

        for (String file : rootFiles) {

            File rootFile = new File(file);

            if (rootFile.exists()) {

                return true;

            }

        }

        return false;

    }


    private static boolean checkForRootBinaries() {

        // Check for the presence of known root-related binaries

        String[] rootBinaries = {"su", "busybox", "magisk", "supersu"};

        for (String binary : rootBinaries) {

            String binaryPath = "/system/xbin/" + binary;

            File binaryFile = new File(binaryPath);

            if (binaryFile.exists()) {

                return true;

            }

        }

        return false;

    }

}



Step->(3)*********************************************



public class DeveloperModeChecker {


    public static boolean isDeveloperModeEnabled(Context context) {

        // Check if the developer mode setting is enabled

        int developerModeSetting = Settings.Global.getInt(context.getContentResolver(),

                Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);


        // Additionally, check if the USB debugging setting is enabled

        int usbDebuggingSetting = Settings.Global.getInt(context.getContentResolver(),

                Settings.Global.ADB_ENABLED, 0);


        // If either developer mode or USB debugging is enabled, return true

        return developerModeSetting != 0 || usbDebuggingSetting != 0;

    }


}



Step->(4)*********************************************Call login Activity


 // Check for root access using the utility class

        if (RootDetectionUtil.isDeviceRooted(LoginActivity.this) || DeveloperModeChecker.isDeveloperModeEnabled(LoginActivity.this)) {

            // Device is rooted or potentially compromised

            // Show a message or take appropriate action

            Toast.makeText(LoginActivity.this, "Device Is Rooted", Toast.LENGTH_SHORT).show();

            finish();

        }




Calender

 ****** globaly Declaire

   int day, year, month;

    Calendar calendar;

    DatePickerDialog datePicker;

    String dob = "";

{

        {

            calendar = Calendar.getInstance();

            day = calendar.get(Calendar.DAY_OF_MONTH);

            year = calendar.get(Calendar.YEAR);

            month = calendar.get(Calendar.MONTH);

            datePicker = new DatePickerDialog(DispatchActivity.this, new DatePickerDialog.OnDateSetListener() {

                @Override

                public void onDateSet(android.widget.DatePicker view, int year, int month, int dayOfMonth) {

                    // adding the selected date in the edittext

                    binding.fromDate.setText(dayOfMonth + "-" + (month + 1) + "-" + year);

                    dob = year + "-" + (month + 1) + "-" + dayOfMonth;

                }

            }, year, month, day);

            // set maximum date to be selected as today

//        datePicker.getDatePicker().setMinDate(calendar.getTimeInMillis());

            // show the dialog

            datePicker.show();



        }


    }





////////////////////////////////////////////////////////////////////////////////////////////////Kotlin code.....!!!


global variable  define



    private var day: Int = 0

    private var year: Int = 0

    private var month: Int = 0

    private lateinit var calendar: Calendar

    private lateinit var datePicker: DatePickerDialog

    private var dob: String = ""





  calendar = Calendar.getInstance()

             day = calendar.get(Calendar.DAY_OF_MONTH)

             year = calendar.get(Calendar.YEAR)

             month = calendar.get(Calendar.MONTH)


             datePicker = DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->

                 // Adding the selected date in the edittext

                 binding.includePersonalLayout.dob.text = "$dayOfMonth-${month + 1}-$year"

                 dob = "$year-${month + 1}-$dayOfMonth"

             }, year, month, day)


             // Uncomment the following line to set the maximum date to be selected as today

              datePicker.datePicker.maxDate = calendar.timeInMillis


             // Show the dialog

             datePicker.show()


LocationUtils

 


 


public class LocationUtils {


    private static final int LOCATION_PERMISSION_REQUEST_CODE = 101;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationUpdateListener listener;
    private Activity activity;

    public interface LocationUpdateListener {
        void onLocationReceived(Location location);
        void onLocationPermissionDenied();
    }

    public LocationUtils(Activity activity, LocationUpdateListener listener) {
        this.activity = activity;
        this.listener = listener;
        this.fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity);
    }

    public void checkPermissionsAndGetLocation() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            getLastLocation();
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            } else {
                if (listener != null) {
                    listener.onLocationPermissionDenied();
                }
            }
        }
    }

    private void getLastLocation() {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null && listener != null) {
                        listener.onLocationReceived(location);
                    }
                }
            });
        }
    }
}




step-(2) use in Activity

globally declair-> LocationUtils locationUtils;

in declaire oncreate->  
locationUtils = new LocationUtils(OtpLoginActivity.this,this);
locationUtils.checkPermissionsAndGetLocation();

  step(3)outer of oncreate->
  @Override
    public void onLocationReceived(Location location) {
         latitude = location.getLatitude();
         longitude = location.getLongitude();
//        Toast.makeText(this, "Latitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onLocationPermissionDenied() {

        locationText.setText("Location permission denied.");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        locationUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    public class OtpHandler {


        public OtpHandler() {
        }

this is first step->>
class ko implement krna hoga implement keyword se upprr
implements LocationUtils.LocationUpdateListener
isss type se example k torr p->
@AndroidEntryPoint
public class OtpLoginActivity  extends BaseActivity<LoginViewModel, ActivityOtpLoginBinding> implements LocationUtils.LocationUpdateListener{