Error with Text View

1

my codigo throws an error when I define the id of TextView .

    package com.david.animefm2;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.CollationElementIterator;
import java.util.ArrayList;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

import static android.R.drawable.ic_media_play;


public class MainActivity extends Activity {

    private ArrayList radios;
    private RadioAdapter adapter;
    private ListView lvRadios;
    private String url ="";
    private String txt = "";
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private AdView mAdView;

    TextView titulo = (TextView)findViewById(R.id.etRadio);
    //TextView texto = (TextView) findViewById(R.id.etRadio);

    //noti
    // Variables de la notificacion
    NotificationManager nm;
    Notification notif;
    static String ns = Context.NOTIFICATION_SERVICE;

    //Defino los iconos de la notificacion en la barra de notificacion
    int icono_v = R.drawable.animelayer;
    int icono_r = R.drawable.radioanime;

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


        //config
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        MobileAds.initialize(this, "ca-app-pub-9173335460606469/5989305154");
        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
                Log.i("Ads", "onAdLoaded");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
                Log.i("Ads", "onAdFailedToLoad");
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
                Log.i("Ads", "onAdOpened");
            }

            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
                Log.i("Ads", "onAdLeftApplication");
            }

            @Override
            public void onAdClosed() {
                // Code to be executed when when the user is about to return
                // to the app after tapping on an ad.
                Log.i("Ads", "onAdClosed");
            }
        });

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.start);
        //variables
        radios = new ArrayList<radio>();
        rellenarArrayList();
        adapter = new RadioAdapter(this, radios);
        lvRadios = (ListView) findViewById(R.id.lvRadeo);
        lvRadios.setAdapter(adapter);

        //Lista
        ListView lista = (ListView) findViewById(R.id.lvRadeo);
        lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                SetUrl(i);
            }
        });

        // Inicio el servicio de notificaciones accediendo al servicio
        nm = (NotificationManager) getSystemService(ns);

        // Realizo una notificacion por medio de un metodo hecho por mi
        notificacion(icono_r, "titulo contenido", "texto contenido", "texto extendido");

        //BOTON FLOTANTE

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()){
                    //metodo de pausa
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                } else {
                    BotonReproducir();
                }
            }
        });
    }

    //Nombre y icono
    private void rellenarArrayList() {
        radios.add(new radio("Radio Vocaloid", R.drawable.radiovocaloid));
        radios.add(new radio("Radio Anime", R.drawable.radioanime));
        radios.add(new radio("Anime Layer", R.drawable.animelayer));
        radios.add(new radio("Anime Radio SU", R.drawable.radioanimesu));
        radios.add(new radio("canario", R.drawable.ic_home_black_24dp));
        radios.add(new radio("cerdo", R.drawable.ic_home_black_24dp));
        radios.add(new radio("delfin", R.drawable.ic_home_black_24dp));
        radios.add(new radio("gato", R.drawable.ic_home_black_24dp));
        radios.add(new radio("iguana", R.drawable.ic_home_black_24dp));
        radios.add(new radio("lince", R.drawable.ic_home_black_24dp));
        radios.add(new radio("lobo", R.drawable.ic_home_black_24dp));
        radios.add(new radio("morena", R.drawable.ic_home_black_24dp));
        radios.add(new radio("orca", R.drawable.ic_home_black_24dp));
        radios.add(new radio("perro", R.drawable.ic_home_black_24dp));
        radios.add(new radio("vaca", R.drawable.ic_home_black_24dp));

    };
    //Urls
    private void seturl(int i) {
        switch (i) {
            case 0:
                url= "http://curiosity.shoutca.st:8019/stream"; //Radio Vocaloid
                txt = "Radio Vocaloid";
                break;
            case 1:
                url="http://perseus.shoutca.st:9253/stream"; //Radio Anime
                txt = "Radio Anime";
                break;
            case 2:
                url="http://animelayer.ru:5190/play"; //Anime Layer
                txt = "Anime Layer";
                break;
            case 3:
                url="http://animeradio.su:8000"; //Radio Anime SU
                txt = "Radio Anime SU";
                break;
        };
        titulo.setText(txt);
        BotonReproducir();
    }

    private void SetUrl(int i){
        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        Toast.makeText(getApplicationContext(), "posicion " + (i), Toast.LENGTH_SHORT).show();
        seturl(i);
    }

    private void BotonReproducir() {
        if (url != "") {
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer arg0) {
                    //Inicia reproducción.
                    mediaPlayer.start();
                    Toast.makeText(getApplicationContext(),"Bufering...", Toast.LENGTH_LONG ).show();
                    // Lanzo la notificacion creada en el paso anterior
                    nm.notify(1, notif);
                    //fab.setImageResource(R.drawable.ic_media_play);
                }
            });
        } else {
            Toast.makeText(getApplicationContext(),"Select a rario", Toast.LENGTH_SHORT).show();
        }
    }
    //notificacion

    public void notificacion(int icon, CharSequence textoEstado, CharSequence titulo, CharSequence texto) {
        // Capturo la hora del evento
        long hora = System.currentTimeMillis();

        // Definimos la accion de la pulsacion sobre la notificacion (esto es opcional)
        Context context = getApplicationContext();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        // Defino la notificacion, icono, texto y hora
        notif = new Notification(icon, "Holaaaaa", hora);
       // notif.(getApplicationContext(), "Old title", "Old notification content text", PendingIntent.getActivity(mContext, 0, new Intent(), 0));
        //Defino que la notificacion sea permamente
            //notif.flags = Notification.FLAG_ONGOING_EVENT;
    }


    @Override
    public void onResume() {
        super.onResume();
        Toast.makeText(getApplicationContext(),"7. onResume()", Toast.LENGTH_SHORT).show();
        nm.cancel(1);
    }
    @Override
    public void onDestroy() {
        super.onResume();
        Toast.makeText(getApplicationContext(),"7. onResume()", Toast.LENGTH_SHORT).show();
        nm.cancel(1);
    }

    public void onPause() {
        super.onResume();
        Toast.makeText(getApplicationContext(),"7. onResume()", Toast.LENGTH_SHORT).show();
        nm.notify(1, notif);
    }


}


