Change Activity theme programmatically dosen't work [duplicate] - android

This question already has answers here:
This Activity already has an action bar supplied by the window decor
(25 answers)
Closed 3 years ago.
I want change app theme from code but it doesn't work .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.NightMode);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar)
Errors
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.w7orld.animex, PID: 23421
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.w7orld.animex/com.w7orld.animex.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:345)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.w7orld.animex.MainActivity.onCreate(MainActivity.java:70)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I found way to do that. In onCreate i put this
setTheme(Designs.getThemeNoActionBar(this));
setContentView(R.layout.activity_main);
get the theme from shared preferences and return theme without actionbar.
public static int getThemeNoActionBar(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("Designs", Context.MODE_PRIVATE);
int theme = sharedPreferences.getInt("theme", R.style.AppTheme);
if (theme == nightModeTheme)
return R.style.NightMode_NoActionBar;
else if (theme == theme1)
return R.style.Theme1_NoActionBar;
else
return R.style.AppTheme_NoActionBar;
}
In style res
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="NightMode.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="Theme1.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>

We set the Night-mode like this:
public class App extends Application {
public static final String TAG = "App";
private boolean isNightModeEnabled = false;
#Override
public void onCreate() {
super.onCreate();
// We load the Night Mode state here
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
this.isNightModeEnabled = mPrefs.getBoolean(“NIGHT_MODE”, false);
}
public boolean isNightModeEnabled() {
return isNightModeEnabled;
}
public void setIsNightModeEnabled(boolean isNightModeEnabled) {
this.isNightModeEnabled = isNightModeEnabled;
}
}
As this instance will be launched before everything else, you will be able to call isNightModeEnabled() whenever you want and as such, in any Activity once your app is opened.
public final class FeedActivity extends AppCompatActivity {
private final static String TAG = “FeedActivity”;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (MyApplication.getInstance().isNightModeEnabled()) {
setTheme(R.style.FeedActivityThemeDark);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
}
}
How to work with night-mode in Android is posted here
Here is some example pictures showing the difference between cycling though light and night mode:

The first problem that's visible is the placement of these lines:
setTheme(R.style.NightMode);
setContentView(R.layout.activity_main);
You must always place the setContentView(layout) call immediately after the super.onCreate(savedInstanceState);. Because this is the code that's generating the layout and its views.

Related

Android app running on emulator not on real device

