Android executing both IF and ELSE statement together - android

I am working with FireBase Notifications and I can send a notification which will send the user to the webview page I input on the console.
The problem is that when it matches the IF statement is fires the else statement too, what could be the cause of this?
if(getIntent().getExtras()!=null) {
for (String key : getIntent().getExtras().keySet()) {
if (key.equals("url")){
mwebView.loadUrl("http://example.com/" + getIntent().getExtras().getString(key));
}else {
mwebView.loadUrl("http://example.com");
}
}
}
Because it executes both at the same time the app crashes.
Also when I load the app the usual way it matches the with:
if(getIntent().getExtras()!=null)
and then loads the else statement. Shouldnt getExtras be null?
When I first install a new instance of the app it uses the following statement:
if(getIntent().getExtras()==null) {
if (haveNetworkConnection()) {
mwebView.loadUrl("http://example.com");
} else {
mwebView.loadUrl("file:///android_asset/myerrorpage.html");
}
}
Update:
As I cannot find out why this it happening I am trying another approach, How would I get the variable outside of the loop to use like the following:
if(getIntent().getExtras()!=null) {
for (String key : getIntent().getExtras().keySet()) {
String valuex = getIntent().getExtras().getString(key);
}
}
if (haveNetworkConnection()) {
mwebView.loadUrl("http://example.com/" + valuex);
} else {
mwebView.loadUrl("file:///android_asset/myerrorpage.html");
}

If and Else can not both be executed in one go.
You should check your other code and ensure, that this code section is not executed twice for some reason (once with TRUE and once with FALSE).

Related

Is there a way to bring the current app that is running code to the foreground Xamarin Forms - Android

I have created a custom document provider for Android using this code as a base.
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/storageprovider/
This allows for a new drive to be mapped onto the documents folder when browsing/saving documents.
If there is an exception due to a password timeout for example, I would like to pop back up the existing app so the users can entered their credentials again to log in.
Is this possible? As an example of what I am looking for, if the QueryRoots failed with a particular exception, could I run something to pop back up the app interface here?
public override ICursor QueryRoots(string[] projection)
{
Log.Verbose(TAG, "queryRoots");
var result = new MatrixCursor(ResolveRootProjection(projection));
try
{
if (!IsUserLoggedIn())
{
return result;
}
MatrixCursor.RowBuilder row = result.NewRow();
... other init code here
}
catch (Exception ex)
{
if (ex.Message == "NoSessionException")
{
// LOGIC TO BRING BACK APP TO LOG IN AGAIN HERE...
}
}
return result;
}
I make a sample code about how to lauch the app again for your reference. You could put Launch method in catch statement.
In Xamarin.Forms, you could use Dependency service to start the app with package name.
Create a interface:
public interface IDpendencyService
{
Task<bool> Launch(string stringUri);
}
Implemention of Android:
public class DependencyImplementation : Activity, IDpendencyService
{
public Task<bool> Launch(string stringUri)
{
Intent intent = Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage(stringUri);
if (intent != null)
{
intent.AddFlags(ActivityFlags.NewTask);
Forms.Context.StartActivity(intent);
return Task.FromResult(true);
}
else
{
return Task.FromResult(true);
}
}
}
Register in MainActivity:
DependencyService.Register<IDpendencyService, DependencyImplementation>();
I use a Button event to invoke. You could try to invoke in catch.
DependencyService.Get<IDpendencyService>().Launch("com.companyname.xamarindemo");
Screenshot: I have a button on Page21. When i click the button, it would reload the app and pop back up the existing app.

How to Stop App on Package Name change?

I need to implement a function where if the Package name of the App is changed, the App will stop i.e. this.finish();
But it isn't working, here is the code I am Using -
public void chk(){
String ucci = getApplicationContext().getPackageName();
if (ucci!=("my.package.name"))
{
//do nothing
}
else {
this.finish();
Toast.makeText(this, "Name Changed", Toast.LENGTH_LONG)
.show();
}
}
& then I use it in onCreate like this.chk(); but doesn't work
Logically if package name is equal to "my.package.name" then finish() called otherwise nothing happen.
Please use !ucci.equals("my.package.name") instead of !=.
== and != work on object identity. While the two Strings have the same value, they are actually two different objects.

