无法启动活动(java.lang.RuntimeException)

时间:2017-07-18 13:32:30

标签: android

我正在开发一个Android应用程序,虽然它没有编译错误,但在启动它时没有响应。我尝试了几件事,但都没有。当我添加第二个活动时,这个问题就开始了,但我已经尝试删除它,但它仍然失败。

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="xxx.xxxx.xxx">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:debuggable="false"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
           <receiver
               android:name="xxx.xxx.xxx.Monitor"
               android:enabled="true"
               android:permission="android.permission.RECIEVE_BOOT_COMPLETED" >
                  <intent-filter>
                      <action android:name="android.intent.action.BOOT_COMPLETED" />
                      <category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </receiver>
        <activity android:name="com.xxx.xxx.MainActivity"
                android:configChanges= "orientation|screenSize"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>
        <activity android:name="com.xxx.xxx.Ajustes"
            android:configChanges= "orientation|screenSize"
            android:label="@string/app_name">
        </activity>
    </application>
</manifest>

摇篮

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "xxx.xxxx.xxx"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'com.android.support:design:26.+'
}

logcat的一部分;

07-18 12:36:05.414 3649-3649/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: xxx.xxx.xxx, PID: 3649
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx/com.xxx.xxx.MainActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
                                                     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:866)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                  Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
                                                     at com.android.internal.policy.PhoneWindow.requestFeature(PhoneWindow.java:338)
                                                     at android.app.Activity.requestWindowFeature(Activity.java:3946)
                                                     at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:52)
                                                     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:866) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

异常引用的行是

 requestWindowFeature(Window.FEATURE_NO_TITLE);

但是评论它或改变它的可能性并没有解决问题。

MainActivity:

public class MainActivity extends Activity
{
    static WebView web;
    static String etiqueta;
    static String mensaje;
    static String si;
    Context context=this;
    static SharedPreferences datos;
    ImageButton boton;
    static boolean paisES;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);


        web = (WebView) findViewById(R.id.webV);

        paisES =("ES".equals(Locale.getDefault().getCountry())|| "es".equals(Locale.getDefault().getLanguage()));


        //Verificar conexión

        if (Conectividad.conectado(this))
        {
            if(paisES)
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=es_ES";
            }
            else
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=en_US";
            }
        }
        else
        {
            if(paisES)
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=es_ES";
                mensaje="No tienes conexión ¿Deseas configurar tu conexión a Wi-fi ahora?";
                si="Sí";
            }
            else
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=en_US";
                mensaje="You have no connection. Do you want to configure your Wi-Fi connection?";
                si="Yes";
            }
            dialogWifi(web);
        }
        //si hay un ID metido, entra directamente al mismo. Si no, va al launcher
        if (Leer("ID").equals("vacío")==false)
        {
            //SEGUIDA DE LA EJECUCIÓN PREVIA
            if ("ES".equals(Locale.getDefault().getCountry()))
            {
                //mensaje = "¿Quieres seguir la ejecución desde el punto en el que lo dejaste?";
                //si = "Sí";
                //leemos el fichero para saber si hay datos de ejecuciones previas
                etiqueta="https://www.xxx.xx/xxx/"+Leer("ID")+"/?mode=autoplay&language=es_ES";

            }
            else
            {
                // mensaje = "Do you want to continue the execution from the point you left it?";
                //si = "Yes";
                etiqueta="https://www.xxx.xx/player/"+Leer("ID")+"/?mode=autoplay&language=en_US";
            }
            // dialReanudar(web);
        }

        web=(WebView)findViewById(R.id.webV);
        GestionWeb.CrearWeb(etiqueta, web);
        GestionWeb.Seguirweb(web);

        //Para acelerar el webView
        web.getSettings().setCacheMode(web.getSettings().LOAD_NO_CACHE);
        web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    public void BotonAjustes()
    {
        View.OnClickListener aj= new  View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent intent= new Intent(MainActivity.this, Ajustes.class);
                startActivity(intent);
            }
        };
        boton= (ImageButton) findViewById(R.id.imageButton7);
        boton.setOnClickListener(aj);
    }
    /**
     * Método para preguntarle al usuario si desea configurar el wi-fi o no. en caso afirmativo, se le redirecciona a ajustes
     * @param view se necesitará para usar web
    */
    public void dialogWifi(View view)
    {
        AlertDialog.Builder dial= new AlertDialog.Builder(this);
        dial.setMessage(mensaje);
        dial.setPositiveButton(si, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                //Abre la configuración de Wi-fi
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                dialogInterface.cancel();
                web.reload();
            }
        });
        dial.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                dialogInterface.cancel();
            }
        });
        dial.create().show();
    }

    public void dialReanudar(View view)
    {
        AlertDialog.Builder dial= new AlertDialog.Builder(this);
        dial.setMessage(mensaje);
        dial.setPositiveButton(si, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                //En este caso, etiqueta tendrá la web leída
                etiqueta=Leer("enelace");
                GestionWeb.CrearWeb(etiqueta,web);
                dialogInterface.cancel();
            }
        });
        dial.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                dialogInterface.cancel();
            }
        });
        dial.create().show();
    }

    public static void Guardar(String guardado, String fichero)
    {
        SharedPreferences.Editor editor=datos.edit();
        editor.putString(fichero, guardado);
        editor.commit();
    }

    public static String Leer(String fichero)
    {
        String e=datos.getString(fichero, "vacío" ); //(valor que queremos recoger, valor por defecto si no encuentra nada)
        return e;
    }
}

1 个答案:

答案 0 :(得分:1)

您应该在requestWindowFeature(Window.FEATURE_NO_TITLE);

之前致电setContentView(R.layout.activity_main);

尝试以下方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    ...
}