Android emulator is working when running the application but on a real device the app gets an error from the action bar. I am using android bumble bee and the device is a Samsung s21
I already have NoActionBar as well as windowNoTitle true and windowActionBar false
Here is my error
Process: com.example.wonderfinder, PID: 14427
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wonderfinder/com.example.wonderfinder.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4166)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4312)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2571)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8741)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:581)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:183)
at com.example.wonderfinder.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:8578)
at android.app.Activity.performCreate(Activity.java:8557)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4147)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4312) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2571) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:226) 
at android.os.Looper.loop(Looper.java:313) 
at android.app.ActivityThread.main(ActivityThread.java:8741) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067) 
2022-11-16 13:17:46.765 14427-14427/? I/Process: Sending signal. PID: 14427 SIG: 9
Here is my theme.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.WonderFinder" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryVariant">#color/primaryDarkColor</item>
<item name="android:colorPrimaryDark">#color/primaryColor</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/primaryColor</item>
<item name="colorSecondaryVariant">#color/primaryColor</item>
<item name="colorOnSecondary">#color/black</item>
<item name="android:textColorHint">#color/textColor</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<item name="android:navigationBarColor">#color/primaryColor</item>
<!-- Customize your theme here. -->
</style>
<style name="ActionBarTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- Primary brand color. -->
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryVariant">#color/primaryDarkColor</item>
<item name="android:colorPrimaryDark">#color/primaryColor</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/primaryColor</item>
<item name="colorSecondaryVariant">#color/primaryColor</item>
<item name="colorOnSecondary">#color/black</item>
<item name="android:textColorHint">#color/textColor</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<item name="android:navigationBarColor">#color/primaryColor</item>
<!-- Customize your theme here. -->
</style>
</resources>
Here is my main activity
package com.example.wonderfinder;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.wonderfinder.databinding.ActivityMainBinding;
import com.example.wonderfinder.databinding.NavDrawerLayoutBinding;
import com.example.wonderfinder.databinding.ToolbarLayoutBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
//Declare all variables as private variables with their respective types
private NavDrawerLayoutBinding navDrawerLayoutBinding;
private ActivityMainBinding activityMainBinding;
private ToolbarLayoutBinding toolbarLayoutBinding;
private FirebaseAuth firebaseAuth;
private TextView txtName, txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
navDrawerLayoutBinding = NavDrawerLayoutBinding.inflate(getLayoutInflater());
setContentView(navDrawerLayoutBinding.getRoot());
//Set the variables to their respective values
activityMainBinding = navDrawerLayoutBinding.mainActivity;
toolbarLayoutBinding = activityMainBinding.toolbar;
setSupportActionBar(toolbarLayoutBinding.toolbar);
firebaseAuth = FirebaseAuth.getInstance();
//Toggle the drawer with open and close
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, navDrawerLayoutBinding.navDrawer, toolbarLayoutBinding.toolbar,
R.string.open_navigation_drawer,
R.string.close_navigation_drawer
);
navDrawerLayoutBinding.navDrawer.addDrawerListener(toggle);
toggle.syncState();
NavController navController = Navigation.findNavController(this, R.id.fragmentContainer);
NavigationUI.setupWithNavController(navDrawerLayoutBinding.navigationView, navController);
View headerLayout = navDrawerLayoutBinding.navigationView.getHeaderView(0);
txtName = headerLayout.findViewById(R.id.txtHeaderName);
txtEmail = headerLayout.findViewById(R.id.txtHeaderEmail);
//Call getUserData method
getUserData();
}
//Close the nav the drawer on back pressed
#Override
public void onBackPressed() {
if (navDrawerLayoutBinding.navDrawer.isDrawerOpen(GravityCompat.START))
navDrawerLayoutBinding.navDrawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
//Method to populate the users username and email in the nav drawer
private void getUserData() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users")
.child(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
UserModel userModel = snapshot.getValue(UserModel.class);
txtName.setText(userModel.getUsername());
txtEmail.setText(userModel.getEmail());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I'm going to take a wild stab in the dark here and assume that you are using dark mode (night mode) on your device, but normal (day mode) on the emulator. Am I right??
See some of the answers in this related question: This Activity already has an action bar supplied by the window decor?

Error inflating class Button Android studio

I am working on an app in Android Studio, and after adding buttons to MainActivity to move to other activities, despite the fact that the layout shows up properly in the editor, I get the error which will be posted at the end. There are other activities in my project which I did not include, because the error refers to activity_main.xml, but I will include them if they are necessary to solve the problem.
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/view_img_main_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#drawable/grocery_img_1" />
<Button
android:id="#+id/btn_inventory"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_below="#id/view_img_main_menu"
android:text="#string/btn_my_groceries_text"
android:theme="#style/BtnTheme" />
<Button
android:id="#+id/btn_shopping_list"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_below="#id/btn_inventory"
android:text="#string/btn_shopping_list_text"
android:theme="#style/BtnTheme" />
</RelativeLayout>
Here is MainActivity:
public class MainActivity extends AppCompatActivity {
private Button btnInventory;
private Button btnShopList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInventory = findViewById(R.id.btn_inventory);
btnShopList = findViewById(R.id.btn_shopping_list);
btnInventory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent inventoryIntent = new Intent(MainActivity.this, Inventory.class);
startActivity(inventoryIntent);
}
});
btnShopList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shopListIntent = new Intent(MainActivity.this, ShoppingList.class);
startActivity(shopListIntent);
}
});
}
Here is the error I get awhen I try to run the code:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.grocerystatusapplication/com.example.grocerystatusapplication.MainActivity}: android.view.InflateException: Binary XML file line #15 in com.example.grocerystatusapplication:layout/activity_main: Binary XML file line #15 in com.example.grocerystatusapplication:layout/activity_main: Error inflating class Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3344)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3488)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
at android.os.Handler.dispatchMessage(Han
E/AndroidRuntime: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)
Here is styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowBackground">#color/colorLayoutBackground</item>
</style>
<style name="BtnTheme" parent="TextAppearance.AppCompat.Widget.Button.Colored">
<item name="colorButtonNormal">#color/colorViewBackground</item>
</style>
<style name="TextViewTheme" parent="">
<item name="android:background">#drawable/rounded_corners</item>
<item name="android:textColor">#android:color/white</item>
</style>
I have tried changing the attributes of the Button that the error refers to (line 15, btn_inventory), but I did not get anywhere. Did not come across this error before and don't really understand what is the problem. What can I change to make it work? After looking through posts about the same error, I did not get an answer to my question, there seemed to be a quite a few reasons this error came up.
In both Button tags change
android:theme="#style/BtnTheme"
to
style="#style/BtnTheme"

