Of course I know there are yellow warnings that they are important. For example if we use the following code we will get a yellow warning, because we did not use the show() method.
Toast.makeText(getApplication(),"Warning",Toast.LENGTH_SHORT);
But also there are yellow warnings that I do not know they are important or not. For example if I create a button in visual Editor in the android studio, the android studio says to me that I should use the String resources for naming the button.
If I do not use the string resources for naming the button does it make disruption in the program?
The second case:
When I want to use the try{} catch{} in my code and if I do not use a code in the block of the catch, as the result the android studio says to me that the block of the catch is empty. Is filling the block of the catch really important?
For the first part of the question: it does not disrupt your program. Hold your mousecursor on the yellow line for approx. a second and a pop-up appears with the explanation. From the top of my head, I think Android Studio warns you, as you are hard coding text that will be shown to the user. When you use string resources instead, it is really easy to translate the displayed text.
You can read more about String resources here: http://developer.android.com/guide/topics/resources/string-resource.html
For the second part, it sounds like you need to work on your programming skills (not to be rude, but I consider that as one of the basic things in programming land). You wrap code in a try/catch block, as you expect that your code inside the try block might throw an exception. So, if your program ends up in a catch block, you probably want to let the user know in some way, or at least log something, so you know what is going wrong. Read more about catch blocks here: http://developer.android.com/guide/topics/resources/string-resource.html.
Related
I'm repairing my friend's code and got confused.
My friend wants to fetch entered text (in EditText). Seems easy, right? Well, it is but instead of user input, he gets this warning/error:
To be honest I'm not sure how to fix it. He is coding in Kotlin (Android 10).
Activity that contains EditText:
And XML:
This is how it looks when debugging:
The app started working just fine after running "File -> invalidate Cashes/Restart" option, I just don't understand where this warning came from and how to fix it because the error remained unchanged (even though the app works). Do you have an idea how to solve it?
All the best!
fyi lambda expression like setOnClickListener from kotlin is not debuggable, see here.
if you want to debug variables inside setOnClickListener you should use the normal one e.g. setOnClickListener(object: View.OnClickListener {..})
sometimes there will be problem in auto generated binding files, if so it will be solved after invalidate cache and restart ide. sometimes the warning/error show but the project and complied without errors. so no need to worry about that. for next time post the code as code not screen shots.
I understand that the question is regarding evaluating expression, but there is a way you can read variables from your debugger console, even if you're inside an anonymous callback. I found it helpful sometimes. Here are the steps:
First enter debugger mode inside of your anonymous callback,
In your debugger console, look at the right side for "Frames"
Within Frames under , you'll see stack of function execution first top one on the list is the latest:
Click on row(s) below the latest function, until you find an instance of your activity AddInformationActivity. You will see the activity instance on the right side window under Variables. Don't go as far as selecting functions browned out, because those are from internal libraries.
When you see you AddInformationActivity instance, you can expand it and see its variables.
Hope that helps!
It's not a beautiful way, but if you create a method like this:
private fun debug() {
println()
}
and add a breakpoint on the println() it'll capture the activity.
(Don't use TODO as it'll crash the app with a NotImplementedError once called.)
I have this method now in my code all the time to call it whenever I need it.
I know, that question is old, but I just stumbled over it and needed a way.
I am new to android development. In the overriden onCreate() method of my activity, I perform some operations. For ex. check if SharedPreference is already available and then route to other activity. How do I perform exception handling on this onCreate() method. Is it the right way to wrap the contents in a try catch and display the error dialog on exception?
If the exceptions are not handled properly, in my case the onCreate() method, the app crashes with message:
Unfortunately your application stopped working
On searching in the internet, I found that UncaughtExceptionHandler could be used to handle it. Any sample implementation and how to call it from all my activities would be helpful.
THat's the wrong way to go about it. Instead, go into your logcat. Read the stack trace of the exception. Figure out what you did wrong. Fix it. Just catching exceptions is a horrible practice unless you're catching a specific exception for a specific reason- its very unlikely your app is in a state where it can continue correctly. Don't be lazy, track down your bug and fix it.
With something like this you can catch a generic Exception in your onCreate() method:
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
try {
// do whatever you need
} catch (Exception e) {
e.printStackTrace();
}
}
Exception catching can be used with many goals. An interesting one is to catch particular expected exceptions to fix some problems (for example setting a generic value into a variable otherwise null after occurring an error).
The general purpose however is to avoid that an error causes a problem or in the worst case a crash of your application. Depending oh what kind of software you are developing, a crash may represents a little problem (like in an Android app), a very big one (like in airplane's softwares or power plants' softwares).
We can identify two kind of exceptions.
The first type are those exceptions specific to definite problems. They have to be declared into methods signature, so you are encouraged or obbligated to manage these exceptions and their relative problems. These exceptions represent an error that should probably occur during particular code execution, like a parsing error, or an input output error. For this type of problems we have particular exceptions, to catch and easily manage them (for example as previously said to init a variable with a default value after an error).
The second type of those exception represents instead some generic problems that can occur during program execution. They are a big and generic set and generally their probability of occurring is low. For this reason you are not obbligated to manage them. The main example of this type is the general Exception class.
So an catching an Exception is not the right approach to solve a bug, as suggested by Gabe Sechan.
Catching a generic Exception in the main() Java method can be a way, for example, to show a default human readable error to the user if nothing else is available.
Or could be a way to keep the failing of the current operation reducing crash probability.
Now, in Android we can't act directly on the main() method. onCreate() method is executed and exited so catching here a generic Exception has no much sense. Obviously it depends also on what you do in your onCreate() method and what you want to do if an error occurs. You could do some strange stuff (is very defined what you should do in the onCreate() method) and you could need to manage a big set of problems only showing an error, so it has more sense catch only a generic Exception than a lot of particular exceptions to make the same thing in each catch block.
If you want to achieve this goal (a message showed for all the errors occurred during onCreate() execution, made Activity by Activity) this is the right approach.
If instead what you want to achieve is to intercept all of the errors that are generated during all of your app execution, a good approach could be the UncaughtExceptionHandler, that act similarly to catch a generic Excepetion into a Java main() method. At this level an interesting approach is described here.
For more infos about exceptions you can read this and this.
I'm working currently on an android project and I have no plans in mind whatsoever to translate it to other languages, so I'm not saving string literals in strings.xml. However Android Studio keeps complaining everytime I hard code a string literal especially when setting the text value for a TextView.
Is there a way to disable these warnings?
you can edit it in the following location Settings->Editor->Inspections->Android Lint->TextView Internationalization:
and for the xml Settings->Editor->Inspections->Android Lint->Hardcoded Text:
The best way to do this in my opinion is to use a gradle file, this will allow you to suppress these globally without having to do it in Android Studio, so your settings can go into source control as well, and then you don't have to individually decorate each method you want to apply the warning to. To do this, disable SetTextI18n in your gradle files lint options as follows:
android {
lintOptions{
disable 'SetTextI18n'
}
}
Gradle sync and voila, warnings gone.
Add
#SuppressLint("SetTextI18n")
on top of your function(s).
Example:
#SuppressLint("SetTextI18n")
private void updateEZWBMode2ConnectionStatus(){
switch (IsConnected.checkMode2(mContext)){
case IsConnected.USB_TETHERING:
M2StatusTV.setText("Status: Connected");
M2StatusTV.setTextColor(Color.argb(255,0,255,0));
M2ReceiveTV.setVisibility(View.VISIBLE);
startTestReceiverSafe(M2ReceiveTV);
break;
case IsConnected.USB_CONNECTED:
M2StatusTV.setText("Status: No Tethering");
M2StatusTV.setTextColor(Color.argb(255,255,51,51));
M1ReceiveTV.setVisibility(View.GONE);
M2ReceiveTV.setVisibility(View.GONE);
stopTestReceiverSafe();
break;
case IsConnected.USB_NOTHING:
M2StatusTV.setText("Status: No USB Connection");
M2StatusTV.setTextColor(Color.argb(255,255,51,51));
M1ReceiveTV.setVisibility(View.GONE);
M2ReceiveTV.setVisibility(View.GONE);
stopTestReceiverSafe();
break;
}
}
Old question, but anyway the accepted answer is misleading.
There is no need to translate string literal resources. In fact, they can be marked as non-translatable in the resources file. This way, you'll still adhere to best practices while not being annoyed by lint and translations.
<string name="invite_sent" translatable="false">Invite sent</string>
While disabling Lint my be useful to stop being annoyed, there is a further reason you want to (and should) use string literal resources: repetition. Following the DRY (Don't Repeat Yourself) principle can avoid a miriad of problems down the line, from complex refactors to unexpected behaviour, as well as inconsistency in the user(s) experience while using the app. Just imagine that an "Ok" button is present in 10+ screens. Having a single reference and source simplifies and centralizes maintenance of the project.
I've been working on the 'Tip Calculator' app for Android and I have a couple of questions.
I'm supposed to (in the process of creating the GUI) use some EditTexts to allow the user to enter the bill amount and read the calculated total bill. In the version I have, there is no EditText anywhere in the Visual Layout Editor, only CheckText. Are these the same?
Whenever I try to edit the Java code for the app, as per the book I have, I keep getting the message:
Thus and such is never used
For example, with
private static final String BILL_TOTAL = "BILL_TOTAL';
or anything from the import Android list, other than the one referring to a bundle. I'm Not sure how to resolve this. I have some experience with C and C++, but Java is new to me.
The warning that tells you that a variable or method or import is not used can be ignored, especially if you just haven't gotten to using it yet. It's a warning and not an error, so your app should compile regardless.
I don't know what you're using to build your layout (eclipse? I use Intellij Idea), but to add an EditText, you can edit the layout file by hand. Add a line similar to:
<EditText android:id="#+id/myEditText android:width="FILL_PARENT" android:height="WRAP_CONTENT"/>
As a general rule, I like to edit these things by hand. Then, when something breaks or doesn't work as I expect it to, I have some grasp of what's in there, and so I can usually fix it. The value gained by learning how to create a layout by hand easily offsets the value of the time that you'll save.
Good luck.
I want to know is there any method or any link or tutorial to perform redo undo operation in Android edittext. If any one knows than please let me know.
Quick note on the Antti-Brax/Divers(Kidinov) solution. It works great, except if you try to use it with a TextView post-API 23, you'll run into problems, because guess-what, Google actually added a hidden UndoManager (android.content.UndoManager) and didn't document it or make it obvious it was there. But if you have a hard/bluetooth keyboard in Marshmallow or Nougat and hit ^Z or SHIFT-^Z, you'll get undo/redo.
The problem comes if you're already using Antti-Brax's class with an EditText, and you also hook it to ^Z and shift-^Z, you'll run into problems with anyone using a hard keyboard. Namely the ^Z will trigger BOTH the native and Antti-Brax's undo, leading to two undos simultaneously, which isn't good. And after a few of them, you'll probably get a Spannable out of bounds crash.
A possible solution I found is to subclass the TextView/TextEdit/whatever and intercept the undo/redo calls from the TextView so they don't run as follows:
#Override
public boolean onTextContextMenuItem(int id) {
int ID_UNDO, ID_REDO;
try {
ID_UNDO = android.R.id.undo;
ID_REDO = android.R.id.redo;
} catch (Resources.NotFoundException e) {
ID_UNDO = 16908338; // 0x1020032
ID_REDO = 16908339; // 0x1020033
}
return !((id == ID_UNDO) || (id == ID_REDO)) && super.onTextContextMenuItem(id);
}
Those magic id numbers were found here, and are used only as a backup if the android.R.id.undo values aren't found. (it also might be reasonable to assume that if the values aren't there the feature isn't there, but anyway...)
This is not the best solution because both undo trackers are still there and both are running in the background. But at least you won't trigger both of them simultaneously with ^Z. It's the best I could think to do until this gets officially documented and the getUndoManager() methods of TextView is no longer hidden...
Why they made a feature you can't turn off (or even know if it was there or not) "live" in released Android I can't say.
I just opened an issue on Android's issue tracker if anyone wants to follow this.
There is an implementation of undo/redo for Android EditText in
http://credentiality-android-scripting.googlecode.com/hg/android/ScriptingLayerForAndroid/src/com/googlecode/android_scripting/activity/ScriptEditor.java
The code works but does not handle configuration changes properly. I am working on a fix and will post here when it is complete.
My Google search was :-
android edittext onTextChanged undo
I know this is an old question, but as there is no accepted answer, and this is an issue I've tackled myself from many angles, I'd like to add my solution in case it helps anyone. My answer is probably most relevant to large (1,000words+) volumes of text editing apps that require this feature.
The simplest way to resolve this problem is to make periodic copies of all text on screen, save it to an array and call setText() every time the Undo method is called. This makes for a reliable system, but it isn't ideal for large (i.e. 1,000words+) text editing apps. This is because it:
Is wasteful. It could be that only one word changes in a two thousand word document, so that's one thousand, nine hundred and ninety nine words needlessly committed to memory.
Can lead to performance issues, as some low-tier hardware struggles with rendering large amounts of text. On some of my test devices, this method can lead to freezes of a few seconds whenever Undo is called.
The solution I currently use is comparatively complex, but I've published the results in a library here.
Essentially, this library saves a copy of text as soon as a user begins typing, and then another copy of text once they've stopped typing for a set amount of time (in my case, two seconds). The two text strings are then compared, and the altered section of text returned, the indexes where the alterations occured, and details on whether or not the change was an addition of new text, a deletion, or a replacement of old text with new text.
The net result is that only the necessary text is saved, and when Undo is called, there is only a local delete(), replace() or insert() call, which makes for much faster operations on large text fields.
Here is the undo/redo implementation that was linked to from Gary Phillips' answer extracted into a reusable and universal undo/redo plugin for any widget that descends from a TextView. I added some code for persisting the undo history.
http://code.google.com/p/android/issues/detail?id=6458#c123
Hope this helps.
To preserve EditText Styling with regards to undo:
You can create an ArrayList<EditText> or ArrayList<String> (String containing html text) to store your last 10 (for example) actions. So ArrayList [0] would contain html text from your first action and ArrayList [9] would contain html text from your very last action. Each time the user taps "undo" in your app, you would apply ArrayList [size()-1] to your EditText and then remove ArrayList [size()-1] from your Array.