android Studio "Common part can be extracted from 'if' " - android-studio

In Android Studio I created a code where I declare
int variablename = 1
I later perform if (string.contains("hello")){ variablename = 0 }
and later if ( variablename == 0 ) { ...do stuff.. }
but android studio says : "Common part can be extracted from 'if'"
What does that means ?
is it a problem ?
if yes, how to fix it ?

Usually this warning means that there is duplicate code for different conditions, for example:
if(condition)
{
a=1;
b=3;
}
else
{
c=2;
a=1;
}
If you move a=1 out of the if statement the warning disappears.
If your question really contains all relevant code the warning probably means that 'variablename' is completely unnecessary because you don't really use it and could do everything in the first if statement.

This must be a warning you are receiving from Android Studio that informs you about a change you can make to optimize your code. This specific warning usually indicates that there's an unecessary piece of code which can be removed without affecting the existing functionality, thus achieving better readability.
In general, Android Studio will provide you with a lot of warnings that help you optimize your code and it's good practice to try and resolve them.
When you get a warning on a piece of code it is highlighted in yellow and if you hover with your mouse cursor over it, a solution will be suggested to you. Alternatively, use shortcut "Alt+Enter" if you use Windows OS.

Related

Use of variable stores and or groups seems to be causing a crash

I tried implementing the variable store function to switch groups in a keyboard layout I developed, only for them to fail to implement in real use. To give you an idea, I'll write the gist of it in pseudocode
begin group(main)
group(main)
store(mode) 'off'
if(mode='off') > use(off)
if(mode='on') > use(on)
group(on) using keys
'+ {key} > set(mode='off')
group(off) using keys
{key} > set(mode='on')
Now When I implemented this on my computer after I reset said computer, I found it wouldn't actually use the different group when I actually installed the keyboard. Stranger yet, when I used the save function to save the variable stores, It cause the keyboard and whatever app I was using it in, to crash.
I did a bit of looking and found that my antivirus program (MCafee livesafe) was quarantining the crashpad_handler.exe files in the keyman installation folders. So after getting them back in my system and repairing the installation, I thought that would solve the problem, but it didn't.
Anybody else experiencing this? What did you do to solve it? For reference, everything was working fine before I reset my PC.

Using std::process::Command with windows_subsystem="windows" causes console flash/popup

OK, here is my situation:
I'm making a program with a GUI in rust and I don't want to show the console window to the user.
The easy solution for this is the flag (don't know if that's the actual name for those things) #![windows_subsystem = "windows"]. It works great, the console is gone. Buuut.. The std::process::Command struct is unusable because it flashes a cmd window and not actually runs the command.
So if I have a code like this, I wont be able to use it. (But i need it)
#![windows_subsystem = "windows"]
use std::process::Command;
fn main() {
// GUI stuff that at some point uses the Command like below
Command::new("runas").args(&["/user:MY-COMPANY\\Administrator", "/savecred", path]).spawn().expect("Couldnt start Installer");
}
Does anybody have any idea how I can hide the console window but still be able to use the Command?
An easy workaround for this issue is conhost.
You can use Command::new("conhost").arg("YourCommand")
Came here. Couldn't figure it out either. This is so obscure and nowhere else is there any listed solution. That conhost workaround didn't fix it at all sadly.
Anyways, here's the solution after I finally figured it out.
Import CommandExt on windows from the std library, then set command.creation_flags(CREATE_NO_WINDOW) (you can find the CREATE_NO_WINDOW constant in windows-rs or winapi)
I really don't suggest using the constant manually, but here is the value anyways:
const CREATE_NO_WINDOW: u32 = 134217728u32; (or 0x08000000)
I would like to correct something though
It does actually run the command. It just also flashes the window while doing it. But of course, with the solution above, window flashing is now gone
Here's a list of all of the process creation flags

WARNING: API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'