#90: Error inflating class ImageButton

I am using NoNonsense-FilePicker for filtering the sd card for pdf files by extending the FilePickerActivity and creating a FilteredFilePickerFragment instance through it but i get an error related to an Image button in it's resources.
this is the File Picker Fragment Extender:
public class FilePickerFragmentExtender extends FilePickerActivity {
public FilePickerFragmentExtender() {
super();
}
#Override
protected AbstractFilePickerFragment<File> getFragment(#Nullable String startPath, int mode, boolean allowMultiple, boolean allowCreateDir, boolean allowExistingFile, boolean singleClick) {
AbstractFilePickerFragment<File> fragment = new FilteredFilePickerFragment();
// startPath is allowed to be null. In that case, default folder should be SD-card and not "/"
fragment.setArgs(startPath != null ? startPath : Environment.getExternalStorageDirectory().getPath(),
mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick);
return fragment;
}
}
and this is the Filtered File Picker Fragment:
public class FilteredFilePickerFragment extends FilePickerFragment {
private static final String TAG = "FilteredFilePickerFragm";
// File extension to filter on
private static final String EXTENSION = ".pdf";
public FilteredFilePickerFragment() {
super();
}
/**
* #param file
* #return The file extension. If file has no extension, it returns null.
*/
private String getExtension(#NonNull File file) {
String path = file.getPath();
int i = path.lastIndexOf(".");
if (i < 0) {
return null;
} else {
return path.substring(i);
}
}
#Override
protected boolean isItemVisible(final File file) {
boolean ret = super.isItemVisible(file);
if (ret && !isDir(file) && (mode == MODE_FILE || mode == MODE_FILE_AND_DIR)) {
String ext = getExtension(file);
return ext != null && EXTENSION.equalsIgnoreCase(ext);
}
return ret;
}
}
the error:
FATAL EXCEPTION: main
Process: com.pdfviewer.debug, PID: 15693
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pdfviewer.debug/com.pdfviewer.FilePickerFragmentExtender}: android.view.InflateException: Binary XML file line #90: Binary XML file line #90: Error inflating class ImageButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.view.InflateException: Binary XML file line #90: Binary XML file line #90: Error inflating class ImageButton
Caused by: android.view.InflateException: Binary XML file line #90: Error inflating class ImageButton
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f010031 a=-1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:528)
at android.widget.ImageView.<init>(ImageView.java:180)
at android.widget.ImageButton.<init>(ImageButton.java:84)
at android.widget.ImageButton.<init>(ImageButton.java:80)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1026)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1083)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.nononsenseapps.filepicker.AbstractFilePickerFragment.inflateRootView(AbstractFilePickerFragment.java:239)
at com.nononsenseapps.filepicker.AbstractFilePickerFragment.onCreateView(AbstractFilePickerFragment.java:165)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
com.pdfviewer.debug E/AndroidRuntime: at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:554)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
at android.app.Activity.performStart(Activity.java:6701)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
I searched and found that it's related to the theme of the file-picker but also i didn't find anything wrong in the theme:
<style name="FilePickerTheme" parent="NNF_BaseTheme">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<!-- Setting a divider is entirely optional -->
<item name="nnf_list_item_divider">?android:attr/listDivider</item>
<!-- Need to set this also to style create folder dialog -->
<item name="alertDialogTheme">#style/FilePickerAlertDialogTheme</item>
</style>
<style name="FilePickerAlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
colorss.xml:
<color name="colorPrimary">#3f51b5</color>
<color name="colorPrimaryDark">#303f9f</color>
<color name="colorAccent">#5495fd</color>
The problem was actually related to the theme I am applying to the parent activity of this fragment android:theme="#style/AppTheme" was causing the app to crash because the layout wasn't finding it's appropriate attributes and debugging xml is kinda tricky.
The ImageButton in the resources:
<ImageButton
android:id="#+id/nnf_button_ok_newfile"
// this style line is the cause
style="?attr/borderlessButtonStyle"
android:layout_width="48dp"
android:layout_height="48dp"
android:hint="#android:string/ok"
app:srcCompat="#drawable/nnf_ic_save_black_24dp"
android:tint="?attr/nnf_save_icon_color"/>
and the solution to this problem was to either change your Activity theme in the manifest to android:theme="#style/FilePickerTheme" which is bad for user experience to user different themes between activities, or the other solution which is to Override the onCreate method and set the theme before the creation of the activity happens as follows:
FilteredFilePickerFragment
#Override
public void onCreate(Bundle savedInstanceState) {
getActivity().setTheme(R.style.FilePickerTheme);
super.onCreate(savedInstanceState);
}

