Activity closes when calling Oncreate method to create Spinner

Asked

Viewed 69 times

0

I have a Spinner that if I invoke his creative method on Oncreate, the program shuts down abruptly. I think q must be something null or some variable of another scope, because if I call the method of creating Spinner in the method of the commit button, it will normal.

Another thing, is that when guys on youtube do the identification of some xml component by id, they do it inside Oncreate, but if I do this and call my method to capture the values of an Editext, for example, it closes, to circumvent, identify it within the same capture method.

I wanted to know more about this Oncreate method, and whether it is important to identify the elements within it or make the capture within the Oncreate.

My Code:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    meuperfil=(Button) findViewById(R.id.button);
    avaliarcard=(Button) findViewById(R.id.button2);
    info=(Button) findViewById(R.id.button3);
    montarcard=(Button) findViewById(R.id.button4);
    submit=(Button) findViewById(R.id.submit);
    voltar=(Button) findViewById(R.id.voltar);
    idade=(EditText) findViewById(R.id.editIdade);
    addItemsOnSpinner2();
    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();
        }
    });
}

 public void addItemsOnSpinner2() {
    nivel=(Spinner) findViewById(R.id.spinner);
    String[]list={"0","1","2","3","4"};
    ArrayAdapter<String> dataAdapter;
    dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
    nivel.setAdapter(dataAdapter);
}

//Se chamo o método AddItemsOnSpinner2 no método submeter ele vai normal 
public void submeter(View view){
    masculino=(CheckBox) findViewById(R.id.masculino);
    feminino=(CheckBox) findViewById(R.id.feminino);
    peso=(EditText) findViewById(R.id.editPeso);
    altura=(EditText) findViewById(R.id.edtAlt);
    /*Se não identifico os elementos aq, não é possível executar os comandos
    abaixo*/
    if(masculino.isChecked() && feminino.isChecked()) Toast.makeText(MainActivity.this,
            "Você deve selecionar somente uma opção para sexo", Toast.LENGTH_LONG).show();
    else{
        Toast.makeText(this, "seu peso eh " + peso.getText() + "sua altura eh " + altura.getText() +
                "seu esporte eh " + nivel.getSelectedItem(), Toast.LENGTH_LONG).show();
    }

Logcat:

12-26 23:05:10.330 1385-1385/com.clicks.lucas.clicks E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.clicks.lucas.clicks/com.clicks.lucas.clicks.MainActivity}: java.lang.NullPointerException

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

at android.app.ActivityThread.access$600(ActivityThread.java:130)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)

at android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:137)

at android.app.ActivityThread.main(ActivityThread.java:4745)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:511)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

at dalvik.system.NativeStart.main(Native Method)
                                                                        Caused by: java.lang.NullPointerException

at com.clicks.lucas.clicks.MainActivity.addItemsOnSpinner2(MainActivity.java:106)

at com.clicks.lucas.clicks.MainActivity.onCreate(MainActivity.java:54)

at android.app.Activity.performCreate(Activity.java:5008)

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 

at android.app.ActivityThread.access$600(ActivityThread.java:130) 

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 

 at android.os.Handler.dispatchMessage(Handler.java:99) 

at android.os.Looper.loop(Looper.java:137) 

 at android.app.ActivityThread.main(ActivityThread.java:4745) 

 at java.lang.reflect.Method.invokeNative(Native Method) 

at java.lang.reflect.Method.invoke(Method.java:511) 

 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 

                                                                           at dalvik.system.NativeStart.main(Native Method) 

My xml:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="120dp"
        android:layout_height="126dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        app:srcCompat="@drawable/icon"
        tools:layout_editor_absoluteX="103dp"
        tools:layout_editor_absoluteY="100dp" />

    <EditText
        android:id="@+id/edtAlt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editPeso"
        android:ems="10"
        android:hint="Altura em cm"
        android:inputType="number"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="35dp" />

    <EditText
        android:id="@+id/editPeso"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/masculino"
        android:ems="10"
        android:hint="Peso em kg"
        android:inputType="number"
        tools:layout_editor_absoluteX="53dp"
        tools:layout_editor_absoluteY="204dp" />

    <EditText
        android:id="@+id/editIdade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/edtAlt"
        android:ems="10"
        android:hint="Idade"
        android:inputType="number"
        tools:layout_editor_absoluteX="53dp"
        tools:layout_editor_absoluteY="204dp" />

    <Button
        android:id="@+id/voltar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:onClick="voltar"
        android:text="Voltar" />

    <CheckBox
        android:id="@+id/masculino"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView2"
        android:text="Masculino" />

    <CheckBox
        android:id="@+id/feminino"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/masculino"
        android:layout_alignBottom="@+id/masculino"
        android:layout_alignEnd="@+id/editPeso"
        android:layout_alignRight="@+id/editPeso"
        android:layout_marginEnd="11dp"
        android:layout_marginRight="11dp"
        android:text="Feminino" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/imageView2"
        android:text="Qual o seu sexo?"
        android:textColor="#000000"
        android:textSize="16dp" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/nivelexercicios"
        android:layout_marginTop="12dp"
        android:onClick="submeter"
        android:text="Enviar" />

    <CheckBox
        android:id="@+id/sim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/perderpeso"
        android:text="Sim" />

    <CheckBox
        android:id="@+id/nao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_below="@+id/perderpeso"
        android:layout_toLeftOf="@+id/feminino"
        android:layout_toStartOf="@+id/feminino"
        android:text="Não" />

    <TextView
        android:id="@+id/perderpeso"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editIdade"
        android:text="Deseja perder peso?"
        android:textColor="#000000"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/ganharmusc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_below="@+id/editIdade"
        android:layout_marginLeft="12dp"
        android:layout_marginStart="12dp"
        android:layout_toEndOf="@+id/perderpeso"
        android:layout_toRightOf="@+id/perderpeso"
        android:text="Deseja ganhar Músculos?"
        android:textColor="#000000"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/nivelexercicios"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/sim"
        android:text="Defina em uma escala de 0-4 a quantidade de esporte que pratica?"
        android:textColor="#000000"
        android:textSize="16dp" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/nivelexercicios"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="406dp" />

</RelativeLayout>

  • No error in logcat?

  • Not when I compile it, but error in AVD, program has stopped

  • Take a look at the logcat while running the app, it should surely show some error there. If you find, edit the question and post here

  • blz I’ll do it

  • Deu Nullpointerexception

  • Edit the question and put the complete bug stack in text form preferred. This makes it easy to trace the origin of the nullpointer.

  • Check that the Spinner id in your XML is the same as the one you put in java in the addItemsOnSpinner2 method. If it is and to try to understand what the problem is it puts some debugs in the code in the Spinner method through the Log. d("addItemsOnSpinner2","Error")

  • I debugged the code and on the line that access

  • nivel.setAdapter(dataAdapter); it is causing the problem, but not its because, because at the beginning of the method I made the identification of the Spinner level

  • Put the XML of this layout.

  • I don’t know if there is, but Spinner’s not in my main Victoria, so I was wondering if there’s any

  • Well redundant kk

  • The Oncreate method, only access the components of Activity_main? because, my Spinner is in another Layout

  • Spinner is called "spinner1" but you’re catching one with the id "spinner". This will return null. findViewById will only work with the elements that are in the layout you defined by setContentView.

  • It’s not even Spinner kkk I switched later to test

  • But this setContentView I will test inside the method

  • Okay, you guys are fucked!!!

Show 12 more comments

1 answer

0

The Spinner creation code was correct. The error is that it was called in a method that did not see the layout I created. Just give a setContentView that solved it. Problem Solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.