Parse findAllInBackground & fetchAllInBackground

i'm having an issue that soon enough going to blow me.
i have Database table lets call it A. table A has field that determines if this row is processed or no. i update the field myself from within the Parse Browser to either True | False, and trying to call query.findInBackground() to check with the Boolean value however the returned List always returns False if its True and vice versa. enough talking let me show you what i'm doing.
public static void getMyRequests(ParseUser user, final FindCallback<ServicesModel> callback) {
ParseQuery<ServicesModel> query = new ParseQuery<>(ServicesModel.class);
if (!user.getBoolean(ParseHelper.CAN_UPLOAD)) {
query.whereEqualTo("user", user);
}
query.findInBackground(new FindCallback<ServicesModel>() {
#Override public void done(final List<ServicesModel> objects, ParseException e) {
if (e == null) {
if (objects != null && !objects.isEmpty()) {
for (ServicesModel object : objects) {
object.setHandlerUser(object.getParseUser("handlerUser"));
object.setProcessedTime(object.getLong("processedTime"));
object.setCategoryType(object.getString("categoryType"));
object.setUser(object.getParseUser("user"));
object.setUserRequest(object.getString("userRequest"));
object.setImageUrl(object.getString("imageUrl"));
object.setProcessed(object.getBoolean("isProcessed"));
Logger.e(object.getBoolean("isProcessed") + "");
}
callback.done(objects, null);
} else {
callback.done(null, new ParseException(1001, "No Services"));
}
} else {
callback.done(null, e);
}
}
});
}
the code above suppose to refresh my data but however my log always shows that isProcessed is False even tho it's set to True inside the Parse Browser
what i have tried besides this? fetchAllInBackground & fetch() you name it. the object will always return false until i re-run the application from Android Studio what i'm doing here wrong? btw here is how i initialize Parse
Parse.setLogLevel(BuildConfig.DEBUG ? DEBUG_LEVEL : Parse.LOG_LEVEL_NONE);
ParseObject.registerSubclass(ProductsModel.class);
ParseObject.registerSubclass(ProductRentalModel.class);
ParseObject.registerSubclass(ServicesModel.class);
Parse.enableLocalDatastore(context);
Parse.initialize(context, context.getString(R.string.app_id), context.getString(R.string.client_id));
the answer was to remove
Parse.enableLocalDatastore(context);
which is bad anyway, without the datastore enabled the data are refreshed probably, however with enabling the local database, the data will not refresh unless if i killed the app and/or re-install it. that's bad. but did the trick.

"If-else" statement going down the wrong section in step debug

