KILL App's MainActivity on Startup if(networkState==false || null) - java

Good day friends of mine.
I want to add a functionality to my ANDROID application, which I think it is new to me... but it is new in the development world. The application runs very well at the moment... But I need to add this functionality as explained below.
Please see the sample picture below...which tells exactly what I want to do.
I want to check network connection state on Application Startup.
If connection state is true, then, the application should load the MainActivity.xml.
If connection state is false, then, the application should return a new String ("Error") message.
Please see my code sample below...in the onCreate() {} thread.
NOTE: I am not proficient in android development please.
#Override
protected void onCreate(Bundle savedInstanceState) {
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();//this is line 91...
Log.d("Network Info", "" + activeNetwork);//log the connection info
if (activeNetwork != null && activeNetwork.isConnected()) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize the status bar textview control
statusBar = (TextView) findViewById(R.id.textViewStatusMsg);//status bar of the UI
titleLogin = (TextView) findViewById(R.id.textViewLogin);//title text of the UI
If the above condition is TRUE, the application runs well but if the following condition below is FALSE,
the application crashes with ANDROID's error message "Unfortunately, App has crashed!".
Instead of it giving me its own message and crashing, I want to kill the app programmatically using the else...statement below.
} else {
data = new String("NO NETWORK CONNECTION! TRY AGAIN...");
return; //return the message data and kill the APP's UI here
}
}
Any help will suffice please... I am not well vested in android programming and development...

I guess the reason for crashing is because of misplaced of super.onCreate method.
Move this statement outside if block and either you can do a toast message or show an alert dialog.
If above solution didn't work, comment the crash stacktrace.

Related

How do I fix "Could not reach Cloud Firestore Backend" error?

I'm build a simple app and I keep getting this error:
"W/Firestore: (23.0.1) [OnlineStateTracker]: Could not reach Cloud
Firestore backend. Backend didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in
offline mode until it is able to successfully connect to the backend."
I'm not sure why since my Wifi is at full strength. Can anyone assist with this issue? I'm using Java, Android Studio, and I'm testing my app with a Virtual Device.
I'm adding my code at the bottom. All this code is in my OnCreate method.
DocumentReference mDocRef = FirebaseFirestore.getInstance().document(document_path);
mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot){
if(documentSnapshot.exists()){
int Rent_amount = (int) documentSnapshot.get(Rent);
int Food_amount = (int) documentSnapshot.get(Food);
int Bills_amount = (int) documentSnapshot.get(Bills);
TextView Rent_test = (TextView) findViewById(R.id.rent_view);
Rent_test.setText(String.valueOf(Rent_amount));
TextView Food_test = (TextView) findViewById(R.id.Food_view);
Food_test.setText(String.valueOf(Food_amount));
TextView Bills_test = (TextView) findViewById(R.id.Bills_view);
Bills_test.setText(String.valueOf(Bills_amount));
}
}
});
Thank you so much for your help!
I solved this problem. I changed the type of Virtual Device to one without the Google Play Symbol.
If you are using Android Studio, Go to
AVD Manager
Your virtual devices
Drop down by the right-hand side of the device
Wipe Data
Cold Boot
This should fix your issue

Application "blinks" when speechRecognition is restarted

I'm developing an application that among other things , lets user interact with it by voice recognition (Speech to Text).For example user speaks the word "contacts" and the application can recognize and proceed to use logic to it to do something (i.e get the list of contacts and present them).
Now I have used a custom speech Recognizer , and not the one Google provides with the alert dialog.
I also have an animated gradient as a background with some colors.
From the RecognitionListener we get either an error as a response or we get results from the method onResults(Bundle results).In both cases after the response i need to restart the listener in order for the user to continue to interact with the application. However, when my speechRecognition is destroyed and created again, my application "blinks"(very quick black screen, but then the Ui is returned to normal).
I know that the problem is happening because i try to destroy my speechListener and then i re-create it(By calling the function restartSpeechListener), but i cannot seem to find a way to solve this "blinking".
Below is my code for the speechRecognizer initiation and restart :
public void startRecognising() {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechRecogniser listener = new mySpeechRecogniser();
Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"el");
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizer.setRecognitionListener(listener);
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
startActivity(mSpeechRecognizerIntent);
}
// Restart speech recogniser
public void restartSpeechListener() {
mSpeechRecognizer.stopListening();
mSpeechRecognizer.destroy();
startRecognising();
}
Any suggestions or help would be very helpful !

Run Android App Twice To Work, Why?