Error when trying to extend as BaseActivity

I am trying to create a Nav Drawer Activity as a Base Activity. I did something like below.
When i ran it, I got below error.
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.bugmanagement.pankaj.androidexample, PID: 2297
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.bugmanagement.pankaj.androidexample/com.bugmanagement.pankaj.androidexample.Activities.UserManagement.Auth.LoginActivity}:
java.lang.IllegalStateException: This Activity already has an action
bar supplied by the window decor. Do not request
Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in
your theme to use a Toolbar instead. at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:154) at
android.app.ActivityThread.main(ActivityThread.java:6077) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: This Activity already has
an action bar supplied by the window decor. Do not request
Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in
your theme to use a Toolbar instead. at
android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:199)
at
android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:133)
at
com.bugmanagement.pankaj.androidexample.Activities.UserManagement.BaseActivity.onCreate(BaseActivity.java:31)
at
com.bugmanagement.pankaj.androidexample.Activities.UserManagement.Auth.LoginActivity.onCreate(LoginActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6662) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java)  at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102)  at
android.os.Looper.loop(Looper.java:154)  at
android.app.ActivityThread.main(ActivityThread.java:6077)  at
java.lang.reflect.Method.invoke(Native Method)  at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
style.xml is below
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
styles.xml(v21)
<resources>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
</resources>
Main Activity
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Base Activity
public class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.base, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is the issue :
This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
You are using a theme with action bar and at the same time in your xml a Toolbar is use and set like actionbar.
Change the parent of your AppTheme with a theme without actionbar for exemple in your style.xml :
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar" >
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<!-- your item here -->
</style>
EDIT:
For the nav icon
in your activity be sure to have somethong like that:
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_closed);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
//your code
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
Hope this helps.
Sorry for my english.
Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set
windowActionBar to false in your theme
Here is the origin of your problem , and it is happened because you set <item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
in the activity you are setting toolbar as a actionBar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
remove this line <item name="windowActionBar">false</item> from your style.xml file
you can use this piece of code for no action bar theme styling . add this code in your style file
<style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primary_dark</item>
<item name="colorAccent">#color/accent</item>
<item name="android:windowBackground">#color/primary</item>
<item name="colorControlNormal">#color/iron</item>
<item name="colorControlActivated">#color/white</item>
<item name="colorControlHighlight">#color/white</item>
<item name="android:textColorHint">#color/iron</item>
<item name="colorButtonNormal">#color/primary_darker</item>
<item name="android:colorButtonNormal" tools:targetApi="lollipop">#color/primary_darker</item>
<item name="android:typeface">monospace</item>
<item name="preferenceTheme">#style/PreferenceThemeOverlay</item>
</style>

NullPointerException at ActionBarImplICS (using app compat) on long-press

