Problems with setOnItemClickListener [closed]

0

I'm trying to run this Activity as main, but the application does not even run on the phone.

The error points to the following lines of code:

FormularioHelper helper = new FormularioHelper(activity);

this.campoNome = activity.findViewById(R.id.nome);

ListAlumniActivity.java

package com.alura.magnero2018.agendaalura;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

import alura.modelo.Aluno;
import br.com.alura.dao.AlunoDAO;

public class ListaAlunosActivity extends AppCompatActivity {

    private ListView listaAlunos;
    FormularioActivity activity;
    private FormularioHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);
        Button btnNovoAluno = findViewById(R.id.btnNovoAluno);
        listaAlunos = findViewById(R.id.lista_alunos);

        **FormularioHelper helper = new FormularioHelper(activity);**
        Intent intent = getIntent();
        Aluno aluno = ((Aluno) intent.getSerializableExtra("aluno"));
        if (aluno.getNome() !=null) {
            helper.preencheFormulario(aluno);
        }

        listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> lista, View item, int position, long id) {
                Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(position);
                Intent intentVaiProFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
                intentVaiProFormulario.putExtra("aluno", (Serializable) aluno);
                startActivity(intentVaiProFormulario);
            }
        });

        carregaLista();

        registerForContextMenu(listaAlunos);
        btnNovoAluno.setOnClickListener((v) -> {
            Intent abrirFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
            startActivity(abrirFormulario);
        });
    }

    private void carregaLista() {
        AlunoDAO dao = new AlunoDAO(this);
        //cria uma lista com os dados buscados do banco
        List<Aluno> alunos = dao.buscaAlunos();
        dao.close();

        /* pega os dados do contexto do layour lista_alunos e transforma-os em ListView */
        ListView listaAlunos = findViewById(R.id.lista_alunos);

        /* transforma os dados do array alunos de string para view */
        ArrayAdapter<Aluno> adapter = new ArrayAdapter<Aluno>(this, android.R.layout.simple_list_item_1, alunos);
        listaAlunos.setAdapter(adapter);
    }

    protected void onResume()
    {
        super.onResume();
    }

    //quando o menu de contexto comecar a ser criado, serao inseridas funcionalidades no menu
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        MenuItem deletar = menu.add("Deletar");
        deletar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
           @Override
           public boolean onMenuItemClick(MenuItem item) {
               AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
               Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(info.position);

               AlunoDAO dao = new AlunoDAO(ListaAlunosActivity.this);
               dao.deleta(aluno);
               dao.close();
               Toast.makeText(ListaAlunosActivity.this, "Aluno " + aluno.getNome() + " deletado com sucesso!", Toast.LENGTH_SHORT).show();
               carregaLista();
               return false;
           }
       });
    }
}

Android Studio returns me the following errors:

Error Log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.alura.magnero2018.agendaalura, PID: 12337
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alura.magnero2018.agendaalura/com.alura.magnero2018.agendaalura.ListaAlunosActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.alura.magnero2018.agendaalura.FormularioActivity.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1976)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6912)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.alura.magnero2018.agendaalura.FormularioActivity.findViewById(int)' on a null object reference
        at com.alura.magnero2018.agendaalura.FormularioHelper.<init>(FormularioHelper.java:64)
        at com.alura.magnero2018.agendaalura.ListaAlunosActivity.onCreate(ListaAlunosActivity.java:37)
        at android.app.Activity.performCreate(Activity.java:7144)
        at android.app.Activity.performCreate(Activity.java:7135)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1293)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3101)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1976) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6912) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860) 
Application terminated.

activity_lista_alunos.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListaAlunosActivity"
    android:orientation="vertical">

   <ListView
       android:id="@+id/lista_alunos"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

   <Button
       android:id="@+id/btnNovoAluno"
       android:layout_width="56dp"
       android:layout_height="56dp"
       android:text="+"
       android:textColor="#ffffff"
       android:textSize="35sp"
       android:elevation="6dp"
       android:layout_alignParentBottom="true"
       android:layout_alignParentRight="true"
       android:layout_marginBottom="16dp"
       android:layout_marginRight="16dp"
       android:background="@drawable/fundo"
       />

</RelativeLayout>

Forum helper.java

package com.alura.magnero2018.agendaalura;

import android.widget.EditText;
import android.widget.RatingBar;

import com.alura.magnero2018.agendaalura.FormularioActivity;
import com.alura.magnero2018.agendaalura.R;


import alura.modelo.Aluno;

public class FormularioHelper
{
    private EditText campoNome;
    private EditText campoEndereco;
    private EditText campoSitesPessoais;
    private EditText campoTelefone;
    private RatingBar campoNotas;
    private Aluno aluno;

    public EditText getCampoNome() {
        return campoNome;
    }

    public void setCampoNome(EditText campoNome) {
        this.campoNome = campoNome;
    }

    public EditText getCampoEndereco() {
        return campoEndereco;
    }

    public void setCampoEndereco(EditText campoEndereco) {
        this.campoEndereco = campoEndereco;
    }