I want to create a simple AR project, however I get this message when I try to create a .sfb file from .fbx file. This is my first time with AR, and I am not really into Android so much, so I don't really know what to do.
Just change:
string variant.mergeAssets.doLast {
to:
variant.mergeAssetsProvider.get().doLast {
It will work.
you can move to a previous gradle version and it will get fixed.

Why do I keep getting 'Cannot find or open the PDB file' messages in Visual Studio and how to fix?

I have Visual Studio Community 2015.
When I initially ran my code, it would give me numerous errors saying “Module is optimized and the debugger option ‘Just My Code’ is enabled.”
I would receive no output otherwise.
What I tried was:
Clicking ‘Tools - Options -Debugging - General’ then unchecking the box ‘Enable Just My Code’
When I did this and cleaned my solution, then reran it, that error went away, but was replaced by a new error:
“Cannot find or open the PDB file” and at the bottom says “Symbols Loaded”
I do not know why this is occurring or how to fix it.
Here is what I have tried:
Clicking ‘Tools - Options - Debugging - Symbols’ then checking the box for Microsoft Symbol Servers.
Clicking ‘Tools - Options - Debugging - Symbol’” then UNchecking the box for Microsoft Symbol Servers.
Clicking ‘Tools - Options - Debugging - Output Window’ then turning “Module Load Messages” off (**but I did not like this because it seems like it was avoiding the issue, not fixing it. Plus, my program ran, but produced no output.)
Closing program and restarting
Here is my code, for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practice
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter comma separated numbers: ");
var input = Console.ReadLine();
var numbers = input.Split(',');
// Assume the first number is the max
var max = Convert.ToInt32(numbers[0]);
foreach (var str in numbers)
{
var number = Convert.ToInt32(str);
if (number > max)
max = number;
}
Console.WriteLine("Max is " + max);
}
}
}
I don’t know what to do. Please help.
So, while I don't necessarily understand all the details, I did manage to somehow "fix" my problem.
Here is what I did:
Basically, I make sure “Optimize” is unchecked in the Program ‘properties’. (It is unchecked, by default).
Then, in the ‘tools-options-debugging-symbols’ section, I did check “Microsoft Server Symbols.” (I have read the reasons not to, such as the opportunity to reverse engineer your code, but I do not plan on publishing or sending my code anywhere so that shouldn’t be an issue. Plus, IF I ever did, I read about the stripped PDB option and would try that. )
I selected it because my output kept saying “Cannot open or find PDB file.”
It was bugging me to see it and try to ignore it.
And I’m not exactly sure if this made/makes any difference, but I unchecked “Enable Just My Code”…I still don’t know what it really does/affects despite trying to read up on it a bit. (If any one can explain what it does/affects and why I do/don't need to use it, I'd appreciate it!)
Then, I clicked to “Clean Solution” and then clean the program itself before rebuilding and running. This time, it did show my output in the console, and I did see a bunch of messages in the output box, but this time they all said “Symbols Loaded” and I figure that is not a bad message, so I have left well-enough alone for now.
I am posting this just in case anyone else has this issue and might benefit from what I tried.

What is the simplest way to create a UI test in Android Studio that can take screenshots when I need it to?