NullPointerException when long-press over field
compile 'com.android.support:appcompat-v7:19.1.+'
XML
<EditText
android:id="#+id/field"
style="#style/Field"
android:textSize="20sp"
android:hint="#string/hint"
android:nextFocusDown="#+id/other"/>
Style
<style name="Field" parent="Theme.AppCompat.Light">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">14sp</item>
<item name="android:textColor">#color/blue</item>
<item name="android:singleLine">true</item>
<item name="android:gravity">center_vertical</item>
<item name="android:inputType">textCapCharacters|textNoSuggestions</item>
<item name="android:imeOptions">actionNext</item>
<item name="android:popupBackground">#color/white</item>
</style>
LogCat
java.lang.NullPointerException
at android.support.v7.app.ActionBarImplICS.getThemedContext(ActionBarImplICS.java:302)
at android.support.v7.app.ActionBarImplJB.getThemedContext(ActionBarImplJB.java:20)
at android.support.v7.app.ActionBarActivityDelegate.getActionBarThemedContext(ActionBarActivityDelegate.java:208)
at android.support.v7.app.ActionBarActivityDelegateICS.onActionModeStarted(ActionBarActivityDelegateICS.java:195)
at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onActionModeStarted(ActionBarActivityDelegateICS.java:359)
at com.android.internal.policy.impl.PhoneWindow$DecorView.startActionMode(PhoneWindow.java:2437)
at com.android.internal.policy.impl.PhoneWindow$DecorView.startActionModeForChild(PhoneWindow.java:2362)
at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:665)
at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:665)
at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:665)
at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:665)
at android.view.View.startActionMode(View.java:4554)
at android.widget.Editor.startSelectionActionMode(Editor.java:1551)
at android.widget.Editor.performLongClick(Editor.java:859)
at android.widget.TextView.performLongClick(TextView.java:8373)
at android.view.View$CheckForLongPress.run(View.java:18441)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The ActionBar is null. That's because you're using an activity without a title (and thus also without an actionbar):
requestWindowFeature(Window.FEATURE_NO_TITLE);
There are two ways to fix it.
Simple:
Make YourActivity NOT extends ActionBarActivity but normal Activity.
More difficult:
Make transparent ActionBar with no title, no icon, no home button etc. How to do this? First, define ActionBar style and new theme that extends YourAppTheme:
<!-- Your App Theme-->
<style name="YourAppTheme.Light" parent="#style/Theme.AppCompat.Light">
<...>
</style>
<!-- Transparent ActionBar Style -->
<style name="YourAppTheme.Light.ActionBar.Transparent" parent="#style/Widget.AppCompat.Light.ActionBar">
<item name="android:background">#android:color/transparent</item>
<item name="background">#android:color/transparent</item>
</style>
<!-- Fullscreen Activity Theme -->
<style name="YourAppTheme.FullScreen.Light" parent="#style/YourAppTheme.Light">
<item name="android:actionBarStyle">#style/YourAppTheme.Light.ActionBar.Transparent</item>
<item name="actionBarStyle">#style/YourAppTheme.Light.ActionBar.Transparent</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
Next, set this theme to your fullscreen activity:
<activity
android:name="your.package.name.YourFullscreenActivity"
android:label="#string/app_name"
android:theme="#style/YourAppTheme.FullScreen.Light" />
Finally, add following lines to YourFullscreenActivity#onCreate method:
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
I hope it will help.
I think I have a better solution to this issue.
Remove requestWindowFeature(Window.FEATURE_NO_TITLE); from activity and <item name="android:windowNoTitle">true</item> from activity theme.
To your activity code add:
To onCreate() method
View actionBar = getActionBarView();
if (actionBar != null) {
actionBar.setVisibility(View.GONE);
}
To activity class:
public View getActionBarView() {
Window window = getWindow();
View v = window.getDecorView();
int resId;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
resId = getResources().getIdentifier(
"action_bar_container", "id", getPackageName());
} else {
resId = Resources.getSystem().getIdentifier(
"action_bar_container", "id", "android");
}
if (resId != 0) {
return v.findViewById(resId);
} else {
return null;
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
super.onSupportActionModeStarted(mode);
View actionBar = getActionBarView();
if (actionBar != null) {
actionBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
super.onSupportActionModeFinished(mode);
View actionBar = getActionBarView();
if (actionBar != null) {
actionBar.setVisibility(View.GONE);
}
}
This is remove action bar and at the same time allows you to manipulate text in edit text with action mode buttons.
Cheers
The second solution to the above answer works, but causes the top row that would have been covered by the actionbar to be unclickable. Set the height item to zero in the actionbar style to solve this issue:
<item name="android:height">0dp</item>
I think erakitin is a VERY good answer, and quiet simple if you take the "DO NOT extend ActionBarActivity, but in case anyone needs or want to avoid making that change, I'm leaving another answer which I think is also very simple and solves the problem PERFECTLY.
Try adding this to your activity's theme.
<item name="android:windowActionBar">false</item>
public class MainActivity extends ActionBarActivity
Change to:
public class MainActivity extends Activity

Categories

Resources