My keystore is corrupt, therefore the Android Market is requiring me to rename the app and resubmit it. However, whenever I go to edit the package names in Manifest and throughout the files, it gives me tons of errors.
What's the proper way to change the application name?
There is a way to change the package name easily in Eclipse. Right click on your project, scroll down to Android Tools, and then click on Rename Application Package.
If you're using Eclipse, you could try these instructions from Android's developer site. They're specifically for the GestureBuilder sample but should apply to any application as far as I can tell:
[H]ere's how you could do this in Eclipse:
Right-click on the package name (src/com.android.gesture.builder).
Select Refactor > Rename and change the name, for example to
com.android.gestureNEW.builder.
Open the manifest file. Inside the
<manifest> tag, change the package name to
com.android.gestureNEW.builder.
Open each of the two Activity files
and do Ctrl-Shift-O to add missing import packages, then save each
file. Run the GestureBuilder application on the emulator.
Also, be sure you remembered to rename the package itself along with the references to it in the files. In Eclipse you can see the name of the package in the file explorer window/tree view on the left hand side. In my experience, Eclipse can sometimes be a little finnicky and unreliable with this (leaving behind stray references to the old package name, for example).
Here's how you could do this in Eclipse:
Right-click on the package name (src/com.android.gesture.builder).
Select Refactor > Rename and change the name, for example to
com.android.gestureNEW.builder.
Open the manifest file. Inside the <manifest> tag, change the package name to com.android.gestureNEW.builder.
Open each of the two Activity files and do Ctrl+Shift+O to add missing import packages, then save each file.
Run the GestureBuilder application on the emulator.
Link to post
Update
super easy way
right click on your project...
In Android Studio, which, quite honestly, you should be using, change the package name by right-clicking on the package name in the project structure -> Refactor -> Rename...
It then gives the option of renaming the directory or the package. Select the package. The directory should follow suit. Type in your new package name, and click Refactor. It will change all the imports and remove redundant imports for you. You can even have it fix it for you in comments and strings, etc.
Lastly, change the package name accordingly in your AndroidManifest.xml towards the top. Otherwise you will get errors everywhere complaining about R.whatever.
Another very useful solution
First create a new package with the desired nameby right clicking on thejava folder -> new -> package.`
Then, select and drag all your classes to the new package.
AndroidStudio will re-factor the package name everywhere.
After that: in your app's build.gradle add/edit applicationId with the new one. i.e. (com.a.bc in my case):
defaultConfig {
applicationId "com.a.bc"
minSdkVersion 13
targetSdkVersion 19
}
Original post and more comments here
Without Eclipse:
Change package name and Activity names in AndroidManifext.xml and anywhere else it shows up in .xml files (custom view names, etc)
Update package import statement across all source files
Rename all folders to match the package name. Folder locations:
a. bin/classes
b. gen
c. src
Update the project name in build.xml (or your apk's name won't change)
Delete all the .class files in bin/classes/com/example/myapp/ (if you skip this step the files don't get rewritten during build and dex give a bunch of trouble processing "class name does not match path" errors
Delete gen/com/example/myapp/BuildConfig.java (I don't know why deleting BuildConfig.class in step 3a didn't cause dex to update it's path to this, but until I deleted BuildConfig.java it kept recreating gen/com/oldapp_example/oldapp and putting BuildConfig.class in there. I don't know why R.java from the same location doesn't have this problem. I suspect BuildConfig.java is auto-generated in pre-compile but R.java is not)
The above 6 steps are what I did to get my package name changed and get a successful* build. There may be a better way to handle steps 5 and 6 via dex commands to update paths, or perhaps by editing classes.dex.d in the root directory of the project. I'm not familiar with dex or if it's ok to delete/edit classes.dex.d so I went with the method of deleting .class files that I know will be regenerated in the build. I then checked classes.dex.d to see what still needed to be updated.
*No errors or warnings left in my build EXCEPT dex and apkbuilder both state "Found Deleted Target File" with no specifics about what that file is. Not sure if this shows up in every build, if it was there before I messed with my package name, or if it's a result of my deletions and I'm missing a step.
Follow these steps:-
Right click on the project.
Go to Android tools.
Click on Rename Application Package.
Change the application package name.
DONE
The fastest way to do that in Android Studio 1.3:
Change the package name in the manifest
Go to Module Settings[F4]-> Flavors, into Application Id write the same name.
Create new package with that name: [right-click-> new-> package]
Select all java files of your project and then proceed [Right-click-> Refactor-> Move-> {Select package}-> Refactor]
P.S. If you will not follow this order you can end up changing all the java files one by one with new imports and a bunch of compile time errors, so the order is very important.
Changing package name is a pain in the ass. It looks like different methods work for different people. My solution is quick and error free. Looks like no cleaning or resetting eclipse is needed.
Right click on the package name then Refractor > Rename.
Right click on the project name Android tools > Rename Application Package.
Manually set the package names in the Manifest that have not been changed by the previous steps.
Bernstein has the method, use the Eclipse tool, "Rename Application Package", you may have to do some clean-up even after the fact.
Also, Eclipse sometimes loses track of things when you make changes to a project. You may have to use the "Clean Project" tool (under the "Project" menu.) If that doesn't work, you may have to close and restart Eclipse. Voo-doo solutions, but Eclipse can be that way.
I found the easiest solution was to use Regexxer to replace "com.package.name" with "com.newpackage.name", then rename the directories properly. Super easy, super fast.
Fist change the package name in the manifest file
Re-factor > Rename the name of the package in src folder and put a tick for rename subpackages
That is all you are done.
There is also another solution for users without Eclipse, simply change the package attribute in <manifest> tag in AndroidManifest.xml, by replacing the the old package name used with a new one. Note: You have to adjust the all the related import statements and related folders manually in your project than, too.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="new.package.name"
.....
</manifest>
In Android Studio 1.2.2
Say if you want to change com.example.myapp to org.mydomain.mynewapp
You can follow the steps in each of the directories as displayed in the below screen shot. It will give you the preview option so that you can preview before making any changes.
Go to Refactor -> Rename and give your new name. You have to do it for each of the folders, say for com, example and myapp. It will automatically update the imports so that you don't have to worry about it.
Also update the file build.gradle which is not updated automatically.
defaultConfig {
applicationId "org.mydomain.mynewapp" //update the new package name here
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
After that it will ask for sync do it. Then everything will be fine. I'm able to upload my APK to google store after this. Make sure you have signed your app to upload it to the store.
Alternative:
Open AndroidManifest.xml
Change package="NEW NAME" within manifest tag.
Right Click on Project >Android Tools >Rename Application Package
Go to src and right click on your main package >Refactor >Rename
Go to manifest file and change your package name .
I just lost few hours trying all solutions. I was sure, problem is in my code - apk starting but some errors when working with different classes and activities.
Only way working with my project:
rename it - file/rename and check all checkboxes
check for non renamed places, I had in one of layout old name still in tools:context="..
create new workspace
import project into new workspace
For me it works, only solution.
So, using IntelliJ with Android (Studio) plugin was: I went to AndroidManifest.xml on top and changed package name by right-clicking -> Refactor -> rename.
Our then package name had four parts a.b.c.d, the new one only a.b.c.
So I renamed the first three. Then I went to the directory of generated sources (app\build\generated\source\r\development\debug\a\b\c\d), right-clicked R class and Refactor->Move[d] it to one package higher. Same with BuildConfig in app\build\generated\source\buildConfig\development\debug\a\b\c\d.
By using Refactor->Move, IntelliJ updates all references to BuildConfig and R.
Finally I updated all applicationId[s] I found in gradle.build I found. I hit Clean Project, Make and Rebuild Project. Deleted the app from my phone and hit "Play". It all worked out so refactoring was easy and quite fast.
In your Android studio , at project panel , there is gear icon "Click on it".
Uncheck the Compact Empty Middle Packages
Now the package directory has been broken up i.e individual directories.
Select the directory you want to rename.
Right click on that particular directory.
Select refactor and then rename option.
The dialog box has been open up,rename it.
After putting new name, click on Refactor.
Then click on Do Refactor at bottom.
Then android studio will update all changes.
Now open build.gradle file and update the applicationId & sync it.
Now go to manifest file and rename the package.
Rebuild your Project.
You are done :)
If you are looking for a quick and safe solution to change the package name, then I suggest you use the plugin "Android Package Renamer", It is available on Android Studio Market.
What you need to do is
enter "Your package name you want to change"
Click OK.
You can see the detailed answer here
Related
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
In every instance in all of my classes where I reference R.id.something, the R is in red and it says "cannot resolve symbol R". Also every time there is R.layout.something it is underlined in red and says "cannot resolve method setContentView(?)". The project always builds fine. It is annoying to see this all the time. I have read many other questions on here about something similar but most involved importing projects from Eclipse. I am using what I believe to be the most recent version of Android Studio and the project was created with Android Studio and worked without any "cannot resolve R" problems. I would like to know what causes this if anyone knows.
I had this this issue too. A simple 'gradlew clean' and 'gradlew build' did the trick.
Click on Build->Clean Project and that will perform a gradle clean
In the latest versions of Android Studio, at least for me, the following works:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
In latest Android Studio 3.1.3 (July 2018), "Sync Project with Gradle Files" is available in main menu bar.
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
classpath 'com.android.tools.build:gradle:3.2.1'
Problem resolved after changing the gradle version. Details history can be found here.
I have a similar problem and here is what I did:
Clean Project and Sync Project with Gradle ,
check buildTools version in my sdk
From build gradle (module ) change minSdkVersion from 8 to 9
defaultConfig {
applicationId "PackageName"
minSdkVersion 9
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
But all this didn't help.
Finally I found the answer (this worked in my case)
Change from build.gradle(module:app)
android {
compileSdkVersion 21
buildToolsVersion '21.0.1'
......
....
}
Or
Select File | Project Structure change Build Tools Version to 21.1.1
Check your xml files.
Clean Project.
This is it.
For example I had an entry in my strings.xml:
<string name="A">Some text</string>
And in activity_main.xml I used this string entry
<TextView
android:id="#+id/textViewA"
android:text="#string/A"/>
While'd been working with project, I deleted that
<string name="A">Some text</string>
And consequently activity_main.xml became not valid. As the result: cannot resolve R.
So, check your *.xml files and clean project.
If you see this error after moving java files or directories to other locations, then you can guarantee that Android Studio has gotten confused. And guess what? undo-ing those actions doesn't fix the problem.
So you try a clean, but that doesn't work.
And restarting doesn't work either.
But try File -> Invalidate Caches / Restart... -> Invalidate and Restart
Android Studio maintains information about which files are dependent on which other files. And since moving files around is not implemented correctly, moving files causes errors. And that's not all: caches of these dependencies are used in an attempt to speed up the build.
This means you not only have to restart, but you need to invalidate those caches to restore (or more accurately, rebuild) sanity.
I think if you put your Activities files to another folder than the default one. You need to import the com.example.yourproject.R (this is your project R file NOT Android.R file) to ALL activities using R. For example, in MainActivity file insert this line:
import com.example.yourproject.R;
There seems to be many causes for this issue. Recently, I added an activity to test with called NewActivity. This created a file called res/menu/new.xml and gradle did not like that name because new is a reserved word.
gradlew clean
or
"Tools" -> "Android" -> "Sync Project with Gradle Files"
Those are definitely good things to try, but you may have some other issues you need to resolve before you run those commands.
You should do two things, first clean the project (in build menu) - it deletes the build directory which may be the culprit:
Next, Sync project with Gradle files (under file):
This is the placement for the items in Android Studio 3.6.1 on Windows 10.
If all else fails, Invalidate Caches and Restart (under file) usually does the trick. This closes down the whole program and takes the most amount of time, in my opinion.
To clarify, I am running this on windows 10, but it should work on MacOS and Linux as well.
R.java file contains the link between xml and java page. "R cannot be resolved" arise only if there is a problem with some of your resource files. So the best and effective way is delete the last done xml or drawable in res file. and then again start from there according to android coding norms. This is the only way. The effective and right way.
Also use Git for proper tracking of code. ..
Your code is just scrambled. The answer is fairly simple.
Just go to Build --> Clean Project.
That should do the trick.
Check also your version of Android Studio.
I'm currently using Android Studio 3.0.1.
Have you updated your SDK tools recently? Launch the android SDK manager and make sure you have the latest SDK tools, which is now separate from the platform tools. I had this same issue when I first updated my SDK manager, the SDK build tools package did not show up for install/update until I closed and reopened the SDK manager.
I had to import my R package in android studio. For ex: import com.example.<package name>.R
Just clean your project and Sync Project with Gradle File.
And the problem will be resolved.
I recently had this issue and the clean/build etc. didn't resolve it. I guessed I had an issue somewhere but wasn't sure where to look to find it (was it in the manifest, resource xml files etc?).
When something is wrong, you can find out what it is by doing a code analysis run.
From the menu at the top choose:
Analyze -> Inspect code, scan the whole project using the 'Default' profile.
Your inspection results will contain an element called 'Android'. In here you will get a list of anything that is causing issues in your resources and manifest file. The errors will open up the generated xml files from your build which will show any errors in red.
My exact issue was caused because I was using flavour based manifest files and I copied some permissions inside the <application> tag in the flavour by accident.
UPDATE: I did have an issue after where Android Studio still showed the error after the fix, even though I could now build and run perfectly fine while the error was still there. (I am running a canary build so putting it down to that for now)
I have had this with
An uppercase letter in my drawable resources.
Import Android.R being added by Android Studio (or Eclipse)
Error in xml file
I faced this issue when I manually renamed the domain folder of my app. To fix this issue, I had to
Set the proper package folder structure of <manifest> in AndroidManifest.xml.
Set the new package location for android:name of <activity> in AndroidManifest.xml.
Clear cache by
File Menu -> Invalidate Caches / Restart ...
The issue will be gone, once the Android studio restarts and builds the fresh index.
I had the same issue:
Android Studio 3.2
The project compiles and runs fine, but I am getting "Cannot resolve symbol "R" on-screen warnings
Does not help:
Build->Clean Project
Build->Rebuild Project
File->Invalidate Caches/Restart
Helps:
either
in build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
...
}
replace with
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
...
}
or
Update Android Studio to 3.3
This is a very old question, but it still happens a lot and there is no truly comprehensive answer here.
I have had this problem more times than I want to admit. It can be caused by a wide variety of issues that mostly all have to do with your project structure not matching what's expected. Here's a list of all the problems I've had:
Importing from Eclipse to Android Studio does not always work smoothly, especially with older versions of Android Studio. Make sure you're using the correct directory tree. It should look like this for a moderately mature app:
AppName/ // AppName is your app's name, obviously
.gradle/ // This is a compiler created directory. You should normally leave it alone
.idea/ // Ditto
build/ // This too
gradle/ // And this
app/
build/
libs/
src/
androidTest/ // Tests based on the Android instrumentation runner should go here
main/
java/
fully/ // Typically com
qualified/ // the domain name. Longer package
// names may have deeper folder trees
AppName/ // All your java files go here
res/
drawable-*/ // One of these for each resolution you support
layout/ // All of your general layouts
menu/ // All of your menu layouts
values/ // All of your resource xml files
xml/ // PreferenceScreen layouts go here
AndroidManifest.xml
debug/
test/ // Pure jUnit tests should go here
.gitignore
app.iml
build.gradle // This is the gradle file you should be making most changes to
proguard-rules.pro
.gitignore
build.gradle // This gradle file should mostly be left alone
gradle.properties
gradlew
local.properties
AppName.iml
settings.gradle
It may not look like this in your IDE. There is a drop-down above the file tree that displays your files in different ways, and it defaults on my system to one called Android that breaks your files out into their different types. It's easier to fix this kind of problem from the one called Project, and even easier directly from your OS's file system, because Android Studio collapses folders that only contain another folder onto a single line.
Especially if you ever change the name of your app, you need to make sure that the source tree main/java/com/domain/AppName is updated. Also make sure that the package tag in your AndroidManifest.xml is correct.
If there are errors in either your Gradle files or your AndroidManifest.xml, this will prevent Android Studio from properly building your resource files. Gradle files can be broken by upgrading Android Studio sometimes, especially from the pre-1.0 versions. Sometimes this is because it stops supporting older versions of the Gradle plugin, so you need to update your version numbers. It can sometimes be hard to find what the current versions are. As of today, 7/17/15, my apps are compiling fine with com.android.tools.build:gradle:1.2.3. This is in the dependencies block in the outermost gradle file,
If your AndroidManifest references a non-existent drawable or string resource or activity, it will break and cause this error. Sometimes if anything references a nonexistent drawable or string resource you will get this error.
If you have a file in your resources that is corrupted, or an invalid xml file, you will get this error.
In my experience, sometimes Android Studio just hiccups for no reason, and you need to restart it and/or your PC. I don't know why, but sometimes it works.
If you have two xml resources with the same name, in directories that do not override each other, you can have this problem. For instance, you can have the same name in drawable-mhdpi and drawable-xhdpi because they override each other depending on the target device, but if you have the same name in layout and in menu, it will cause a problem. Rename or delete one of the files.
If only some resources are having this problem, those resources are most likely in the wrong directory.
In one case I had to completely reinstall Android Studio. I don't know what was wrong, but it worked.
In one case I moved my entire project to a different directory and re-imported it as a new project. I don't know what was wrong, but it worked.
Xml files with reserved words for names can cause this problem. Rename or delete them.
There are a few ways your Gradle file can end up referencing a version of the build-tools that you do not have installed. Correct this by changing Gradle or downloading the appropriate build-tools.
Finally, after you've fixed whatever is wrong, you need to clean your Gradle project. You do this by going to the Build menu at the top and selecting Clean Project.
Just go to Android Top menu list. click on Build Menu, in under Build click on Rebuild Project.
I have a special case for this problem.
In my project, every thing goes well, it can compile and build successfully, but in my Android Studio IDE(and I also tried Intelligent IDEA, they are in the same situation) the R.java file can not be resolved well and always be drop in red line.
Just like this:
This almost made me crazy, I can't bear the read color when I am programing.
At last I found this tricky problem is cause by my R.java's file size.
My project is very a huge one, it supports many multi-languages and multi screen sizes. There are so many resources that my R.java's file size is about 2.5M.
The max size of a file in Android Studio is 2.5M in default settings, so files bigger than this limit can't not be resolved well. And you can change the default settings in "AndroidStudio-root/bin/idea.properties".
change this line:
idea.max.intellisense.filesize=2500
to :
idea.max.intellisense.filesize=5000
Then restart Android studio, the red color dismissed, I can program happily again.
Build > Clean Project
This worked for me. Had the same problem a few times, and this seems to set it right. Unless you have changed something or called a variable R. This issue usually happens out of nowhere, when it happens to me, so I imagine its just Android studios freaking out. haha
Have a good one, and good luck with your projects.
Do: Build > Clean Project
IMPORTANT: Make sure you don't have any Errors after Clean Project in Message Pane (Alt+0). If you find any red circles with exclamation mark, than you must remove those errors in your code.
Mostly these errors are related to #string/ or #array/. Clean Project again and done!
I had the same problem and most times it is resolved by
Sync project with gradle files
Doing Build -> Clean Project
Doing File -> Invalidate Caches
But this time the error persisted even after doing all these things and at last i found the culprit.
The problem was in an xml file, where i have given ordinary string value for an android:id instead of an id resource type.
MISTAKE
android:id="username"
CORRECTION
android:id="#id/username"
Messing up things related to resources in xml files is a major
reason for this error.Beware of the fact that it may not be shown as an error in the xml layout file.
NOTE
In most cases the compiler shows you the source of error in the Message.
Try to check it first before attempting other solutions
I had the same problem, and it happens when I create a new project.
What I do is:
check for SDK updates
then android studio updates,
then reopen the project
open the andoridmanifest.xml
erase a space between a "_>" in the android:label and save.
That works for me.
I had a hard time fixing this myself.
Make sure you have no errors in your layout.xml files.
Go to Build > Clean project
It worked for me, hope it works for you too.
`I had same problem and it solved by :
1) Sync Project with gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project
4) File -> Invalidate caches
//imp step
5) Check your xml files properly.`
This notation seems to work fine.
android:id="#+id/viewID"
Android Studio's design panel doesn't seem to work well.
Same problem. Started when I added a few images in my drawable folder and tried to access them. Also the images added were having the extension with capital letters. That seems to have crashed the build, since even if I renamed them, the message was the same and R was inaccessible. What I did is, in the .iml file I looked for the excludeFolder and removed them (like bellow):
<excludeFolder url="file://$MODULE_DIR$/build/apk" />
<excludeFolder url="file://$MODULE_DIR$/build/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/res" />
<excludeFolder url="file://$MODULE_DIR$/build/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
After that I rebuilt the project and R magically re-appeared.
There are many causes for this error.
Sometimes it occurs for replacing an image file keeping same name.
Suppose you deleted an item from your layout .xml say a <Button/> but it is still declared in any Activity or Fragment .java.
Many more.
Best way to track the error is Rebuild it rather clean or sync doing some intentional error.
If it doesn't solve your problem then there must have to be some flaw or runtime error or error occurred due to improper use of resources in may be both java or xml file in your code or design which is forcing gradle to stop because (R)esource file can't index your resources properly and you have to admit that.
If your project ran before you made the changes then comment out the changes you have made and try to rebuild the project.
It will surely work since there will be no changes.
To track down the exact error, check the changes by breaking the changes into smaller module.
For example - If you are making a list visible with a button click and inserting list values in the adapter, first check if you are able to make it visible or not then check for adapter errors.
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
In every instance in all of my classes where I reference R.id.something, the R is in red and it says "cannot resolve symbol R". Also every time there is R.layout.something it is underlined in red and says "cannot resolve method setContentView(?)". The project always builds fine. It is annoying to see this all the time. I have read many other questions on here about something similar but most involved importing projects from Eclipse. I am using what I believe to be the most recent version of Android Studio and the project was created with Android Studio and worked without any "cannot resolve R" problems. I would like to know what causes this if anyone knows.
I had this this issue too. A simple 'gradlew clean' and 'gradlew build' did the trick.
Click on Build->Clean Project and that will perform a gradle clean
In the latest versions of Android Studio, at least for me, the following works:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
In latest Android Studio 3.1.3 (July 2018), "Sync Project with Gradle Files" is available in main menu bar.
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
classpath 'com.android.tools.build:gradle:3.2.1'
Problem resolved after changing the gradle version. Details history can be found here.
I have a similar problem and here is what I did:
Clean Project and Sync Project with Gradle ,
check buildTools version in my sdk
From build gradle (module ) change minSdkVersion from 8 to 9
defaultConfig {
applicationId "PackageName"
minSdkVersion 9
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
But all this didn't help.
Finally I found the answer (this worked in my case)
Change from build.gradle(module:app)
android {
compileSdkVersion 21
buildToolsVersion '21.0.1'
......
....
}
Or
Select File | Project Structure change Build Tools Version to 21.1.1
Check your xml files.
Clean Project.
This is it.
For example I had an entry in my strings.xml:
<string name="A">Some text</string>
And in activity_main.xml I used this string entry
<TextView
android:id="#+id/textViewA"
android:text="#string/A"/>
While'd been working with project, I deleted that
<string name="A">Some text</string>
And consequently activity_main.xml became not valid. As the result: cannot resolve R.
So, check your *.xml files and clean project.
If you see this error after moving java files or directories to other locations, then you can guarantee that Android Studio has gotten confused. And guess what? undo-ing those actions doesn't fix the problem.
So you try a clean, but that doesn't work.
And restarting doesn't work either.
But try File -> Invalidate Caches / Restart... -> Invalidate and Restart
Android Studio maintains information about which files are dependent on which other files. And since moving files around is not implemented correctly, moving files causes errors. And that's not all: caches of these dependencies are used in an attempt to speed up the build.
This means you not only have to restart, but you need to invalidate those caches to restore (or more accurately, rebuild) sanity.
I think if you put your Activities files to another folder than the default one. You need to import the com.example.yourproject.R (this is your project R file NOT Android.R file) to ALL activities using R. For example, in MainActivity file insert this line:
import com.example.yourproject.R;
There seems to be many causes for this issue. Recently, I added an activity to test with called NewActivity. This created a file called res/menu/new.xml and gradle did not like that name because new is a reserved word.
gradlew clean
or
"Tools" -> "Android" -> "Sync Project with Gradle Files"
Those are definitely good things to try, but you may have some other issues you need to resolve before you run those commands.
You should do two things, first clean the project (in build menu) - it deletes the build directory which may be the culprit:
Next, Sync project with Gradle files (under file):
This is the placement for the items in Android Studio 3.6.1 on Windows 10.
If all else fails, Invalidate Caches and Restart (under file) usually does the trick. This closes down the whole program and takes the most amount of time, in my opinion.
To clarify, I am running this on windows 10, but it should work on MacOS and Linux as well.
R.java file contains the link between xml and java page. "R cannot be resolved" arise only if there is a problem with some of your resource files. So the best and effective way is delete the last done xml or drawable in res file. and then again start from there according to android coding norms. This is the only way. The effective and right way.
Also use Git for proper tracking of code. ..
Your code is just scrambled. The answer is fairly simple.
Just go to Build --> Clean Project.
That should do the trick.
Check also your version of Android Studio.
I'm currently using Android Studio 3.0.1.
Have you updated your SDK tools recently? Launch the android SDK manager and make sure you have the latest SDK tools, which is now separate from the platform tools. I had this same issue when I first updated my SDK manager, the SDK build tools package did not show up for install/update until I closed and reopened the SDK manager.
I had to import my R package in android studio. For ex: import com.example.<package name>.R
Just clean your project and Sync Project with Gradle File.
And the problem will be resolved.
I recently had this issue and the clean/build etc. didn't resolve it. I guessed I had an issue somewhere but wasn't sure where to look to find it (was it in the manifest, resource xml files etc?).
When something is wrong, you can find out what it is by doing a code analysis run.
From the menu at the top choose:
Analyze -> Inspect code, scan the whole project using the 'Default' profile.
Your inspection results will contain an element called 'Android'. In here you will get a list of anything that is causing issues in your resources and manifest file. The errors will open up the generated xml files from your build which will show any errors in red.
My exact issue was caused because I was using flavour based manifest files and I copied some permissions inside the <application> tag in the flavour by accident.
UPDATE: I did have an issue after where Android Studio still showed the error after the fix, even though I could now build and run perfectly fine while the error was still there. (I am running a canary build so putting it down to that for now)
I have had this with
An uppercase letter in my drawable resources.
Import Android.R being added by Android Studio (or Eclipse)
Error in xml file
I faced this issue when I manually renamed the domain folder of my app. To fix this issue, I had to
Set the proper package folder structure of <manifest> in AndroidManifest.xml.
Set the new package location for android:name of <activity> in AndroidManifest.xml.
Clear cache by
File Menu -> Invalidate Caches / Restart ...
The issue will be gone, once the Android studio restarts and builds the fresh index.
I had the same issue:
Android Studio 3.2
The project compiles and runs fine, but I am getting "Cannot resolve symbol "R" on-screen warnings
Does not help:
Build->Clean Project
Build->Rebuild Project
File->Invalidate Caches/Restart
Helps:
either
in build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
...
}
replace with
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
...
}
or
Update Android Studio to 3.3
This is a very old question, but it still happens a lot and there is no truly comprehensive answer here.
I have had this problem more times than I want to admit. It can be caused by a wide variety of issues that mostly all have to do with your project structure not matching what's expected. Here's a list of all the problems I've had:
Importing from Eclipse to Android Studio does not always work smoothly, especially with older versions of Android Studio. Make sure you're using the correct directory tree. It should look like this for a moderately mature app:
AppName/ // AppName is your app's name, obviously
.gradle/ // This is a compiler created directory. You should normally leave it alone
.idea/ // Ditto
build/ // This too
gradle/ // And this
app/
build/
libs/
src/
androidTest/ // Tests based on the Android instrumentation runner should go here
main/
java/
fully/ // Typically com
qualified/ // the domain name. Longer package
// names may have deeper folder trees
AppName/ // All your java files go here
res/
drawable-*/ // One of these for each resolution you support
layout/ // All of your general layouts
menu/ // All of your menu layouts
values/ // All of your resource xml files
xml/ // PreferenceScreen layouts go here
AndroidManifest.xml
debug/
test/ // Pure jUnit tests should go here
.gitignore
app.iml
build.gradle // This is the gradle file you should be making most changes to
proguard-rules.pro
.gitignore
build.gradle // This gradle file should mostly be left alone
gradle.properties
gradlew
local.properties
AppName.iml
settings.gradle
It may not look like this in your IDE. There is a drop-down above the file tree that displays your files in different ways, and it defaults on my system to one called Android that breaks your files out into their different types. It's easier to fix this kind of problem from the one called Project, and even easier directly from your OS's file system, because Android Studio collapses folders that only contain another folder onto a single line.
Especially if you ever change the name of your app, you need to make sure that the source tree main/java/com/domain/AppName is updated. Also make sure that the package tag in your AndroidManifest.xml is correct.
If there are errors in either your Gradle files or your AndroidManifest.xml, this will prevent Android Studio from properly building your resource files. Gradle files can be broken by upgrading Android Studio sometimes, especially from the pre-1.0 versions. Sometimes this is because it stops supporting older versions of the Gradle plugin, so you need to update your version numbers. It can sometimes be hard to find what the current versions are. As of today, 7/17/15, my apps are compiling fine with com.android.tools.build:gradle:1.2.3. This is in the dependencies block in the outermost gradle file,
If your AndroidManifest references a non-existent drawable or string resource or activity, it will break and cause this error. Sometimes if anything references a nonexistent drawable or string resource you will get this error.
If you have a file in your resources that is corrupted, or an invalid xml file, you will get this error.
In my experience, sometimes Android Studio just hiccups for no reason, and you need to restart it and/or your PC. I don't know why, but sometimes it works.
If you have two xml resources with the same name, in directories that do not override each other, you can have this problem. For instance, you can have the same name in drawable-mhdpi and drawable-xhdpi because they override each other depending on the target device, but if you have the same name in layout and in menu, it will cause a problem. Rename or delete one of the files.
If only some resources are having this problem, those resources are most likely in the wrong directory.
In one case I had to completely reinstall Android Studio. I don't know what was wrong, but it worked.
In one case I moved my entire project to a different directory and re-imported it as a new project. I don't know what was wrong, but it worked.
Xml files with reserved words for names can cause this problem. Rename or delete them.
There are a few ways your Gradle file can end up referencing a version of the build-tools that you do not have installed. Correct this by changing Gradle or downloading the appropriate build-tools.
Finally, after you've fixed whatever is wrong, you need to clean your Gradle project. You do this by going to the Build menu at the top and selecting Clean Project.
Just go to Android Top menu list. click on Build Menu, in under Build click on Rebuild Project.
I have a special case for this problem.
In my project, every thing goes well, it can compile and build successfully, but in my Android Studio IDE(and I also tried Intelligent IDEA, they are in the same situation) the R.java file can not be resolved well and always be drop in red line.
Just like this:
This almost made me crazy, I can't bear the read color when I am programing.
At last I found this tricky problem is cause by my R.java's file size.
My project is very a huge one, it supports many multi-languages and multi screen sizes. There are so many resources that my R.java's file size is about 2.5M.
The max size of a file in Android Studio is 2.5M in default settings, so files bigger than this limit can't not be resolved well. And you can change the default settings in "AndroidStudio-root/bin/idea.properties".
change this line:
idea.max.intellisense.filesize=2500
to :
idea.max.intellisense.filesize=5000
Then restart Android studio, the red color dismissed, I can program happily again.
Build > Clean Project
This worked for me. Had the same problem a few times, and this seems to set it right. Unless you have changed something or called a variable R. This issue usually happens out of nowhere, when it happens to me, so I imagine its just Android studios freaking out. haha
Have a good one, and good luck with your projects.
Do: Build > Clean Project
IMPORTANT: Make sure you don't have any Errors after Clean Project in Message Pane (Alt+0). If you find any red circles with exclamation mark, than you must remove those errors in your code.
Mostly these errors are related to #string/ or #array/. Clean Project again and done!
I had the same problem and most times it is resolved by
Sync project with gradle files
Doing Build -> Clean Project
Doing File -> Invalidate Caches
But this time the error persisted even after doing all these things and at last i found the culprit.
The problem was in an xml file, where i have given ordinary string value for an android:id instead of an id resource type.
MISTAKE
android:id="username"
CORRECTION
android:id="#id/username"
Messing up things related to resources in xml files is a major
reason for this error.Beware of the fact that it may not be shown as an error in the xml layout file.
NOTE
In most cases the compiler shows you the source of error in the Message.
Try to check it first before attempting other solutions
I had the same problem, and it happens when I create a new project.
What I do is:
check for SDK updates
then android studio updates,
then reopen the project
open the andoridmanifest.xml
erase a space between a "_>" in the android:label and save.
That works for me.
I had a hard time fixing this myself.
Make sure you have no errors in your layout.xml files.
Go to Build > Clean project
It worked for me, hope it works for you too.
`I had same problem and it solved by :
1) Sync Project with gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project
4) File -> Invalidate caches
//imp step
5) Check your xml files properly.`
This notation seems to work fine.
android:id="#+id/viewID"
Android Studio's design panel doesn't seem to work well.
Same problem. Started when I added a few images in my drawable folder and tried to access them. Also the images added were having the extension with capital letters. That seems to have crashed the build, since even if I renamed them, the message was the same and R was inaccessible. What I did is, in the .iml file I looked for the excludeFolder and removed them (like bellow):
<excludeFolder url="file://$MODULE_DIR$/build/apk" />
<excludeFolder url="file://$MODULE_DIR$/build/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/res" />
<excludeFolder url="file://$MODULE_DIR$/build/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
After that I rebuilt the project and R magically re-appeared.
There are many causes for this error.
Sometimes it occurs for replacing an image file keeping same name.
Suppose you deleted an item from your layout .xml say a <Button/> but it is still declared in any Activity or Fragment .java.
Many more.
Best way to track the error is Rebuild it rather clean or sync doing some intentional error.
If it doesn't solve your problem then there must have to be some flaw or runtime error or error occurred due to improper use of resources in may be both java or xml file in your code or design which is forcing gradle to stop because (R)esource file can't index your resources properly and you have to admit that.
If your project ran before you made the changes then comment out the changes you have made and try to rebuild the project.
It will surely work since there will be no changes.
To track down the exact error, check the changes by breaking the changes into smaller module.
For example - If you are making a list visible with a button click and inserting list values in the adapter, first check if you are able to make it visible or not then check for adapter errors.
So I'm making a java application in Neatbeans 7.4, been working at it for a while, everything was fine, running the project worked fine, but now when I hit run project, I get the error
Error: Could not find or load main class phleveledit.MainWindow
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I can't think of what I did right before this started happening, so I don't know what I should change.. The code doesn't appear to have any errors. Here's a screenshot of the IDE+project folder
Image (http://puu.sh/5ldYB) :
Any ideas?
Edit: Unfortunately I happened to fix this problem by removing some code, which probably had some errors Netbeans couldn't detect, but I don't know what was exactly wrong so can't vote on a correct answer.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Clean an build your project
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Just close the Netbeans. Go to C:\Users\YOUR_PC_NAME\AppData\Local\Netbeans and delete the Cache folder. The open the Netbeans again and run the project.
It works like magic for me.
(AppData folder might be hidden probably, if so, you need to make it appear in Folder Options).
You can :
RightClick on project node and go to Set configuration
Select the main class for your application.
Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
User\.netbeans\SOME_NUMBER_reflecting_your_version\var\cache\index\
Sometimes due to out of memory space error, NetBeans does not load or find main class.
If you have tried setting the properties and still it is not working then try
Select the project from the project explorer
Click on Run in the Menu Bar
Click on Compile
It worked for me.
This condition happens to me every 6-months or so. I think it happens when closing NetBeans under very low memory conditions. I discovered that it could be easily corrected by (1) Rename your project, including its folder name using right-click on project explorer's project name---I put a simple suffix on the original name ("_damaged"). (2) Try BUILD. If that is successful, which it is for me, give three cheers. (3) Repeat step (1) to restore the original project name. BUILD and RUN should start without trouble.
I guess that the 'rename the project and folder' process causes a special rediscovery of the applications main location.
Try to rename the package name and the class/jframe names... The clean and build the application.
Right Click on the package name
Go to Refactor
Select Rename
Give it a meaningful name, preferably all in small letters
Click on Refactor
Do the same for the class/jframe names.
Last Select Run from Menu
7.Select Clean and build main project
That should do it!!! All best
I had the same issue once. The problem was not in the code. The cause was... renaming the project folder to some other non supporting name. My project name was "MobStick" and I renamed it to "MobStick - May 26, 2014 04:00PM". Renaming it back to normal solved my problem.
I have run into this error a couple of times as well and for me the above solutions did not work. What does seem to work is going to the Project Properties, and under Compiling toggling Compile on Save.
Using NetBeans 8.1, I got the dread
Error: Could not find or load main class
from carelessly leaving an empty line in the Project Properties > Run > VM Options field. Until you click in the field, you may not see the caret flashing out of place. Remove the empty line to restore equanimity.
I just ran into this problem. I was running my source from the command line and kept getting the same error. It turns out that I needed to remove the package name from my source code and then the command line compiler was happy.
The solutions above didn't work for me so maybe this will work for someone else with a similar problem.
I had the same problem, I had the package and class named the same. I renamed the class, then clean and build. Then I set the main class in the "run" under the properties of the project. I works now.
I found the following steps useful:
Right-click on the project in the left toolbar.
Hover over the 'Set Configuration' item.
Click on 'Customize...'
Click on 'Browse...' by the 'Main Class:' item.
Select the correct class.
Click 'Select Main Class'.
Click 'OK'.
My problem was that, apparently, my package name was being listed twice. Selecting the class using the dialog changed 'aclass.MainClass' to just 'MainClass'.
Hope this helps,
-HewwoCraziness
Edit: This is expanding on Mary Martinez's answer.
You can solve it in these steps
Right-click on the project in the left toolbar.
Click on properties.
Click on Run
Click the browse button on the right side.(select your main class)
Click ok
Possible Fixes:
Fix 1
Go to project properties (right click on the folder of your project in netbeans)
On left tab where it shows the categories, click on the "Run" selection
Then click on Browse to find the Main class you use on your project
Fix 2
Go to C:\Users\name\AppData\Local\Netbeans
delete the Cache folder.
Rebuild and Run
Fix 3
Download most recent version of Netbeans
Fix 4
Download most recent version of JDK and configure Netbeans to use that
I had the same problem for 3,4 days. On my PC my Jar file snapshot would give me this error while on my laptop it would work fine, I tried all the tricks shown above and on other forums like deleting cache, selecting main project file, etc, but somehow I was sure the reason it cannot find the main class when I would execute the JAR file was may be due to classpath issue in maven configuration, and I was right and I fixed it using following steps:
Right-click on the project, and go to the properties
Inside the properties go to Actions
On the right side in Actions select "Run Project" and you will see properties below
Inside "Set Properties" make sure exec.args=classpath %classpath "package_name"
In my case, the package name was accompanied by the main class. So my main class was Login while the package name was com.mycompany.islamic_center_app1, When I checked the entry was
com.mycompany.islamic_center_app1.Login
All I did was remove ".Login" from com.mycompany.islamic_center_app1 and it was fixed, no more errors.
close netbeans.
open netbeans again.
choose new project>>java application.
click next.
deselect create main class.
now make the application
clean build run
For more reference watch this video
try this it work out for me perfectly
go to project and right click on your java file at the right corner,
go to properties,
go to run,
go to browse, and then
select Main class.
now you can run your program again.
I had the same problem and I moved the project to a location where the path had no none-english letter and that fixed the problem
if you are on window os, then try to start NetBeans via administrative mode. right click on NetBeans icon and "Run as Administrative".
If none of the above works (Setting Main class, Clean and Build, deleting the cache) and you have a Maven project, try:
mvn clean install
on the command line.
Had the same problem here. Usually Clean and Build solves much of the problem. It happened to be caused by a wrongly installed plugin.
I faced the similar issue with Netbeans 10 and JDK 1.8.
I was not able to choose the right class to launch the project
When I compile or run the project, it shows me the Class name as "initializing view, please wait ...", I could not select the class name.
The issue was resolved with the NetBeans11.3, I am able to choose the correct Class file without any other changes, and the project is launched without any issues.
I had the same issue but none of this thread's solutions worked for me. Finally, it was OneDrive that caused the issue (for once more). So, I simply moved the NetBeansProjects folder from Documents which is synced with OneDrive, to C:\Users\yourName\AppData\Local\NetBeans (selected this path as there is already a NetBeans folder) and that was it, case closed.
If you also have NetBeansProjects to a OneDrive syncing folder it is worth trying this solution, just be sure that the path you will select is not synced with OneDrive. Also, remember to close Netbeans before making the folder change and after you move the folder to the new path you need just to open Netbeans again, go to file menu/open project and select your project from the new path.
I am attempting to incorporate admob ads in my app. So far I have added the following code
in the onCreate method of my app's main activity...
adView = new AdView(this,AdSize.BANNER,"my code number");
adView.loadAd(new AdRequest());
The program compiles without error but at run time I get the message java.lang.NoClassDefFoundError: com.google.ads.AdView. I have seen a supposed explanation of the problem and the cure here but I could not see how it was applicable to my project because I do not have either a "lib" or "libs" directory within my project.
According to eclipse's SDK manager, I have the most up to date version of everything that I use.
I had a similar problem, but did not have to add the libs folder; I tried, with no success, then removed them afterwards, when I realized that I had just forgotten to export the included Jar archived.
Fix:
Select project settings > Java Build Path, then Order and export.
Here, check the GoogleAdMobAdsSdk-package.
This should solve the NoClassDefFoundError-issue.
Just create manually the "libs" folder, and add your libraries there. By default, they doesn't exist
Project-> Clean
Project settings -> Java Build Path. Open "Order and export" tab.
Check GoogleAdMobsAdsSDK.
It is worked for me.
Was getting this error updating from android 16 to 20.
Solved by going to Java Build Path, Order and Export tab, checked and moved GoogleAdMobAdsSdk just under my source. For some reason that fixed it.
Changing the order back didn't break it. So some setting must have needed to be initialized.
I had this problem, and this problem too:
Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode and Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode
Despite many hours of following all solutions listed the only way I could get my app to work was to use the AdMob banner example here:
https://github.com/googleads/googleads-mobile-ios-examples/tree/master/admob/SmartBannerExample
And re-build my project around it, copying my files in to that project. If you are stuck, try it.
Don't know why it worked, but now it does. Something in my project was very wrong. Now I can carry on with my work. I love Google/Android, but really what a mess!
See this answer Android update 17 seems incompatible with external Jars.
You need to put all jars in libs folder insted of lib.
It's not enough only to add "GoogleAdMobAdsSdk-6.4.1.jar" in Java Build Path,then you should switch to table:Order and export.check the "GoogleAdMobAdsSdk-6.4.1.jar" here.
UPDATE:
Select project settings > Java Build Path, then Order and export.
Here, check the google-play-services.jar.
This should solve the NoClassDefFoundError-issue.
In my case I needed to click on the "Android Private Libraries" on the "Order and Export" Tab
Go to Properties - Java Build Path - Order and Export and check every Checkmark! That did the trick for my project.
I am trying to refactor my package using Eclipse
org.sheehan.activity
to
org.sheehan.stocks.activity
For some reason my project just blows up when I do this and R doesn't get regenerated. How can I refactor properly?
UPDATE:
I updated my Android Manifest to reflect the change. R still doesn't get regenerated. Even after a clean. The compiler is complaining about org.sheehan.activity.R
I resolved by:
Android Tools > Rename Package Application
If you renamed properly, all your references across your project should have gotten updated. After doing this, clean your project by going to Project > Clean. This should fix it.
Fixing missing reference to R in eclipse:
Refactor -> Rename`
Build -> Clean
Android Tools -> Fix Project Properties
select the base package of your project in the eclipse package explorer, press F2 (Rename), in the rename dialog: SELECT ALL the checkboxes.:
That should do it
The package name doesn't update in the XML files. Specifically your manifest which needs to know the base package.
For more advanced imports and refactors, literally closing the Eclipse IDE can refresh a cache that causes random errors like "End position lies outside document range" or the "what once worked now doesn't hair puller outter errors."
Signs you should close Eclipse when trying to rename things are:
When you import a project, do some refactoring (like trying to change the package name), then delete the project and try again, you will see immediate R.java errors when you didn't before
When you are importing projects that have manually generated R.java files that have custom imports like "com.ns.proj.R" and don't see the name update in Preview
The box that asks if you want to "Rename subpackages" is checked unexpectedly
the code in the "Preview>>" looks as if it's been complied before instead of black and white code with the proper names replaced
you get XML errors in the manifest activity name like this
android:name="com.ns.proj.CustomCocom.ns.proj.CustomControlse="#android:style/Theme.Light.NoTitleBar"
when it should be
android:name="com.ns.proj.CustomControls"
android:style="Theme.Light.NoTitleBar"
There are too many to name obviously, however this is as important as "keep your eye on the ball" in sports. Something that is so easy to forget, yet things like these apply to other software programs like Dreamweaver (e.g. when you use the Dreamweaver "Put" option instead of FTP dragging with FileZilla and you notice your domain isn't updating your changes online). I called Adobe when I first started as a developer 8 years ago because I knew I wasn't doing anything wrong. They said sometimes the generated files to perform the action get corrupted...in other words, IDE's have bugs too!
In general, close the IDE before you off yourself...it could save your life!
Right click in your Project, go to
Android Tools > Rename Package Application
Sometimes if Project > Clean doesn´t work, so Delete /gen and /bin folders of your project.