java.lang.NullPointerException in onCreate for some SDK versions - android-studio

Recently I have updated the webview code and updated the apk on playstore. On update, some of the devices are not able to open the app; specifically Android 12 devices. Tried to take reference from other stack post to solve it, but nothing seems to address this specific issue.
Would appreciate if you go through the code below and let me know the issue.
Stack trace from playstore console-> Type: java.lang.RuntimeException
Exception java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3846)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4022)
at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2336)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:246)
at android.app.ActivityThread.main (ActivityThread.java:8653)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1130)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
at com.careturtle.patient1.MainActivity.onCreate (MainActivity.java:126)
at android.app.Activity.performCreate (Activity.java:8207)
at android.app.Activity.performCreate (Activity.java:8191)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3819)
MainActivity
package com.example.test;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
//import com.monstertechno.adblocker.AdBlockerWebView;
//import com.monstertechno.adblocker.util.AdBlocker;
public class MainActivity extends Activity {
private static final int LOCATION_PERMISSION_CODE = 1;
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_main);
Context = this;
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token1 = sharedPreferences.getString("regtoken", null);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
//new AdBlockerWebView.init(this).initializeWebView(mWebview);
WebSettings webSettings = mWebview.getSettings();
if(welcome.action_var == "3"){
mWebview.clearCache(true);
Toast.makeText(getApplicationContext(), "App Reset Successful!", Toast.LENGTH_LONG).show();
welcome.action_var = "0";
}
webSettings.setTextSize(WebSettings.TextSize.NORMAL);
mWebview.getSettings().setJavaScriptEnabled(true);
CookieManager.getInstance().setAcceptCookie(true);
mWebview.setWebChromeClient(new WebChromeClient());
//mWebview.setWebChromeClient(new JsPopupWebViewChrome());
mWebview.setWebViewClient(new CustomWebViewClient());
//mWebview.setWebViewClient(new Browser_home());
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
//webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptEnabled(true);
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if(welcome.action_var == "2") {
mWebview.loadUrl("https://www.example.com/faq");
}else if(welcome.action_var == "4") {
mWebview.loadUrl("https://www.example.com/change_language");
}else if (welcome.action_var == "666"){
String qrLink = getIntent().getStringExtra("a");
mWebview.loadUrl(qrLink);
}else{
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("https://www.example.com/active_token");
getIntentValue = null;
} else {
mWebview.loadUrl("https://www.example.com/testa?reg=" + r);
}
}
}
}
mWebview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("ALERT!")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
// Indicate that we're handling this manually
return true;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback){
callback.invoke(origin, true, false);
}
});
if ( Build.VERSION.SDK_INT >= 23){
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED ){
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);
//return ;
} else {
if (canGetLocation()) {
//DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED
} else {
//SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
}
}
public boolean canGetLocation() {
boolean result = true;
LocationManager lm;
boolean gpsEnabled = false;
boolean networkEnabled = false;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
return gpsEnabled && networkEnabled;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
if (canGetLocation()) {
} else {
//SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
private static final long TIMEOUT = 25000L;
private Handler timeoutHandler = new Handler();
// #SuppressWarnings("deprecation")
// #Override
// public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
// return AdBlockerWebView.blockAds(view,url) ? AdBlocker.createEmptyResource() :
// super.shouldInterceptRequest(view, url);
//
// }
private Runnable timeoutRunnable = new Runnable() {
#Override
public void run() {
//show some error message here
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
}
};
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
} else if (url.contains("example.com")) {
view.loadUrl(url);
} else {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
//} else if (url.contains("www.") && !url.contains("www.example.com")) {
// Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// startActivity(i);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
String currentPage = mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage", currentPage);
editor.apply();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
timeoutHandler.removeCallbacks(timeoutRunnable);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebview.clearCache(true);
timeoutHandler.removeCallbacks(timeoutRunnable);
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
if(Build.VERSION.SDK_INT >= 21) {
if (errorResponse.getStatusCode() != 404) {
mWebview.clearCache(true);
timeoutHandler.removeCallbacks(timeoutRunnable);
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
super.onReceivedHttpError(view, request, errorResponse);
}
}
}
}
//-------------
#Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}else if (currenturl.contains("https://www.example.com/welcome") || currenturl.contains("https://www.example.com/login") || currenturl.contains("https://www.example.com/faq") || currenturl.contains("https://www.example.com/change_language")){
Intent intent = new Intent(MainActivity.this, welcome.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent);
}else {
mWebview.goBack();
}
if (mWebview.canGoBack()) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("https://www.example.com/welcome");
getIntentValue = null;
} else {
try {
mWebview.loadUrl("https://www.example.com/testa?reg=" + r);
}catch (Exception e){
}
}
}
public static void reLoad() {
mWebview.reload();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
Build.Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 31
buildToolsVersion '30.0.3'
defaultConfig {
applicationId "com.example.test"
minSdkVersion 24
targetSdkVersion 31
versionCode 48
versionName "5.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testImplementation 'junit:junit:4.12'
implementation 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
implementation 'com.google.firebase:firebase-messaging:11.0.4'
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
//implementation 'com.github.MonsterTechnoGits:WebViewAdblock:1.1'
// implementation 'me.dm7.barcodescanner:zxing:1.9'
def camerax_version = "1.0.0-beta07"
implementation "androidx.camera:camera-camera2:$camerax_version"
implementation "androidx.camera:camera-lifecycle:$camerax_version"
implementation "androidx.camera:camera-view:1.0.0-alpha14"
implementation 'com.google.zxing:core:3.3.3'
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
}
apply plugin: 'com.google.gms.google-services'
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.test">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA2" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<meta-data
android:name="android.webkit.WebView.EnableSafeBrowsing"
android:value="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_icon"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_icon"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:allowBackup,icon,theme,label"
android:usesCleartextTraffic="true">
<activity
android:name=".ScannerActivity"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"></activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".SimpleScannerActivity"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"></activity>
<activity
android:name="com.example.test.welcome"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:exported="true"
android:launchMode="singleTop"
tools:replace="android:screenOrientation"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="http"
android:host="www.example.com"
/>
</intent-filter>
</activity>
<!-- http://play.google.com/store/apps/details?id=com.example.test -->
<!-- Accepts URIs that begin with "http://example.com/test/test1" -->
<!-- <data android:scheme="myapp" />
<data android:scheme="http" android:host="careturtle1.com" android:pathPrefix="/barcode"/>
<intent-filter
android:label="#string/app_name">
<action android:name="android.intent.action.VIEW" />
<data
android:host="play.google.com/store/apps/details?id="
android:pathPrefix="/com.example.test"
android:scheme="http"/>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
-->
<service android:name=".MyFirebaseInstanceId"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".FcmMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_icon" />
<activity
android:name=".noconnection"
android:screenOrientation="portrait"></activity>
</application>
</manifest>

Related

Broadcast Reciever ACTION_SHUTDOWN Intent is not working in Android version 11

Foreground service class code for calling the shutDown broadcast receiver.
public class SmsForegroundService extends Service{
private BroadcastReceiver receiver;
public static class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
Log.d(TAG, "onReceive: "+intent.getAction());
if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
Log.d(TAG, "onReceive: ScreenOff");
}
}
// constructor
public MyReceiver(){
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
receiver = new MyReceiver();
this.registerReceiver(receiver,filter);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: service destroyed");
super.onDestroy();
this.unregisterReceiver(receiver);
}
//
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG ,"service running");
final String CHANNEL_ID = "foreground Service ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentText("Service is running")
.setContentTitle("Service is enabled")
.setSmallIcon(R.drawable.ic_launcher_background);
startForeground(1001, notification.build());
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return null;
}
}
AndroidManifest file, here I added only the permission for Foreground services, I think there is no other permission is required for action_shutdown in manifest for versions greater than Oreo.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mywork.smsbroadcast">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SmsBroadcast">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".SmsForegroundService">
</service>
</application>
</manifest>
MainActivity I have called the service class inside on Create method MainActivity class.
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!foregroundServiceRunning())
{
Intent serviceIntent = new Intent(this, SmsForegroundService.class);
ContextCompat.startForegroundService(this,serviceIntent);
}
}
public boolean foregroundServiceRunning(){
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo serviceInfo: activityManager.getRunningServices(Integer.MAX_VALUE)){
if(SmsForegroundService.class.getName().equals(serviceInfo.service.getClassName())){
return true;
}
}
return false;
}
}

