android-studio , Can I replace ActionBarActivity with AppCompatActivity in a Tabbed Activity in Android Studio?

Can I replace ActionBarActivity with AppCompatActivity in a Tabbed Activity in Android Studio?


Tag: android-studio

The following Tabbed Activity is created by Android Studio 1.2.2 Wizard, it works well in API 9, but someboyd told me that ActionBarActivity is deprecated,

so I hope to replace public class MainActivity extends ActionBarActivity implements ActionBar.TabListener with public class MainActivity extends AppCompatActivity implements ActionBar.TabListener , and stay all other code the same, is it OK?


package com.example.cuiwei.myapplication;

import java.util.Locale;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

     * The {@link} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link}.
    SectionsPagerAdapter mSectionsPagerAdapter;

     * The {@link ViewPager} that will host the section contents.
    ViewPager mViewPager;

    protected void onCreate(Bundle savedInstanceState) {

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(;

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            public void onPageSelected(int position) {

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    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 == {
            return true;

        return super.onOptionsItemSelected(item);

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {

        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);

        public int getCount() {
            // Show 3 total pages.
            return 3;

        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            return null;

     * A placeholder fragment containing a simple view.
    public static class PlaceholderFragment extends Fragment {
         * The fragment argument representing the section number for this
         * fragment.
        private static final String ARG_SECTION_NUMBER = "section_number";

         * Returns a new instance of this fragment for the given section
         * number.
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            return fragment;

        public PlaceholderFragment() {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;



You can safely replace ActionBarActivity with AppCompatActivity.

As you can see in v7-appcompat source code from version v22.1.0 ActionBarActivity simply extends AppCompatActivity:

 * @deprecated Use {@link} instead.
public class ActionBarActivity extends AppCompatActivity {


Android Studio plugin for capture Strings

I'm searching a plugin for Android Studio that help me catch the Strings in my APP, I don't use the recomendations of the Android and make my APP using Strings hardcoded. How do you capture the Strings of codes of automatic way? [I've searched in the google (web) but I...

Is there a way to make images take up less space in an apk or will I have to use an APK expansion file? [closed]

I made an app in android studio that has a lot of images, making the app exceed the 50MB limit. I do not fully understand how to make an expansion file so I want to try to avoid it. I copied all the images in each mipmap, can I get...

Android Studio and gradle

I tried importing Xabber ( GitHub ) within Android Studio , I did the git init etc . Now I find that I can start the app for that problem Gradle , I've looked everywhere , but could not find anything that would work .. The problem is: Error:Execution failed...

Having problems while trying to delete single rows from a custom ToDo list?

I want to delete selected rows from a todo list by clicking on the checkbox and deleting them trough the delete button, for that I am within my custom adapter setting a setOnCheckedChangeListener on my checkbox and setOnClickListener on my delete button, now keep in mind that the delete button...

How to set max line length in Android Studio code editor?

How can I set a maximum length for Android Studio's code editor, or may be set a word wrap? In my Android Studio, no matter how long a statement I type on a single line, it never automatically goes to the next line, but rather a horizontal scroll bar appears....

Android Studio: cannot upgrade google play services

I have tried download the latest version on the sdk manager, but is still not working. I have seen other posts telling users to enter the following... compile '' I do not understand where to enter it. I tried in the terminal feature of the android studio but it gives...

How to put Like function under an image and save the “Liked” status?

I'm trying to figure out how to put a "Like function" to a few local stored images and remember the app that the user liked those images. Let me explain: I want the user to be able to press "Like" under the image he likes. This means the "Liked" status...

Can't migrating AndroidManifest.xml file to Android Studio?

When i try to migrating Eclipse ADT project to Android Studio using "Import project (Eclipse ADT, Gradle, etc.)" then selecting project root folder and then third window gives me error like this C:\Users\Tsomone\workspace\cims-android-app-new\AndroidManifest.xml: Invalid XML file: C:\Users\Tsomone\workspace\cims-android-app-new\AndroidManifest.xml: Premature end of file. and when i try to click Finish, it shows...

Can I replace ActionBarActivity with AppCompatActivity in a Tabbed Activity in Android Studio?

The following Tabbed Activity is created by Android Studio 1.2.2 Wizard, it works well in API 9, but someboyd told me that ActionBarActivity is deprecated, so I hope to replace public class MainActivity extends ActionBarActivity implements ActionBar.TabListener with public class MainActivity extends AppCompatActivity implements ActionBar.TabListener , and stay all other...

how to add menu items to action bar in more than 30 activities

I have created an app in android studio that has more than 30 activities .I created menu items in some activities by adding them in individual menu files and they worked fine . But the problem is that it is a real headache to add all the menu items in...

android studio casting warning

I mistakenly disable this feature but I don't know how to enable again. The feature is that warns me when I cast an object to another class. For example: ImageView scanner; TextView errorMessage; @Override protected void onCreate(Bundle savedInstanceState) { errorMessage = (TextView) findViewById(; scanner = (TextView) findViewById(; // studio warns...

Android build project error trying to build apps > 65K (65536) methods

I have added these two new dependencies in my build.gradle compile '' compile '' And right now, I can't build my project because I've got an error. I have found information about the error and the solution that I have found says that I have to add ... compile 'com.parse.bolts:bolts-android:1.+'...

Twitter4j - cannot resolve method - setUsessl(boolean)

I'm using twitter4j 4.0.3 core I have this code: public final class TwitterUtil { private RequestToken requestToken = null; private TwitterFactory twitterFactory = null; private Twitter twitter; private TwitterUtil() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET); configurationBuilder.setUseSSL(true); Configuration configuration =...

Make Robolectric run test for the current build type only

I'm using Robolectric alongside Android Studio (v 1.2.2) classpath '' buildToolsVersion "21.1.2" testCompile 'org.robolectric:robolectric:3.0-rc3' My project contains 4 build types. In spite of having debug build type selected in the "Build Variants" window, Robolectric tests every declared build type (4 times). Is it an expected behavior? How can I narrow...

Duplicate entry for class in gradle

I am trying to implement ken burns view in android studio in my app, i have importted the folder which contains its classes, but gradle gives me this error Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'. > duplicate entry: com/flaviofaria/kenburnsview/MathUtils.class Here is my build.gradle apply plugin: '' android { compileSdkVersion 21...

XML parsing error (android studio)

I have made an xml file (using android studio), which allows me to have a tool bar throughout my android application. However, I just keep on getting the following error: ?xml version="1.0" encoding="utf-8"? xmlns:android="" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/ColorPrimary" android:elevation="4dp" > Errors: Error:(2) Error parsing XML: XML or text declaration not...

Android - Custom Home Application Doesn't Appear When Click Home Button

I'am using Android Studio and I have developed an Home Application by adding <activity android:windowSoftInputMode="stateAlwaysHidden" android:screenOrientation="landscape" android:launchMode="singleInstance" android:stateNotNeeded="true" android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> <category...

ProGuard issues with Android Archieve(.aar) library

I've a library project which I want to distribute, in AAR format. I've applied ProGuard on it. ProGuard settings works well if I use this lib as a module, but not when I use resulting AAR. Basically it fails with exception "java.lang.IllegalArgumentException: already added Lmy/lib/package/name/R;" in Application project. ProGuard is...

getView method causing NullPointerException

I'm getting a NullPointerException, when I'm trying to get some image from database I think my getter and setter method is wrong, any help is much appreciated. This is my Activity public class ViewMoreDetailsImages extends Activity{ ProgressBar progressbar_01; ListView lv_images; ImageAdapter imageAdapter; List<ImageInformation> imageInformationList = new ArrayList<ImageInformation>(); @Override protected void...

Getting processDebugResources error in Android Studio

I am getting an error when I try to compile the project in android studio like this, Error:Execution failed for task ':app:processDebugResources'. > org.gradle.process.internal.ExecException: Process 'command 'E:\adt-bundle- windows-x86_64-20140702\sdk\build-tools\23.0.0_rc2\aapt.exe'' finished with non-zero exit value 1 What is the reason for this? How to solve this? Thanks....

Close module in android studio

in eclipse there is simple option to close or open project. How can I do it in android studio to close and open module without import it and delete each time?

populating a text view in an android Fragment from a text file in /res/raw

I am attempting to populate an textview in an android fragment. I am having no luck at all as the fragment is blank. I know I am fundamentally missing something. I have read the docs on fragments and I am still confused. Below is my code for one of the...

Huge unusable font size in Android Studio

As the title states, I've inadvertently set the font size to something gargantuan in Android studio and it's now totally unusable. At most I see the tops of a few letters once the program loads, so I can't even get back into the options to reduce the font size. Looking...

Generated source files should not be edited?

When I create this new class Quake and try to write some code in it ,it displays the following message, and when I try to run it Android Studio automatically delete the class Quake. Can someone explain me why is this happening and how to resolve it ?...

Unexpected Token Error in Android Studio

package com.hello_world.helloworld; import; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.util.log; public class HelloWorld extends AppCompatActivity { private static final String TAG - "My Message"; Another error it says is that Private field 'TAG' is never used. I am unsure why i am getting these errors and I need...

Use higher API level in android with an external library

Would it be possible to import an external library (.jar file) in an android project containing the features of API level 21, and then use them in my application with a minimum sdk version set to say like 17? I'm really into Matierial Design but as Google states, "To use...

How to determine Android Full SDK Download size?

I'm asked to report Download size of Full Android SDK (Not Disk Size). On Disk : 49GB On Network (Downloaded Zip Files): ?GB Installed: Windows 7 x64 machine Tools till 24.3.1 Tool preview channel Android M Android API (22, 21,20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10,...

Create menu from button?

I would like to create menu where I can select how to sort posts. On iOS exists something like this: It's something similiar on Android? Or can give me advice which component I should use to solve my task? My app:...

Want to perform an action on a button press rather than a button click

I need to execute some code upon the press of a button, but right now I have and can only find information on executing code upon the click of a button (press and let go). How can I set a press listener or something like this? This is what I...

Trouble implementing android_serialport_api into my own application

I am currently working on an embedded system for my company that runs the android 4.2 OS (from TI bbb source) on the Beaglebone black. I have been tasked with setting up communication with the serial port (UART). I have been able to configure the serial port and run the...

Android device monitor seems to miss crashes

At seemingly random occasions it looks like Log cat in Device monitor bundled with Android studio misses error messages. I have an app that crashed on different errors, Index out of bounds to mention one. At some occasions this crash was shown in the log, at other occasions it showed...

Cannot resolve symbols setAdapter and AttachToListView in Android Studio

I was attaching the list view to FAB, but Android Studio is showing the following error: cannot resolve symbol at setAdapter and AttachToListView methods I tried rebuilding and closing and reopening the project. Code: public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } String[]...

If I change ID of an element in Android Studio, how do I carry on this change throughout the code?

For example, say I'm using a relative layout and a lot of views are centered around a TextView with ID of TextView. If I change this ID to TextView1, the other elements referencing it all break. How can I change the ID so that the changes are carried out? Thanks...

Android Studio manifest Errors

Could anyone please me as when ever I try to run my app I get errors in the manifest file such as the followig five errors below. Error:(2) No resource identifier found for attribute 'versioncode' in package 'android' Error:(2) No resource identifier found for attribute 'versionname' in package 'android' Error:(9)...

PDF file path is incorrect [duplicate]

This question already has an answer here: Android - Access file from assets \ PDF display 4 answers I want to open a PDF file in my application but something goes wrong everytime. Yeah , I watched many topics about it, however none of them helped me. Here are...

Simple Android Studio TextView Code Using Java

I am trying to create a TextView in Android Studio using the code on their reference (I already know I can use XML but I am trying to learn java). My code doesn't work and I can't figure out why. I look just like the code on the reference. I...

Invisible folders in Android Studio Project view

I have recently switched to Android Studio and try to migrate an ADT project. In the app/src/main/res/ directory I have the values, values-v11 and values-v14 folder. But in the Studio's Project view only the "values" folder is displayed. Why? How to resolve this?

Team explorer for android studio like visual studios [on hold]

Is there any plugin for android studio that would enable 2 computers running android studio to run the same project and synchronize the files whensoever its edited on one computer to both of them? If not,can we use git to do the same ?

Android _ failed for task ':app:packageAllDebugClassesForMultiDex' _ AbstractDateTime.class?

My Project was working fine, when I have added bellow code in my project get me error, I add : compile 'joda-time:joda-time:2.7' compile 'net.danlew:android.joda:2.8.0' Here is my build.gradle : apply plugin: '' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "" minSdkVersion 14 targetSdkVersion 22 versionCode 1 versionName "1.0"...

Android studio gradle flavor dimensions build varients not working correctly

I have two dimensions of an app, call then green and blue. There will only be these two dimensions but an unlimited number of product flavors. This is the way I'm setting it up in gradle flavorDimensions "green", "blue" productFlavors { one { applicationId "" versionCode 1 versionName ""; flavorDimension...

Error:(12) No resource identifier found for attribute 'scalteType' in package 'android'

Getting error messages when running an app on debug mode during the Gradle Build in Android Studio. This is the error message: Information:Gradle tasks [:app:assembleDebug] :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72211Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42211Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig...

Logcat goes crazy on Android Studio

Since version 1.2.2 of Android Stduio, LogCat doesnt appear to be able to only filter the output messages of my app. Instead, it filters all my device messages. I have Log level "Debug" and "Show only selected application" enabled. Here's a screenshot of my LogCat: Edit: why I'm being...

How to download a library dependence on gradle for external use?

I have a project on PhoneGap and I am trying to build a plugin to use a FilePicker library. So, I build one Android Studio Project and I have it working. So, right now, that I know that I know how to do it, I just need to know how...

Error execute unrecognized vm option 'MaxPermSize=350m' on Ubuntu 14.04

Error to Execute/Install on Ubuntu: [email protected]:~$ cd android-studio/bin [email protected]:~/android-studio/bin$ ./ Unrecognized VM option 'MaxPermSize=350m' Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. And with some knowledge after searching on search engines, I open the studio.vmoptions file in edit mode and...

Install Ultimate edition IntelliJ plugins in Android Studio

I have Ultimate edition of IntelliJ Idea w/ a valid licence. There is a very useful plugin only available in full edition named Database Tools and SQL support that allows the developer to browse and run queries on sqlite database stored in phone. Now i need to use this plugin...

Countdown Timer Notification

I'm begginer in Android programming, I have to do a CountdownTimer that starts from a number selected by the user using a two number pickers (one for Hours and other for minutes). The characteristics must be: -The CountdownTimer must work in background and notify the user when it arrives to...

PNG transparent backgrounds appearing black when using Android Studio

The social icons below (for fb, twitter, mail and share) are circular PNGs with transparent backgrounds. When I use the code and exact same images in Eclipse, I get transparent background but when build and run with Android Studio, I get black backgrounds. See details below. Images are the same....

app crashes with no input while using Edittext in android studio

I am having this issue with Edittext in android studio.The app works fine but app crashes with no input Here is the java code public void onButtonClick (View v) { int num1,num2,sum; EditText e1 = (EditText)findViewById(; EditText e2 = (EditText)findViewById(; TextView t1 = (TextView)findViewById(; num1 = Integer.parseInt(e1.getText().toString()); num2 = Integer.parseInt(e2.getText().toString());...

Android Studio HAXM not working

I want to use android studio on a hp with E2 AMD vision processor. The problem is that when I download the HAXM installer from the SDK manager and try to install it I get an error saying that my computer does not support this program. I went to the...

Cant start developing for android

I have an app on iOS and now i need an android version. BUT I CANT. I downloaded android studio, downloaded everything from SDK manager, did everything for a basic project. But... Everything i use is deprecated. Tried making tabbed application... ActionBarActivity deprecated, every other thing i trie is deprecated......