    public EditText getCampoSitesPessoais() {
        return campoSitesPessoais;
    }

    public void setCampoSitesPessoais(EditText campoSitesPessoais) {
        this.campoSitesPessoais = campoSitesPessoais;
    }

    public EditText getCampoTelefone() {
        return campoTelefone;
    }

    public void setCampoTelefone(EditText campoTelefone) {
        this.campoTelefone = campoTelefone;
    }

    public RatingBar getCampoNotas() {
        return campoNotas;
    }

    public void setCampoNotas(RatingBar campoNotas) {
        this.campoNotas = campoNotas;
    }


    public FormularioHelper(FormularioActivity activity)
    {
        **this.campoNome = activity.findViewById(R.id.nome);**
        this.campoEndereco = activity.findViewById(R.id.endereco);
        this.campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
        this.campoTelefone = activity.findViewById(R.id.telefone);
        this.campoNotas = (RatingBar) activity.findViewById(R.id.notas);
        Aluno aluno = new Aluno();
    }

    public Aluno pegarAluno()
    {
        Aluno aluno = new Aluno();
        aluno.setNome(String.valueOf(campoNome.getText()));
        aluno.setEndereco(String.valueOf(campoEndereco.getText()));
        aluno.setSite(String.valueOf(campoSitesPessoais.getText()));
        aluno.setTelefone(String.valueOf(campoTelefone.getText()));
        aluno.setNota(Double.valueOf(campoNotas.getProgress()));

        return aluno;
    }

    public void preencheFormulario(Aluno aluno)  {
        campoNome.setText(aluno.getNome());
        campoEndereco.setText(aluno.getEndereco());
        campoTelefone.setText(aluno.getTelefone());
        campoSitesPessoais.setText(aluno.getSite());
        campoNotas.setProgress(aluno.getNota().intValue());
        this.aluno = aluno;
    }
}
    
asked by anonymous 27.12.2018 / 15:33

2 answers

0

The problem was in the part of the code that filled the data on the screen. Because I was in Activity ListAlumniActivity when it should be in Activity ActivityActivity

FormularioHelper helper = new FormularioHelper(this);

        Intent intent = getIntent();
        Aluno aluno = ((Aluno) intent.getSerializableExtra("aluno"));
        if (aluno !=null) {
            helper.preencheFormulario(aluno);
        }

And the position of the element was not being picked up correctly. In this snippet of code:

ListAlumniActivity

listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> lista, View item, int position, long id) {
                Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(position);
                Intent intentVaiProFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
                intentVaiProFormulario.putExtra("aluno", (Serializable) aluno);
                startActivity(intentVaiProFormulario);
            }
        });

===================================================== ====================================

Functional code

ActivityAjativity

package com.alura.magnero2018.agendaalura;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import alura.modelo.Aluno;
import br.com.alura.dao.AlunoDAO;

