I have followed through this tutorial (I am completely new to Android Studio): Loading/Splash Screen Tutorial
and I am unsure why my code isn't working correctly.
I get the loading circle come up on the app I have created, but it does not go away when the app loads the webpage.
I have gone over my code a few times now and I cannot see any errors (obviously there are some somewhere!) Just seems as if it isn't recognising that my webpage has loaded within the app.
Here is my code from my MainActivity.java file:
import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
String ShowOrHideWebViewInitialUse = "show";
private WebView myWebView;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
myWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setMinimumFontSize(1);
myWebView.getSettings().setMinimumLogicalFontSize(1);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("https://node-red-test.ftp21.net:1024/ui");
myWebView.setWebViewClient(new WebViewClient() { #Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){ handler.proceed(); } });
}
// This allows for a splash screen
// (and hide elements once the page loads)
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView myWebView, String url, Bitmap favicon) {
// only make it invisible the FIRST time the app is run
if (ShowOrHideWebViewInitialUse.equals("show")) {
myWebView.setVisibility(myWebView.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(myWebView.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
I am currently running Android Studio version 2.1.2 - due to problems with later versions that I came across when following another tutorial.
Thanks,
Related
So as a homework from collage i have to make a simple login app using fingerprint, i followed this video: How to Make a FingerPrint Authentication System in Android Studio and Java
But im getting some error that aren't explained and i can't find a answer form, this is my code:
package com.example.actividad14;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.Color;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView msg_txt = findViewById(R.id.txt_msg);
Button login_btn = findViewById(R.id.login_btn);
BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate()){
case BiometricManager.BIOMETRIC_SUCCESS:
msg_txt.setText("You can use the fingerprint sensor to login");
msg_txt.setTextColor(Color.parseColor("#Fafafa"));
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
msg_txt.setText("The device doesn't have a fingerprint sensor");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
msg_txt.setText("The biometric sensor is currently unavailable");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
msg_txt.setText("Your device doesn't have any fingerprint saved, please check your security settings");
login_btn.setVisibility(View.GONE);
break;
}
Executor executor = ContextCompat.getMainExecutor(this);
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
#Override
public void onAuthenticationSucceeded(#NonNull androidx.biometric.BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),"Login Succes!", Toast.LENGTH_SHORT).show();
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder()
.setTitle("Login")
.setDescription("Use your fingerprint to login in your app")
.setNegativeButtonText("Cancel")
.build();
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
biometricPrompt.authenticate(prompInfo);
}
});
}
}
At BiometricManager biometricManager = BiometricManager.from(this); im getting "cannot resolve method 'from' in 'biometricmanager'", but every video i have seen says that you create your BiometricManager this way.
At BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() { im getting "'BiometricPrompt' has private access in 'android.hardware.biometrics.BiometricPrompt'".
At final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder() im getting "cannot resolve PromptInfo"
And finally at biometricPrompt.authenticate(prompInfo); im getting "cannot resolve method '(authenticate(BiometricPrompt.PrompInfo))'"
Sorry for the inconvinience, i fount out what was wrong, instead of using:
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
use
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
in the build.gradle i used
implementation 'androidx.biometric:biometric:1.2.0-alpha04'
But this can depend on new updates, so try with the newer ones also:
https://mvnrepository.com/artifact/androidx.biometric/biometric?repo=google
And finally i had PrompInfo instead of PromptInfo
This other post really helped me:
Android BiometricPrompt: Cannot resolve symbol PromptInfo
I'm currently creating my own application with Android Studio. In this app, I want to create a switch, that changes to dark mode and back.
In the MainActivity.java I'm using the following code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private Button button;
private Switch aSwitch;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button feed = findViewById(R.id.feed);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
aSwitch = findViewById(R.id.day_night);
checkNightModeActivated();
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(true);
recreate();
}
});
feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Newsfeed.class));
}
});
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
private void checkNightModeActivated() {
if(sharedpreferences.getBoolean(KEY_ISNIGHTMODE, false)) {
aSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
aSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
The problem is, that the switch will change the mode to dark when I've started the app. But then, the app beginns to flicker and does not longer responds.
Can soneone please tell me, what I'm doing wrong?
Kind regards
Kai
I've found a solution for my problem.
private Switch day_night;
day_night=findViewById(R.id.day_night);
day_night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});
package com.example.androidapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Login extends AppCompatActivity {
EditText username, password;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = findViewById(R.id.editTextEmail);
password = findViewById(R.id.editTextPassword);
btnLogin = findViewById(R.id.buttonLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(username.getText().toString()) || TextUtils.isEmpty(password.getText().toString())){
Toast.makeText(Login.this,"Username / Password Required", Toast.LENGTH_LONG).show();
}else{
//proceed to login
login();
}
}
});
}
public void login(){
LoginRequest loginRequest = new LoginRequest();
loginRequest.setUsername(username.getText().toString());
loginRequest.setPassword(password.getText().toString());
Call<LoginResponse> loginResponseCall = ApiClient.getUserService().userLogin(loginRequest);
loginResponseCall.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.d("#sid","res"+response.code());
if(response.isSuccessful()){
Toast.makeText(Login.this,"Login Successful", Toast.LENGTH_LONG).show();
final LoginResponse loginResponse = response.body();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Login.this,Permission2.class).putExtra("data",loginResponse.getUsername()));
}
},700);
}else{
Toast.makeText(Login.this,"Login Failed", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(Login.this,"Throwable "+t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Whenever I am trying to make a login page for my application, its showing login failed and its not passing intent as well as unable to pass the data on 2nd page of my application. I am helpless and not getting any idea to resolve this issue.
I request you to kindly check my above coding and let me know if I have done anything wrong.
First of all, please reformat the pasted code to be more readable.
Second of all - did you add Internet permission to AndroidManifest file?
Third of all - you can print what's wrong to log, for example:
Log.d("LoginError", "${response.errorBody.string()}");
Also did you follow some kind of tutorial on how to use Retrofit? Maybe follow some easy tutorial to get idea how to work this out :)
I'm trying face-recognition with android studio using opencv, for which I have just began loading opencv libraries and dependencies. It works fine on emulator, but the OpenCVLoader.initDebug() returns false when the app runs on real device.
This is my MainActivity.
package com.example.opencvtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.opencv.android.OpenCVLoader;
public class MainActivity extends AppCompatActivity {
private static String TAG = "MainActivity";
static{
if(OpenCVLoader.initDebug()){
Log.i(TAG,"OpenCV Loaded Successfully");
}
else{
Log.i(TAG,"Could not load openCV");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I have a problem with comunication between my phone and wear device. I decided to add wear module to my app. Wear app has just one class (MainActivity)
package cz.johrusk.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener {
GoogleApiClient mGoogleApiClient;
private TextView mTextView;
static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
sendNumber(1);
Log.d(TAG,"BBBBBBBB");
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
Log.d(TAG,"mGoogleApiClient connected;");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"FAILE" + connectionResult);
}
public void sendNumber(int number) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/number");
putDataMapRequest.getDataMap().putInt("number",number);
putDataMapRequest.getDataMap().putLong("Time",System.currentTimeMillis());
PutDataRequest putDataReq = putDataMapRequest.asPutDataRequest();
putDataReq.setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.d(TAG,"Fail");
}
else{
Log.d(TAG,"Succes");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG,"TEST");
}
}
I quess that "Wearable.DataApi.putDataItem" should call WearableListenerService in my phone app. Here is that service:
package cz.johrusk.showsmscode.service;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
public class WatchListener_service extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("prijato","number is: ");
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals("/number")){
int number = dataMap.getInt("numa");
long time = dataMap.getInt("timestamp");
Log.d("received","number is: " + number);
}
}
}
}
}
However, onDataChanged method in WatchListener_service isn't called. onResult method inside ResultCallbacks print "Succes" so it seems that DataItem is send correctly.
I already find many similar problems on Stackoverlflow so I checked all these things:
Both modules has same applicationId
Both modules use 'com.google.android.gms:play-services-wearable:9.0.0'
SetUrgent is used to putDataRequest so there shouldnt be any delay.
WearableListenerService has declared correct intent filter in Manifest :
action android:name="com.google.android.gms.wearable.DATA_CHANGED"
data android:scheme="wear" android:host="*"
Both phone and Wear app run on physical device. My question is... What should I do to fix this issue?
Thanks
Check if both apps have the same debug key. I had some problems with that and problem was different keys for both apps (wear and mobile).
PS: The Android Wear API is ridiculous. I quit developing for Wear because of how terrible is that API that doest not work as they say this should.