java – App without build errors is not responding

Question:

I am developing an app that, despite not having compilation errors, does not respond when trying to emulate it. I have tried to comment out parts of the code but the result has not changed. Therefore, I do not know where the problem could be. What could this be due to?

I add the manifest and Gradle just in case:

Manifest :

<?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>

Gradle:

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) 

the line of the main activity that you refer to there is

 requestWindowFeature(Window.FEATURE_NO_TITLE);

But I've tried commenting on it and it didn't work.

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);
        setContentView(R.layout.activity_main);

       // BotonAjustes();
        //Identificar la WebView con la variabe "web" que hemos creado
        web = (WebView) findViewById(R.id.webV);

        //identificar el país y el idioma para distintos diomas
        paisES =("ES".equals(Locale.getDefault().getCountry())|| "es".equals(Locale.getDefault().getLanguage()));

        //Para poner pantalla completa
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //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;
    }
}

It should be noted that the app started to give problems when adding a new activity .

Answer:

The problem you're having is that you're doing the requestWindowFeature() after the setContentView(); This is what is causing the error that appears in the Logcat:

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

As the Android documentation says for the requestWindowFeature() function

Enable extended screen features. This must be called before setContentView(). May be called as many times as desired as long as it is before setContentView(). If not called, no extended features will be available. You can not turn off a feature once it is requested. You can't use other title features with FEATURE_CUSTOM_TITLE.

Translation:

Enable extended display features. This must be called before setContentView(). It can be called as many times as you like, as long as it's before setContentView(). If it is not called, there will be no extended functions. A feature cannot be disabled once it is requested. You cannot use other title functions with FEATURE_CUSTOM_TITLE.

So your code should be changed to accomplish this as follows:

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

    setContentView(R.layout.activity_main);

    .....
}

EDIT:

Try to put the getWindow().setFlags(); before the setContentView() also since according to the documentation of setFlags() it indicates that:

Note that some flags must be set before the window decoration is created (by the first call to setContentView(View, android.view.ViewGroup.LayoutParams)

Translation:

Note that some flags need to be set before the window decoration is created (by the first call to setContentView(View, android.view.ViewGroup.LayoutParams)

Leaving your code as follows:

 @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);

        .....
    }
Scroll to Top