public class FormularioActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_formulario);
        FormularioHelper helper = new FormularioHelper(this);

        Intent intent = getIntent();
        Aluno aluno = ((Aluno) intent.getSerializableExtra("aluno"));
        if (aluno !=null) {
            helper.preencheFormulario(aluno);
        }   
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        /*cria um objeto do tipo MenuInflater, o qual é responsável por criar objetos do tipo menu, a partir de um
        arquivo xml
         */
        MenuInflater inflater = getMenuInflater();
        /*metodo que pega a referencia do arquivo xml e pega item por item e vai criando os MenuItem e adicionando no menu */
        inflater.inflate(R.menu.activity_menu_formulario, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) //switch vai aqui
    {
        FormularioHelper helper = new FormularioHelper(this);

        switch (item.getItemId())
        {
            case R.id.menu_formulario_ok:

                Aluno aluno = helper.pegarAluno();
                AlunoDAO dao = new AlunoDAO(this);
                dao.insere(aluno);
                dao.close();

                Toast.makeText(FormularioActivity.this, "Aluno " + aluno.getNome() + " salvo", Toast.LENGTH_LONG).show();
                Intent abrirLista = new Intent(FormularioActivity.this, ListaAlunosActivity.class);
                startActivity(abrirLista);

                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Student.java

package alura.modelo;

import android.support.annotation.NonNull;
import android.text.Editable;

import java.io.Serializable;

public class Aluno implements Serializable {
    private Long id;
    private String nome;
    private String endereco;
    private String telefone;
    private String site;
    private Double nota;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getSite() {
        return site;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public Double getNota() {
        return nota;
    }

    public void setNota(Double nota) {
        this.nota = nota;
    }

    @NonNull
    public String toString() {
        return getId() + " " + getNome();
    }
}

Formper.java

package com.alura.magnero2018.agendaalura;

import android.widget.EditText;
import android.widget.RatingBar;

import com.alura.magnero2018.agendaalura.FormularioActivity;
import com.alura.magnero2018.agendaalura.R;


import alura.modelo.Aluno;

public class FormularioHelper
{
    private EditText campoNome;
    private EditText campoEndereco;
    private EditText campoSitesPessoais;
    private EditText campoTelefone;
    private RatingBar campoNotas;
    private Aluno aluno;

    public EditText getCampoNome() {
        return campoNome;
    }

    public void setCampoNome(EditText campoNome) {
        this.campoNome = campoNome;
    }

    public EditText getCampoEndereco() {
        return campoEndereco;
    }

    public void setCampoEndereco(EditText campoEndereco) {
        this.campoEndereco = campoEndereco;
    }

    public EditText getCampoSitesPessoais() {
        return campoSitesPessoais;
    }

    public void setCampoSitesPessoais(EditText campoSitesPessoais) {
        this.campoSitesPessoais = campoSitesPessoais;
    }

    public EditText getCampoTelefone() {
        return campoTelefone;
    }

    public void setCampoTelefone(EditText campoTelefone) {
        this.campoTelefone = campoTelefone;
    }

    public RatingBar getCampoNotas() {
        return campoNotas;
    }

    public void setCampoNotas(RatingBar campoNotas) {
        this.campoNotas = campoNotas;
    }


    public FormularioHelper(FormularioActivity activity)
    {
        this.campoNome = activity.findViewById(R.id.nome);
        this.campoEndereco = activity.findViewById(R.id.endereco);
        this.campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
        this.campoTelefone = activity.findViewById(R.id.telefone);
        this.campoNotas = (RatingBar) activity.findViewById(R.id.notas);
        aluno = new Aluno();
    }

    public Aluno pegarAluno()
    {
        Aluno aluno = new Aluno();
        aluno.setNome(String.valueOf(campoNome.getText()));
        aluno.setEndereco(String.valueOf(campoEndereco.getText()));
        aluno.setSite(String.valueOf(campoSitesPessoais.getText()));
        aluno.setTelefone(String.valueOf(campoTelefone.getText()));
        aluno.setNota((double) campoNotas.getProgress());

        return aluno;
    }

    public void preencheFormulario(Aluno aluno)  {
        campoNome.setText(aluno.getNome());
        campoEndereco.setText(aluno.getEndereco());
        campoTelefone.setText(aluno.getTelefone());
        campoSitesPessoais.setText(aluno.getSite());
        campoNotas.setProgress(aluno.getNota().intValue());
        this.aluno = aluno;
    }
}

ListAlumniActivity.java

package com.alura.magnero2018.agendaalura;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

import alura.modelo.Aluno;
import br.com.alura.dao.AlunoDAO;

public class ListaAlunosActivity extends AppCompatActivity {

    private ListView listaAlunos;
    FormularioActivity activity;
   private FormularioHelper helper;
    Aluno aluno = new Aluno();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);
        Button btnNovoAluno = findViewById(R.id.btnNovoAluno);
        listaAlunos = findViewById(R.id.lista_alunos);
        listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> lista, View item, int position, long id) {
                Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(position);
                Intent intentVaiProFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
                intentVaiProFormulario.putExtra("aluno", (Serializable) aluno);
                startActivity(intentVaiProFormulario);
            }
        });

        carregaLista();

        registerForContextMenu(listaAlunos);
        btnNovoAluno.setOnClickListener((v) -> {
            Intent abrirFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
            startActivity(abrirFormulario);
        });
    }

    private void carregaLista() {
        AlunoDAO dao = new AlunoDAO(this);
        //cria uma lista com os dados buscados do banco
        List<Aluno> alunos = dao.buscaAlunos();
        dao.close();

        /* pega os dados do contexto do layour lista_alunos e transforma-os em ListView */
        ListView listaAlunos = findViewById(R.id.lista_alunos);

        /* transforma os dados do array alunos de string para view */
        ArrayAdapter<Aluno> adapter = new ArrayAdapter<Aluno>(this, android.R.layout.simple_list_item_1, alunos);
        listaAlunos.setAdapter(adapter);
    }

    protected void onResume()
    {
        super.onResume();
    }

    //quando o menu de contexto comecar a ser criado, serao inseridas funcionalidades no menu
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        MenuItem deletar = menu.add("Deletar");
        deletar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
           @Override
           public boolean onMenuItemClick(MenuItem item) {
               AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
               Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(info.position);

               AlunoDAO dao = new AlunoDAO(ListaAlunosActivity.this);
               dao.deleta(aluno);
               dao.close();
               Toast.makeText(ListaAlunosActivity.this, "Aluno " + aluno.getNome() + " deletado com sucesso!", Toast.LENGTH_SHORT).show();
               carregaLista();
               return false;
           }
       });
    }
}
    
03.01.2019 / 15:45
0

I believe that @Override was missing in this part of the code

 listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override 
        public void onItemCIick(AdapterView<?> lista, View item, int position, long id) {
            Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(position);
            Intent intentVaiProFormulario = new Intent(ListaAlunosActivity.this, FormularioActivity.class);
            intentVaiProFormulario.putExtra("aluno", aluno);
            startActivity(intentVaiProFormulario);
        }
    });
    
27.12.2018 / 18:32