<?xml version="1.0" encoding="utf-8"?>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    app:adSize="BANNER"
    app:adUnitId="ca-app-pub-9173335460606469/5989305154"></com.google.android.gms.ads.AdView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/tvNumCelda"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:text="       BETA" />

    <ListView
        android:id="@+id/lvRadeo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tvNumCelda"
        android:layout_marginBottom="65dp"
        android:layout_marginTop="50dp"
        android:cacheColorHint="@color/common_google_signin_btn_text_dark_pressed"
        android:clickable="true" />

</LinearLayout>

<LinearLayout
    android:id="@+id/star"
    android:layout_width="match_parent"
    android:layout_height="65dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_weight="0.50"
        android:visibility="visible"
        app:srcCompat="@drawable/radioanimesu" />

    <TextView
        android:id="@+id/etRadio"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="25dp"
        android:layout_weight="1"
        android:text="Select a radio station"
        android:textAlignment="center" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/start"
        android:layout_width="67dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:clickable="true"
        app:backgroundTint="@color/colorPrimary"
        app:fabSize="mini"
        android:src="@android:drawable/ic_media_play"/>

</LinearLayout>

  

10-05 16: 15: 44.195 26479-26479 / com.david.animefm2 E / AndroidRuntime: FATAL EXCEPTION: main                                                                       Process: com.david.animefm2, PID: 26479                                                                       java.lang.RuntimeException: Unable to instantiate activity ComponentInfo {com.david.animefm2 / com.david.animefm2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method android.view.View android.view.Window. findViewById (int) 'on a null object reference                                                                           at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2849)                                                                           at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3045)                                                                           at android.app.ActivityThread.-wrap14 (ActivityThread.java)                                                                           at android.app.ActivityThread $ H.handleMessage (ActivityThread.java:1642)                                                                           at android.os.Handler.dispatchMessage (Handler.java:102)                                                                           at android.os.Looper.loop (Looper.java:154)                                                                           at android.app.ActivityThread.main (ActivityThread.java:6776)                                                                           at java.lang.reflect.Method.invoke (Native Method)                                                                           at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:1520)                                                                           at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)                                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById (int)' on a null object reference                                                                           at android.app.Activity.findViewById (Activity.java:2457)                                                                           at com.david.animefm2.MainActivity. (MainActivity.java:45)                                                                           at java.lang.Class.newInstance (Native Method)                                                                           at android.app.Instrumentation.newActivity (Instrumentation.java:1086)                                                                           at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2839)                                                                           at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3045)                                                                           at android.app.ActivityThread.-wrap14 (ActivityThread.java)                                                                           at android.app.ActivityThread $ H.handleMessage (ActivityThread.java:1642)                                                                           at android.os.Handler.dispatchMessage (Handler.java:102)                                                                           at android.os.Looper.loop (Looper.java:154)                                                                           at android.app.ActivityThread.main (ActivityThread.java:6776)                                                                           at java.lang.reflect.Method.invoke (Native Method)                                                                           at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:1520)                                                                           at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

    
asked by Djdadi43 05.10.2017 в 16:26
source