Encrypt Bluetooth Chat

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

Action_Call permission not granted in Android Studio

I am trying to make an app which can directly call if the number is entered but the permission is not granted and hence no call is made...
I have requested permission in AndriodManifest.xml
Everytime I enter a number, "Hello" pops up which is written if Granted is Not Granted.
My code:
MainActivity.java
package com.example.block9;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void redirectmessage(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
String message = (((EditText) findViewById(R.id.textmessage)).getText()).toString();
Uri num = Uri.parse("smsto:" + number);
Intent smsIntent = new Intent(Intent.ACTION_SENDTO, num);
smsIntent.putExtra("sms_body", message);
startActivity(smsIntent);
}
public void redirectcall(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
Toast t = null;
//t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
return;
}
startActivity(callIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.block9">
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any Help would be Appreciated!!`enter code here.
If your Target Device API is <22 then you don't need to ask for permission as the permission will automatically provide But as a Developer you have to ready for every possibility. in case if target device API is >=23 then you have to manually request the permission. For more information on this Read this
public void redirectcall(View v) {
String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
Toast t = null;
//t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
grantPermission();
return;
}
startActivity(callIntent);
}
private void grantPermission() {
// show your dialog box to ask for permission
new AlertDialog.Builder(this)
.setTitle("Call Permission Required")
.setMessage("This App needs Call permission, to function properly")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
.show();
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//here permission will be given
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 3); // 3 is requestCode and can be any number
}
})
.create()
.show();
}
After Making a Request Now, we will call #Override method onRequestPermissionsResult() to handle the scenario of Rejected or accepted Request
*#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 3: //remember that 3 is the same number which we specified while requesting
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// Call-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
redirectcall();
}
}else{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}*
Full MainActivity.java code is here: https://gist.github.com/Shoaibpython/eda5394ee4bc441396d68d5ef603cd3
Please consider replying here if you saw any error.

How to fix gradle error in android studio

I am trying to build an application for tracking the location as a background service. Latitude and Longitude points should change when the location changes.
The error I am getting is "failed linking references". So I tried changing the sdk version to 28 and build tools to 3.2.0 but facing issues.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.suppalapat21.tracker">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Dependencies:
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
}
build.gradle(app):
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.suppalapat21.tracker"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-location:17.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
MainActivity.java
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements ConnectionCallbacks,OnConnectionFailedListener,LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1000);
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
Log.v(this.getClass().getSimpleName(), "onPause()");
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
Error Message:
Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
Error:error: failed linking references.

Android Studio Code Dont Work On Android Version 9.0

Please My Android App works well in any android app version but dont work on android 9.0 ??
there is no errors display when run the code from android studio on emulator ..
this is my login_activity.java
package com.steam.carwash.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.icanstudioz.sclient.R;
import com.steam.carwash.Server.Server;
import com.steam.carwash.custom.MyApplication;
import com.steam.carwash.fragment.ForgotPassword;
import com.steam.carwash.model.ResObj;
import com.steam.carwash.model.User;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.norbsoft.typefacehelper.TypefaceHelper;
import com.steam.carwash.permissionhelper.ActivityManagePermission;
import org.json.JSONObject;
import okhttp3.ResponseBody;
public class LoginActivity extends ActivityManagePermission {
EditText email, password;
Button login;
TextView register, forgot;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
bindViews();
}
private void bindViews() {
mProgress = new ProgressDialog(this);
mProgress.setTitle("Processing...");
mProgress.setMessage("Please wait...");
mProgress.setCancelable(false);
mProgress.setIndeterminate(true);
email = findViewById(R.id.input_email);
password = findViewById(R.id.input_password);
login = findViewById(R.id.btn_login);
register = findViewById(R.id.txt_register);
forgot = findViewById(R.id.txt_forgot);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
final String eml = email.getText().toString().trim();
final String pwd = password.getText().toString().trim();
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
loginUser(eml, pwd,instanceIdResult.getToken());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loginUser(eml, pwd,"");
}
});
}
}
});
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
TypefaceHelper.typeface(email, MyApplication.getLight());
TypefaceHelper.typeface(password, MyApplication.getLight());
TypefaceHelper.typeface(register, MyApplication.getRegular());
TypefaceHelper.typeface(forgot, MyApplication.getRegular());
TypefaceHelper.typeface(login, MyApplication.getRegular());
}
private Boolean validate() {
String eml = email.getText().toString().trim();
String pwd = password.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(eml).matches()) {
email.setError(getString(R.string.email_is_invalid));
} else if (pwd.isEmpty()) {
password.setError(getString(R.string.password_is_required));
} else {
//Toast.makeText(LoginActivity.this, "Is Valid", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private void loginUser(String email, String password, String token) {
Toast.makeText(LoginActivity.this, "okiii", Toast.LENGTH_SHORT).show();
HttpParams params = new HttpParams();
params.put("type", "simple");
params.put("utype", "0");
params.put("email", email);
params.put("password", password);
params.put("fcm_token", token);
OkGo.<ResObj<User>>post(Server.BASE_URL + "user/login").params(params).execute(new Callback<ResObj<User>>() {
#Override
public void onStart(Request<ResObj<User>, ? extends Request> request) {
//Toast.makeText(LoginActivity.this, "ok", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(Response<ResObj<User>> response) {
Toast.makeText(LoginActivity.this, "Login On Success", Toast.LENGTH_SHORT).show();
if (response.body() != null) {
Toast.makeText(LoginActivity.this, "Good Job", Toast.LENGTH_SHORT).show();
ResObj<User> userResObj = response.body();
User user = userResObj.getData();
HttpParams params1=new HttpParams();
params1.put("access_token",user.getAccess_token());
params1.put("user_id",user.getId());
OkGo.getInstance().addCommonParams(params1);
MyApplication.getInstance().setUser(user);
MyApplication.getInstance().createLoginSession(user.getName(), user.getEmail(), user.getId(), user.getFcm_token(),user.getAccess_token());
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
Toast.makeText(LoginActivity.this, "Good b", Toast.LENGTH_SHORT).show();
finish();
}
else
Toast.makeText(LoginActivity.this, "Error 2", Toast.LENGTH_SHORT).show();
}
#Override
public void onCacheSuccess(Response<ResObj<User>> response) {
}
#Override
public void onError(Response<ResObj<User>> response) {
}
#Override
public void onFinish() {
}
#Override
public void uploadProgress(Progress progress) {
}
#Override
public void downloadProgress(Progress progress) {
}
#Override
public ResObj<User> convertResponse(okhttp3.Response response) throws Throwable {
try {
ResponseBody responseBody = response.body();
String s = responseBody.string();
JSONObject jsonObject = new JSONObject(s);
Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
if (jsonObject.getString("status").equalsIgnoreCase("success")) {
return new Gson().fromJson(s, new TypeToken<ResObj<User>>() {
}.getType());
} else {
MyApplication.getInstance().showToast(LoginActivity.this, jsonObject.getString("data"));
}
} catch (Exception e) {
//Log.e("catch", e.toString());
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
});
}
}
and this is my androidmainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.icanstudioz.sclient">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:networkSecurityConfig="#xml/network_security_config"
android:debuggable="true"
android:name="com.steam.carwash.custom.MyApplication"
android:allowBackup="true"
android:icon="#drawable/splash"
android:label="#string/app_name"
android:roundIcon="#drawable/boy"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="HardcodedDebugMode">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<activity android:name="com.steam.carwash.activities.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.steam.carwash.fragment.ForgotPassword"/>
<activity android:name="com.steam.carwash.permissionhelper.ActivityManagePermission"/>
<activity
android:name="com.steam.carwash.activities.HomeActivity"
android:fitsSystemWindows="true"
android:windowSoftInputMode="adjustResize|stateAlwaysHidden" />
<activity android:name="com.steam.carwash.activities.LoginActivity" />
<activity android:name="com.steam.carwash.activities.PaymentActivity"/>
<activity
android:name="com.steam.carwash.activities.RegisterActivity"
android:windowSoftInputMode="adjustPan" />
<activity android:name="com.steam.carwash.activities.fullImage" />
<service android:name="com.steam.carwash.Server.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/c_id" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_launcher_foreground" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorPrimaryDark" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBX8-V0iihmTnrgwYlyI5GdP0GKjwfTTd8" />
</application>
when run this on android version 8.0 or below its work well ... but the problem is on version 9 or above ??
just put the below line in manifest under application tag and try
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
if doesnt work try adding below line
android:usesCleartextTraffic="true under application tag and even if it doesnt work try adding android:networkSecurityConfig="#xml/network_security_config in application tag where network_security_config.xml is<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
Create xml under res directory and then network_security_config.xml in xml folder

Resources