Default Template on Android Studio deprecated - android

Earlier I was asking about how to come over from Windows phone development. I didn't just sit and wait for replies I got started.
I installed Android Studio. I learned that it didn't have the 4.4 API by default (the version of Android my new phone will be running) so I located the SDK manager and installed the missing SDK.
The preview pane for the layout editor could not render...I learnt I needed to go to the module settings and change the target there, then to the preview pane drop-down and change the targeted Android version there.
I added a simple button and then realised I have an error with the java ...that I have yet to touch!
public class MainDisplay extends ActionBarActivity {
ActionBarActivity is deprecated.
...but that's the default template!
getMenuInflater().inflate(R.menu.menu_main, menu);
cannot resolve symbol R.
...again, it's default "blank activity" template.
I checked for updates and it is the latest version of Android Studio: 1.2.1.1. My JDK is the latest version: jdk1.8.0_45 (64bit).
Any ideas why my Android Studio (freshly installed today) is generating broken templates or any other ideas about how to fix?
EDIT
I uninstalled Android Studio, the SDK and deleted all folders created by it
then I reinstalled it all. I installed version 1.7 of Java JDK.
I got the same errors on a new project.
This is the source code it generates:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
As you can see, it is extending the deprecated class, and adding those R's it can't resolve .....and this is before I have done anything.
But for tonight, I have run out of time. I had 7 hours free to start porting my app to Android and it's all gone setting up the dev environment. I wouldn't mind but it's not working and I have no idea why.

According to this video you should only make two changes
After I did this 2 changes all worked fine
For more information about this you have this [1] and this blog
UPDATE 1
After this change, clean your project and Sync Project with Gradle File.
UPDATE 2
If after that you have problem resolving symbol R errors after an SDK update in Android Studio you can follow the steps showing in this blog

First one. The ActionBarActivity is deprecated since API 21 (or 22 maybe) and now you should simply extend from Activity and use AppCompatDelegate. It's a really new feature so I suppose they haven't fixed it yet. I haven't tried using it yet so can't help with that. Even if the ActionBarActivity is deprecated it will work fine so it's not a problem for you.
Second. About the R being not found. The problem is inside your Gradle file (not the app one but the second one). In it you will need to fix a line under the dependencies tag (classpath) and change it to newer version. I can't seem to find the right version now but I have already solved this problem today for my friend so it will definitely work
It is also a bug in a current Android Studio version and after you fix it it will work fine.

Related

After migrating to AndroidX: Cannot instantiate class: androidx.appcompat.widget.ShareActionProvider

I migrated to AndroidX (using the wizard in Android Studio), and I'm having problems with the share action provider. The wizard changed (among many other things) app:actionProviderClass="android.support.v7.widget.ShareActionProvider" to app:actionProviderClass="androidx.appcompat.widget.ShareActionProvider", in my detailactivity.xml file.
The app compiles fine, and runs fine, too -- so long as I install it on my device over USB. However, if I compile a signed APK, and install that, I get the following runtime error (when starting the detailfragment):
W/SupportMenuInflater: Cannot instantiate class: androidx.appcompat.widget.ShareActionProvider
I didn't notice this problem while developing, since I run/test the app on my device through USB. However, when I'm now testing the (signed/minified) APK, the SHARE button does not work. How can I troubleshoot and fix this? For instance, why does it fail on the signed/minified APK fail, while it works fine when installing on same device through USB?
It's hard to tell specifically where (in the code) the warning occurs, since the code in the APK is minified. Perhaps I could create an APK where the code is not minified, so I'd get proper references to lines in the source code (in Android Studio LogCat)?
For reference, here is an excerpt from the class where the warning occurs. I'm assuming the warning occurs somewhere here, as this is what's referencing the shareActionProvider?
import androidx.appcompat.widget.ShareActionProvider;
public class ScreenSlidePageFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private ShareActionProvider mShareActionProvider;
public ScreenSlidePageFragment() {
setHasOptionsMenu(true); // only the share button
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detailfragment, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
if (mShareActionProvider != null && mImageData != null) {
mShareActionProvider.setShareIntent(createShareImageIntent());
}
}
}
I got some help on #android-dev (IRC), and it seems the problem was that the minifier (for some reason) removes the androidx.appcompat.widget.ShareActionProvider class. Turning off minification produced a working APK.
The fix was to update my proguard-rules.pro file with a new "keep" line, to prevent it from removing the class. From before, I had a similar rule for the old Android Support Library, so I added the second line below and now it works.
-keep class android.support.v7.widget.** { *; }
-keep class androidx.appcompat.widget.** { *; }
thanks #melatonina!

Convert an old style Android menu to work on newer phones