3 answers

1

The error is:

  

Caused by: java.lang.NullPointerException: Attempt to invoke virtual   method 'android.view.View android.view.Window.findViewById (int)' on a   null object reference at   android.app.Activity.findViewById (Activity.java:2457) at   com.david.animefm2.MainActivity.

You need a context to get the reference of the view, this definition must be done within the onCreate() method:

  TextView titulo = (TextView)findViewById(R.id.etRadio);      

It would be done in this way since the instance of TextView also use it in other methods:

    //TextView titulo = (TextView)findViewById(R.id.etRadio);
   private TextView titulo;

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

    titulo = (TextView)findViewById(R.id.etRadio);

   ...
   ...
    
answered by 05.10.2017 / 17:00
source
0

You are trying to instantiate the view in the variable zone, also the notification variables and the drawables, transfer that code to the onCreate zone of your class:

 TextView titulo = (TextView)findViewById(R.id.etRadio);

TextView titulo = (TextView)findViewById(R.id.etRadio);
//TextView texto = (TextView) findViewById(R.id.etRadio);

//noti
// Variables de la notificacion
NotificationManager nm;
Notification notif;
static String ns = Context.NOTIFICATION_SERVICE;

//Defino los iconos de la notificacion en la barra de notificacion
int icono_v = R.drawable.animelayer;
int icono_r = R.drawable.radioanime;

It would stay like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView titulo = (TextView)findViewById(R.id.etRadio);
    //noti
    // Variables de la notificacion
    NotificationManager nm;
    Notification notif;
    static String ns = Context.NOTIFICATION_SERVICE;

//Defino los iconos de la notificacion en la barra de notificacion
int icono_v = R.drawable.animelayer;
int icono_r = R.drawable.radioanime;

    //config
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    MobileAds.initialize(this, "ca-app-pub-9173335460606469/5989305154");
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    mAdView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // Code to be executed when an ad finishes loading.
            Log.i("Ads", "onAdLoaded");
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            // Code to be executed when an ad request fails.
            Log.i("Ads", "onAdFailedToLoad");
        }

        @Override
        public void onAdOpened() {
            // Code to be executed when an ad opens an overlay that
            // covers the screen.
            Log.i("Ads", "onAdOpened");
        }

        @Override
        public void onAdLeftApplication() {
            // Code to be executed when the user has left the app.
            Log.i("Ads", "onAdLeftApplication");
        }

        @Override
        public void onAdClosed() {
            // Code to be executed when when the user is about to return
            // to the app after tapping on an ad.
            Log.i("Ads", "onAdClosed");
        }
    });

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.start);
    //variables
    radios = new ArrayList<radio>();
    rellenarArrayList();
    adapter = new RadioAdapter(this, radios);
    lvRadios = (ListView) findViewById(R.id.lvRadeo);
    lvRadios.setAdapter(adapter);

    //Lista
    ListView lista = (ListView) findViewById(R.id.lvRadeo);
    lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView adapterView, View view, int i, long l) {
            SetUrl(i);
        }
    });

    // Inicio el servicio de notificaciones accediendo al servicio
    nm = (NotificationManager) getSystemService(ns);

    // Realizo una notificacion por medio de un metodo hecho por mi
    notificacion(icono_r, "titulo contenido", "texto contenido", "texto extendido");

    //BOTON FLOTANTE

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mediaPlayer.isPlaying()){
                //metodo de pausa
                mediaPlayer.stop();
                mediaPlayer.reset();
            } else {
                BotonReproducir();
            }
        }
    });
}
    
answered by 05.10.2017 в 17:04
-1

In the activities, the views have to be initialized within the onCreate() method. There are these declaring and initializing the views in the class, that's why the error. The variables can be declared in the class and initialized in the method OnCreate() , as I show below.

public class MainActivity extends Activity {

    ...

    // Declaras la variable
    TextView titulo;

    ...

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

        // Inicializas la variable
        titulo = (TextView)findViewById(R.id.etRadio);

        ...

    }

    ...

}
    
answered by 05.10.2017 в 17:25