I'm making an android app that test if certain security features on your phone are enabled. For example, if you have password log in enabled or if your data is encrypted on your phone.
For some reason, the app has to be ran twice to test and see if these security features are enabled on the phone or not, and this is the problem I'm trying to solve. I'd like it to test and see if the security features are enabled when the app is created and the first time the app is run, not the second time it is run.
I test if these features are enabled in the onStart() function in my MainActivity file. I included the functions code below:
#Override
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#SuppressLint("NewApi")
public void onStart()
{
super.onStart();
//determine if phone uses lock pattern
//It returns 1 if pattern lock enabled and 0 if pin/password password enabled
ContentResolver cr = getBaseContext().getContentResolver();
lockPatternEnable = Settings.Secure.getInt(cr, Settings.Secure.LOCK_PATTERN_ENABLED, 0);//Settings.System
//returns 1 if pin/password protected. 0 if not
KeyguardManager keyguardManager = (KeyguardManager) getBaseContext().getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.isKeyguardSecure())
{
//it is pin or password protected
pinPasswordEnable=1;
}
else
{
//it is not pin or password protected
pinPasswordEnable=0;
}//http://stackoverflow.com/questions/6588969/device-password-in-android-is-existing-or-not/18716253#18716253
//determine if adb is enabled. works
adb=Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0);
//determine if bluetooth is enabled.works
bluetooth=Settings.Global.getInt(cr, Settings.Global.BLUETOOTH_ON, 0);
//Settings.System BLUETOOTH_DISCOVERABILITY
//determine if wifi is enabled. works
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled())
{
//wifi is enabled
wifiInt=1;
}
else
wifiInt=0;
//determine if data is encrypted
getDeviceEncryptionencryption();
//determine if gps enabled
}//end of onStart() function
If any more code needs to be posted to answer this question, just let me know, and thanks for your help. Maybe the issue has something to do with the super.onStart();
Does anyone think that a splash loading screen might help solve the issue?
super.onStart(); is fine. Splash screen will not help.
From your code I do not see how you determine how many times it ran.
You also mention testing - is it manual testing or you use any framework? Maybe your framework has some init method which runs before each run and it makes this extra call for onStart().
Issues is not in this code. Use debugger or logcat and figure out who calls you twice and, as #nasch had asked, what happens at first run.
Still, real question to help you remains - what do you mean "call twice". Is it you manually clicking app icon twice or is it some testing framework calls your app twice. Both cases are clear to solve.

Android/Java - Wait for AsyncTask to end before performing next function

I'm creating an app which'll show a list of configured Wi-Fi networks in its MainActivity. Now, before fetching the list of configured networks, my app checks if Wi-Fi is turned on. If not, it shows an AlertDialog containing a "Turn on Wi-Fi" Button which triggers an AsyncTask that turns on the Wi-Fi.
Now, I'm using this code to fetch the list of configured Wi-Fi networks
#SuppressWarnings("deprecation")
private ArrayList<String> getAvailableNetworks() {
manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
availableNetworks = new ArrayList<String>();
if (!manager.isWifiEnabled()) {
showDialog(2);
}
if (manager.isWifiEnabled()) {
configuredNetworks = manager.getConfiguredNetworks();
for (int i = 0; i < configuredNetworks.size(); i++) {
availableNetworks.add(configuredNetworks.get(i).SSID.replaceAll("\"", ""));
}
}
return availableNetworks;
}
Now, the problem is that when the app finds out that the Wi-Fi is turned off, it just shows the AlertDialog using showDialog(2); and moves on to the next line of code which leaves the list of configured networks completely blank.
How do I get it to wait until the AsyncTask finishes turning on Wi-Fi before it moves on to the next line of code?
Thanks in Advance.
You can start an Indeterminate Progress Dialog (unCancelable) at OnPreExecute and then dismiss it in onPostExecute
And if you don't want the code to get started executing before the asyncTask gets Completed, just put that code in onPostExecute method of AsyncTask

Android alertdialog not showing when I think it should

I'm developing an android app which I want to check if there's internet connection, if it's not the case display a warning message, and when there's internet connection again load a certain url.
It can be said that both displaying the message and checking there's internet connection work... but no separately.
I mean I have the following code:
if (!checkConnectivity())
{
browser.stopLoading();
LayoutInflater layoutinflater = LayoutInflater.from(app);
final View textEntryView;
textEntryView = layoutinflater.inflate(R.layout.exitdialog, null);
new AlertDialog.Builder(app)
.setView(textEntryView)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setNegativeButton("CANCEL", null)
.show();
while (!checkConnectivity())
{
}
browser.loadUrl(url);
}
If I don't use from while (!checkConnectivity()) to browser.loadUrl(url); then AlertDialog shows properly.
If I don't use from LayoutInflater layoutinflater = LayoutInflater.from(app); to .show(); then the app loads the web page correctly on browser.
But if I use the whole code it looks like it enters the while (!checkConnectivity()) loop before it does the show as what happens when internet connection is restabilished is that the alert dialog is shown briefly and the the web page is loaded.
I find this pretty weird, as I'm not using, as far as I know, threads that could cause that one could be executed before other one, and this is not the case this thing doesn't fulfill one of the most basic things in programming, I mean if an instruction is before another one, the one that's before should be plenty executed logically (except for threads).
Hope someone has an idea about this and can help me.
Your while loop blocks the UI thread and the dialog has no chance to get displayed.
Busy-looping to poll for a condition is also a big red flag.
Consider waiting for a connectivity event, and use a cancellable progress dialog instead of an an alert dialog to disable other UI until the event is received.

Categories

Resources