My old app has one simple menu on the main activity. It has only a few simple options, for instance "About" causing a popup with some info about the app.
It works perfectly on emulator Nexus One (API23), because there is an emulated physical menu button.
However, on most modern phones, there is no button, which means that my menus cannot be accessed.
I actually vaguely remember running it on a phone years ago which didn't have a menu button, yet somehow one could still access the menus. I may remember wrong.
(I started digging into this some days ago, and started modifying my code, the main activity inheriting from something more posh than Activity, which then caused some older API versions to be left out - and things quickly spun out of control. After hours of "maven gradle settings" and "Support Library" stuff and many pages of "AAPT2 errors" and messing up my whole system trying to fix that, I had to throw everything away and get a fresh clone from the repo. Fortunately I could also repair the other changes I had made to the system.)
How does one convert an old-style app menu to work on modern phones? It doesn't have to be fancy.
/** Setup menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/** Handle menu clicks */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_about:
final SpannableString s =
new SpannableString(getApplicationContext().getText(R.string.about));
Linkify.addLinks(s, Linkify.ALL);
AlertDialog d = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("About")
.setMessage(s)
//.setView(message)
.show();
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
return true;
default:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("Currently not used.")
.show();
return super.onOptionsItemSelected(item);
}
}
I'll admit that I no longer understand all the details above from years ago.. it worked, so I never paid it much attention. It looks a bit wordy... probably there are simpler ways to do it.
This is menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"/>
<item
android:id="#+id/action_about"
android:orderInCategory="3"
android:title="About"/>
<item
android:id="#+id/action_manual"
android:orderInCategory="4"
android:title="Manual"/>
</menu>
Maybe there is some "theme" to just add somewhere that makes the menu button show up somewhere on the screen, and that's that? (I know I am optimistic. :))
Everything looks fine.
I think your problem is because you are extending Activity.
change Activity to AppComatActivity.
and change your appThem to android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
Note:
To use the AppCompatActivity, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:
compile 'com.android.support:appcompat-v7:27.0.2'
SOLUTION:
The only way to a solution that I could find was to create a completely new project with default settings in the latest Android Studio. This gives a "latest fashion" setup. Then I moved code in from the old project manually.
Everything now works perfectly!
ISSUES / REASONS:
As mentioned in the comment section above, every attempt I made to modernize the code resulted in a maze of problems. It was an old project, from way back when Android Studio was not even in Beta stage. Hence, it was based on Eclipse. The current Android version back then was Jelly Bean (Kitkat was just released).
In summary, we had an ancient project based on an older IDE. Perhaps it would be doable to convert a modern Eclipse project into Android Studio. Perhaps it would be doable to convert an older AS project into a modern one. However, performing both these major jumps at the same time was too great a challenge for me.
Another issue which has nothing to do with the old code, but which confused the matter greatly is that something called AAPT2 currently for whatever reason assumes american characters only in the search path to the .gradle directory. I use the word "assumes", because if the characters are anything else, you get pages of errors in the build log. None of the errors point very clearly to the reason.
AFAIK I don't even use AAPT2! After some sleepless nights, I solved it by changing the global setting in Android Studio to simply use another path.

Error in running a Hello World app in Android Studio

I created a blank template and chose API 15 as minimum.
1- The activity_main.xml preview asked me to choose another theme. Why?
2- The MainActivity.java class is extending AppCompatActivity instead of Activity. I tried to delete it and typed Activity and imported the corresponding jar but then the IDE doesn't reconize R in R.layout.activity_main. The IDE says it can't resolve AppCompatActivityin import section of the code. Where is the problem?
package com.company.myfirstapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks
P.S.
It seems the gradle was somehow unsuccessful in building the project. I'd used -Xmx256m in its settings.(What was the problem with this curb?) I removed the curb and it built the project. The weird thing is Android Studio recognized AppCompat stuff after building the project! (Shouldn't the IDE know all the classes used in code before compile?). Anyway, my problem is solved now but I don't know the reason
If you are still having that error then you can try going step by step via this blog : Hello World App on android studio
It would be easier if you uploaded your code
If the error is Cannot resolve R you just need to press ctrl+shift+o to organize imports and restart android studio

Eclipse can't detect resources - "R cannot be resolved to a variable"

When I try to create an android project in eclipse the code has errors.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
I'm getting "R cannot be resolved to a variable"
I think it can't detect the resources?
My SRC code is:
package com.android.h4;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In all of R eclipse detects an error. I tried to create a new project with appcompat_v7 and I deleted the libs and res folders as well as the AndroidManifest.xml. Then i imported these folder from a working project with the same name(someone emailed them to me) and at emptied the src but the error remains.
Any idea what I should do?
There are some possibilities that may evoke that error.
The easiest way (seems stupid but often helps)
Go to "Project" in the Menu of Eclipse and click on "Clean"
After Cleaning, the workspace is rebuild and hopefully the R-file
is recognized than. (Sometimes even a restart of Eclipse helps)
Check all your IDs. As already said in comments, it's possible that you have
misspelled the ID (you define your IDs in the layout, there you have to check it)
Last but not least: DON'T TRY TO CHANGE THE R-FILE YOURSELF! :)
I hope I could help you. If not, just specify your problem (i.e send a copy of your layout xml)
You should clean your project and build again. For doing that you should go to
tab project -> clean -> select the project
And for more details you can also dig out on these links
R cannot be resolved - Android error
“R cannot be resolved to a variable”? duplicate

R cannot be resolved to a variable without doing anything to the project

I am getting the error "R cannot be resolved to a variable" that many people seems to be getting. However, none of the answers that I have seen has worked for me. I've gone to the extreme basic and created a helloworld project, with all default settings. The "R cannot be resolved to a variable" error is created instantly, and I cannot see what is wrong... no xml errors, all lowercase in /res/ folder, no difference in AndroidManifest.xml.
For reference, the code on MainActivity.java is:
package com.test.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Is there something wrong with eclipse setting?
I'm using Windows 7 64-bit
Whenever I had a problem with R not been generated, or even disappeared, first clean and rebuild the project, if this is not worked then it was due to some problem in the XML layout file that prevented the application from being built. Check for the /res directory and there must be some file that have some error in it and that is preventing the application from being built. For example, it may be a layout file or it may be due to some missing resource is, but you already defined it in the XML file.

Categories

Resources