0
votes

I have an app with thwo activities. The first Activity used Toolbar but the second Activity should use ActionBar. When I call the second Activity from the first the app takes off. What's the problem?

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.nikva.easyreading">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name=".FileManager"
        android:theme="@style/AppTheme"/>
    <activity
        android:name=".ReaderActivity"
        android:theme="@style/MainTheme"/>
</application>

styles:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:windowActionBar">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/White</item>
</style>

Xmlcode of sec Activity:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

<ProgressBar
    android:layout_gravity="center_horizontal|center_vertical"
    android:visibility="invisible"
    style="?android:attr/progressBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/pBar"/>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lin">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list"
        android:layout_gravity="bottom"/>

</LinearLayout>

error message:

03-02 22:06:38.980 6648-6648/com.example.nikva.easyreading E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.nikva.easyreading, PID: 6648 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nikva.easyreading/com.example.nikva.easyreading.FileManager}: 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:2695) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769) at android.app.ActivityThread.access$900(ActivityThread.java:177) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5910) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 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:203) at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:133) at com.example.nikva.easyreading.FileManager.onCreate(FileManager.java:52) at android.app.Activity.performCreate(Activity.java:6178) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)  at android.app.ActivityThread.access$900(ActivityThread.java:177)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5910)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

"fileManager.class"

    package com.example.nikva.easyreading;

/**
 * Created by nikva on 08.02.2017.
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by [email protected]
 * The class that responsible for the navigation of files(File Manager).
 * @author Nikita Vasko
 */
public class FileManager extends AppCompatActivity implements    AdapterView.OnItemClickListener {

ListView listOfDirs;
ArrayList<String> paths = new ArrayList<>();
String currentPath = "";
ProgressBar pBar;
Toolbar tBar;
final private String TAG = "myTags";
private static final String KEY_LIST = "LIST";
private static final String KEY_PATH = "CURRENT_PATH";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_file_manager);

    listOfDirs = (ListView) findViewById(R.id.list);
    listOfDirs.setOnItemClickListener(this);

    pBar = (ProgressBar) findViewById(R.id.pBar);

    tBar = (Toolbar) findViewById(R.id.tb);
    setSupportActionBar(tBar);


    Log.d(TAG, "Менеджер запущен.");
    if (savedInstanceState == null) {
        paths.add("/storage/emulated/0/");
        paths.add("/storage/extSdCard/");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
                paths);
        listOfDirs.setAdapter(adapter);//Creating a primary form of application
    }
    else{
        currentPath = savedInstanceState.get(KEY_PATH).toString();
        paths = savedInstanceState.getStringArrayList(KEY_LIST);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item,
                paths);
        listOfDirs.setAdapter(adapter);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList(KEY_LIST, paths);
    outState.putString(KEY_PATH, currentPath);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    String localPath = paths.get(position);

    if (localPath.equals("...")) {
        Log.d(TAG, "Переход на уровень ниже");
        upOnLevel();
    } else {
        transition(localPath);
    }
}

/**
 * Method performs transition to new directory.
 * @param currentDirectory - current directory or file that user selected.
 */
void transition(String currentDirectory){
    if (currentDirectory.equals(".android_secure")) {
        Toast.makeText(this, "Доступ закрыт.", Toast.LENGTH_SHORT).show();
        return;
    }
    if (new File(currentPath + currentDirectory).isFile()) {
        Intent intent;
        String pathToFile = currentPath + currentDirectory;

        if (pathToFile.contains(".txt")) {
            pBar.setVisibility(View.VISIBLE);

            intent = new Intent(this, ReaderActivity.class);
            intent.putExtra("PATH_TO_BOOK", pathToFile);
            startActivity(intent);

            pBar.setVisibility(View.INVISIBLE);
        }
        else {
            Toast.makeText(this, "Эта версия работает только с txt-файлами",
                    Toast.LENGTH_SHORT).show();
        }
    }
    else {
        if (currentPath.equals("")) {
            Log.d(TAG, "Создание пути в новое хранилище.");
            currentPath = currentDirectory;
        } else {
            Log.d(TAG, "Создание пути в новую директорию");
            currentPath = currentPath + currentDirectory + "/";
        }

        File file = new File(currentPath);
        Log.d(TAG, "Создание объекта File " + file.getPath());
        if (file.isDirectory()) {
            Log.d(TAG, "Выбрана директория");
            fill(file.list());
        } else {
            Log.d(TAG, "Выбран файл");
            return;
        }
    }
}

/**
 * Method performs transition to upper level.
 */
void upOnLevel(){
    //If user want to go to the first level then paths setting manually
    Log.d(TAG, "Проверка: на каком уровне находится приложение" + new File(currentPath).getParent());
    if (new File(currentPath).getParent().equals("/storage/emulated") ||
            new File(currentPath).getParent().equals("/storage")){
        Log.d(TAG, "Возвращаемся на первый уровень");
        String [] s  = {"/storage/emulated/0/", "/storage/extSdCard/"};
        currentPath = "";
        fill(s);
    } else{
        String path = new File(currentPath).getParent() + '/';
        currentPath = "";
        transition(path);
    }
}

/**
 * Method which fills ListView with new directories or files from directory that was selected
 * by user.
 * @param dirs - list of elements from new directory.
 */
void fill(String [] dirs){
    Log.d(TAG, "Заполнение ListView");
    paths.clear();

    if (!currentPath.equals("")){
        paths.add("...");
    }

    for (int i = 0; i < dirs.length; i++){
        paths.add(dirs[i]);
    }
    Log.d(TAG, "Создание адаптера");
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
            paths);
    listOfDirs.setAdapter(adapter);
}

}

 

1

1 Answers

1
votes

Problem is in your FileManager class set windowActionBar=false through style

in your Manifest:

<activity android:name=".FileManager"
      android:theme="@style/AppTheme.NoActionBar"> <!-- Define custom Style -->

in styles.xml

 <style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

As u want to use ActionBar supplied by the Activity there is no need for this lines:

 tBar = (Toolbar) findViewById(R.id.tb);
setSupportActionBar(tBar);      //remove this

instead use:

 ActionBar actionBar = getSupportActionBar();
 actionBar.show();