Hopefully a simple answer but I'm a little baffled. I'm expecting the code to go down the first if section below, but it always goes to the else.
When I get to line on a breakpoint >> if (url2!=null && !url2.isEmpty())
In the expressions window:
url2 IS "???/wp-content/uploads/2011/01/toonieJune10_091-640x334.jpg"
url2!=null IS true
!url2.isEmpty() IS true
However when debugging it always seems to hit the else, even though both conditions are true. I'm suspecting something is out of sync with my built code somehow as the step through debugging seems to give me inconsistencies.
I've tried cleaning the code and making some changes in the class and recompiling etc.
Help is much appreciated! Thanks!
public String getImageBannerUrl()
{
if (getPhotoFile1()!=null) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if (url2!=null && !url2.isEmpty())
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Try somthing like..
public String getImageBannerUrl()
{
if ((!getPhotoFile1().isEmpty()) && (!getPhotoFile1().matches(" "))) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if ((!url2.isEmpty()) && (!url2.matches(" ")))
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Note : here getPhotoFile1() must be returning String value..

How to distinguish an Importand Application from a non Importand one when both are in background

I hope that this question will not have the same luck with this one.
I want to give my users the ability to close some applications which are in the background via a list. By applications in the background I mean applications that the user started and then press the home button, for example Internet Browser. I have managed to find the background applications via the ActivityManager (both getRunningAppProcesses and getRunningTasks will do the job). However there are some applications in the background which are important for the system to work (i.e. Phone, Launcher, Input Methods etc) and I don't want them in my list.
My question is: How can I distinguish them from the non Important ones. I don't want to use some kind of String checking / filtering (like contains(com.android) etc) because I want to exclude some Important 3rd party apps like non stock Launchers, Dialer, Messaging etc.
Everyone who owns a Galaxy S2 and have used the "Program Monitor Widget" will know what i mean.
Thank you very much for your time and efforts...
Well I finally came up with a function that checks if a running task may considered as an "Important" one. First of all we have to use the getRunningTasks function from the ActivityManager to get a list filled with ActivityManager.RunningTaskInfo objects and then we pass each of these objects to the following function to do the check. Hope this helps someone...
public boolean isRunningTaskImportant(ActivityManager.RunningTaskInfo taskinfo) {
//What makes a running task important is somehow "fluid" but there are a few task categories
//on which is safe to assume that they are important. These categories are:
//1. If task has not any actual activities running. This is because these are not actuall running but they are frozen by the
// the system and they will be killed if needed. They are not Important but we do not want them in our running apps list.
//2. Well known namespaces including our own if we want to
//3. Home Launcher Applications
//4. Phone Handling Applications
boolean result = false;
ComponentName bActivity = taskinfo.baseActivity;
if (bActivity == null) return false; //<-- The task has no base activity so we ignore it...
String pName = bActivity.getPackageName();
if (taskinfo.numRunning == 0) {
result = true;
} else {
if (pName.equalsIgnoreCase("com.android.phone")) {
result = true;
} else if (pName.equalsIgnoreCase("com.android.contacts")) {
result = true;
} else if (pName.equalsIgnoreCase("com.chdcomputers.powerpanel")) {
result = true;
} else {
//Here we are checking if out task is a home launcher application.
//This code is based on this question: http://stackoverflow.com/questions/3293253/getting-list-of-installed-apps-easy-but-how-to-launch-one-of-them
Log.d(TAG, "isRunningTaskImportant checking for launchers");
Intent launchersIntent = new Intent(Intent.ACTION_MAIN, null);
launchersIntent.addCategory(Intent.CATEGORY_HOME);
List<ResolveInfo> list = cx.getPackageManager().queryIntentActivities(launchersIntent,0);
boolean found = false;
for (ResolveInfo ri : list){
if (!found){
Log.d(TAG, "isRunningTaskImportant checking launcher app: " + ri.activityInfo.applicationInfo.packageName);
found = pName.equalsIgnoreCase(ri.activityInfo.applicationInfo.packageName);
}
if (found) break;
}
result = found;
if (!found) {
//Finaly we are going to check if out task is a Phone Handling application
//The idea behind that is to check for what kind of permissions the application wants
//In my opinion any "serious" phone handling app should ask for, at least, the following 9 permissions:
//CALL_PHONE, CALL_PRIVILEGED, READ_CONTACTS, WRITE_CONTACTS, SYSTEM_ALERT_WINDOW, READ_PHONE_STATE,
//MODIFY_PHONE_STATE, PROCESS_OUTGOING_CALLS, RECEIVE_BOOT_COMPLETED
//So if the application asks for those permissions we can assume that is a phone handling application...
Log.d(TAG, "isRunningTaskImportant checking possible phone app: " + pName);
try {
PackageInfo pi = cx.getPackageManager().getPackageInfo(pName,PackageManager.GET_PERMISSIONS);
String[] perms = pi.requestedPermissions;
if (perms == null) {
result = false;
} else {
int pCount = 0;
for (String perm : perms) {
if (perm.equalsIgnoreCase("android.permission.CALL_PHONE")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.CALL_PRIVILEGED")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.READ_CONTACTS")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.WRITE_CONTACTS")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.SYSTEM_ALERT_WINDOW")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.READ_PHONE_STATE")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.MODIFY_PHONE_STATE")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.PROCESS_OUTGOING_CALLS")) {
pCount++;
} else if (perm.equalsIgnoreCase("android.permission.RECEIVE_BOOT_COMPLETED")) {
pCount++;
}
}
result = (pCount == 9);
}
} catch (Exception ex) {
Log.e(TAG, "isRunningTaskImportant checking possible phone app ERROR: " + ex.getMessage());
result = false;
}
}
}
}
return result;
}

Categories

Resources