I am trying to create a UI test in Android Studio which will navigate through the various screens of my application and take screenshots when I tell it to.
I am new to Android Studio and Android programming in general; I have a decent understanding of XML and Java, but I don't know much about build files and I am not very good at using Android Studio, it seems.
I started this endeavor a couple weeks ago, and the first solution I tried was to use uiautomator. However, the documentation on that page (and seemingly just about everywhere else) is geared towards development with Eclipse, which I would like to avoid using for this project if possible.
The next thing I tried was Espresso. After I overcame some issues with implementing Espresso into my project, I was able to write tests with Espresso which would navigate through the screens of my application. However, unlike uiautomator, Espresso does not have built-in functionality to take screenshots at this time.
I first attempted to solve this problem of being unable to take screenshots with Espresso by writing custom code; as I'm still unfamiliar with Android, I wasn't really sure how to go about that, so I searched for help on the Internet (How to programmatically take a screenshot in Android?). However, I was unable to get the solutions I found to function from inside the test file.
Somebody recommended the usage of this tool: https://github.com/rtyley/android-screenshot-lib but I could not figure out how to import that into my project.
I eventually came back to uiautomator; I was still having a lot of trouble importing it into my project, and some people said that Robotium would help with that. I got Robotium to work, but I still could not import uiautomator.
It has been probably one month since I started using Android Studio, and in that time, I've had nothing but trouble simply getting the software to function properly. For the sake of brevity, I've omitted all the problems I have managed to solve on my own, but, to put it bluntly, I'm at the end of my patience.
TL;DR
If somebody could either:
-explain in the simplest possible way how to import uiautomator into an Android Studio project (I have read a lot of documentation about how to import external libraries into a project, but they all tell me to add a 'libs' folder to my project, but do not specify which type of folder to use [Java Resource Folder? Assets Folder? Module? etc.], and/or they tell me to go into Project Structure, select my app, go to dependencies, and choose "Import as Module," which does not work...)
OR
-explain how best to take a screenshot from inside of an Espresso test, including any instructions on how to import any required libraries
OR
-explain in detail some other way to create a UI test that can take screenshots...
...I would really appreciate it. I've spent days trying to figure out how to do this, and I am so frustrated. Many people have asked similar questions, but the answers are either too vague or the problems aren't close enough to my own.
Thanks!
Alright, after much trouble, I've found a very simple solution. It took me a very long time to work out, but if anyone else needs to do something similar, I'll put my conclusion here.
First of all, the testing framework that is easiest to use with Android Studio, it seems, is Espresso. Setting up Espresso is fairly simple; most of the instructions can be found here: https://code.google.com/p/android-test-kit/wiki/EspressoSetupInstructions Make sure you read it carefully -- it tells you basically everything you need to know, but I missed some important details and that caused me a lot of trouble.
If you browse around that Espresso site, it tells you just about everything you need to know about how to write Espresso tests. It was a little frustrating for me because, if I wrote a test and the test failed, my device would then have connection issues with my laptop and I would have to disconnect and reconnect the USB cord I was using. I think this had something to do with the fact that I was using a Nexus 7 with a Windows 8 laptop, which has given me some problems in other areas, so you may not encounter this issue yourself.
Now, unlike uiautomator, the documentation of which claims to have support for taking screenshots, Espresso does not have built-in support for taking screenshots. That means you'll have to figure out a different way to take screenshots. My solution was to create a new class (called HelperClass, in my case) inside my androidTest package and add this method to it.
public static void takeScreenshot(String name, Activity activity)
{
//slightly modified version of solution from http://www.ssaurel.com/blog/how-to-programmatically-take-a-screenshot-in-android/
//I added "/Pictures/" to my path because that's the folder where I wanted to store my screenshots -- you might not have that folder on your device, so you might want to replace "/Pictures/" with just "/" until you decide where you want to store the screenshots
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/" + name;
View v = activity.getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
//the following line will help you find where the screen will be stored on your device
Log.v("Screenshot", "The image file path is " + imageFile.getPath());
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
}
In order for this function to work, you will also have to add the following line to your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Without that, the function above will throw a FileNotFoundException every time you run it.
Finally, to call the takeScreenshot function from inside your Espresso test code, use this line (assuming you called your class HelperClass... if not, use the name of your class instead.
HelperClass.takeScreenshot("Whatever you want to call the file", getActivity());
Finding where your screenshots are stored can be a little difficult if you don't know where to look. I added a line of code to the takeScreenshot function that would print the filepath to LogCat, but I was using the file explorer on my computer to look for the screenshots on my Nexus (which was, of course, connected to the computer), and I couldn't find that path. However, I got a file explorer application on my tablet which made it very easy to find where the files were located in relation to everything else.
My solution may not be the simplest and it certainly isn't the best -- you'll fill your device up with screenshots before long if you aren't careful to delete the ones you don't need anymore, and I haven't got any idea how one would go about saving the screenshots directly to, say, a computer connected to the tablet via USB. That would certainly be helpful. However, if you really need a simple UI test that takes screenshots, and you're frustrated to no end like I was, this solution should probably help. I certainly found it useful.
I hope this helps somebody else -- it definitely solved my problems, at least for now.
Of course if you don't have all the restrictions that I did when I had to write a UI test that took screenshots, the other posts in this thread probably work much better.
You should give AndroidViewClient/culebra a try. Using culebra GUI, you can automatically generate a test case that interacts with your app and takes screenshot exactly when you indicate so.

Resources