Error when bringing information from database

Asked

Viewed 69 times

1

I’m having trouble bringing the information from the database and displaying it in a list, when executing the code to bring the information from the application BD to and the following error appears:

Stack Trace


  • FATAL EXCEPTION: main Process: com.example.Matheus.privatewalletm, PID: 3515 java.lang.Nullpointerexception: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$Onclicklistener)' on a null Object Reference at com.example.Matheus.privatewalletm.Usuarioadapter.getView(Usuarioadapter.java:60) at android.widget.Abslistview.obtainView(Abslistview.java:2347) at android.widget.Listview.makeAndAddView(Listview.java:1864) at android.widget.Listview.fillDown(Listview.java:698) at android.widget.Listview.fillFromTop(Listview.java:759) at android.widget.Listview.layoutChildren(Listview.java:1673) at android.widget.Abslistview.onLayout(Abslistview.java:2151) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.widget.Relativelayout.onLayout(Relativelayout.java:1076) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.widget.Framelayout.layoutChildren(Framelayout.java:579) at android.widget.Framelayout.onLayout(Framelayout.java:514) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.support.v7.widget.Actionbaroverlaylayout.onLayout(Actionbaroverlaylayout.java:435) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.widget.Framelayout.layoutChildren(Framelayout.java:579) at android.widget.Framelayout.onLayout(Framelayout.java:514) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.widget.Linearlayout.setChildFrame(Linearlayout.java:1703) at android.widget.Linearlayout.layoutVertical(Linearlayout.java:1557) at android.widget.Linearlayout.onLayout(Linearlayout.java:1466) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.widget.Framelayout.layoutChildren(Framelayout.java:579) at android.widget.Framelayout.onLayout(Framelayout.java:514) at android.view.View.layout(View.java:15671) at android.view.Viewgroup.layout(Viewgroup.java:5038) at android.view.Viewrootimpl.performLayout(Viewrootimpl.java:2086) at android.view.Viewrootimpl.performTraversals(Viewrootimpl.java:1843) at android.view.Viewrootimpl.doTraversal(Viewrootimpl.java:1061) at android.view.Viewrootimpl$Traversalrunnable.run(Viewrootimpl.java:5885) at android.view.Choreographer$Callbackrecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$Framedisplayeventreceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) )

----

Classes Envolvidos

Class Novo:

public class Novo extends AppCompatActivity {

    private Usuario usuario;
    private EditText editTextNome;
    private EditText editTextData;
    private EditText editTextRg;
    private EditText editTextCpf;
    private EditText editTextDoenca;
    private EditText editTextAlergia;
    private EditText editTextProfissao;


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

        this.usuario = new Usuario();
        this.editTextNome = (EditText) findViewById(R.id.editTextNome);
        this.editTextData = (EditText) findViewById(R.id.editTextData);
        this.editTextRg = (EditText) findViewById(R.id.editTextRg);
        this.editTextCpf = (EditText) findViewById(R.id.editTextCpf);
        this.editTextDoenca = (EditText) findViewById(R.id.editTextDoenca);
        this.editTextAlergia = (EditText) findViewById(R.id.editTextAlergia);
        this.editTextProfissao = (EditText) findViewById(R.id.editTextProfissao);

        Intent intent = getIntent();
            if(intent != null){
                Bundle bundle = intent.getExtras();
                if(bundle != null){
                    this.usuario.setId(bundle.getInt("id"));
                    this.editTextNome.setText(bundle.getString("nome"));
                    this.editTextData.setText(bundle.getInt("data"));
                    this.editTextRg.setText(bundle.getString("rg"));
                    this.editTextCpf.setText(bundle.getString("cpf"));
                    this.editTextDoenca.setText(bundle.getString("doenca"));
                    this.editTextAlergia.setText(bundle.getString("alergia"));
                    this.editTextProfissao.setText(bundle.getString("profissao"));

                }
            }
    }

    public void confirmar (View view){
        this.usuario.setNome(this.editTextNome.getText().toString());
        this.usuario.setData(this.editTextData.getText().toString());
        this.usuario.setRg(this.editTextRg.getText().toString());
        this.usuario.setCpf(this.editTextCpf.getText().toString());
        this.usuario.setDoenca(this.editTextDoenca.getText().toString());
        this.usuario.setAlergia(this.editTextAlergia.getText().toString());
        this.usuario.setProfissao(this.editTextProfissao.getText().toString());
        this.usuario.confirmar();

        Toast.makeText(this,this.usuario.get_messagem(),Toast.LENGTH_LONG).show();
        if(usuario._status)
            finish();
    }

    public void cancelar (View view){
        finish();
    }
}

Class Usuario:

public class Usuario extends _default {
    private int id;
    private String nome;
    private String data;
    private String rg;
    private String cpf;
    private String doenca;
    private String alergia;
    private String profissao;


    public int getId() {
        return id;
    }

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

    public String getNome() {
        return nome;
    }

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

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getRg() {
        return rg;
    }

    public void setRg(String rg) {
        this.rg = rg;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getDoenca() {
        return doenca;
    }

    public void setDoenca(String doenca) {
        this.doenca = doenca;
    }

    public String getAlergia() {
        return alergia;
    }

    public void setAlergia(String alergia) {
        this.alergia = alergia;
    }

    public String getProfissao() {
        return profissao;
    }

    public void setProfissao(String profissao) {
        this.profissao = profissao;
    }

    public Usuario(){
        super();
        this.id = -1;
        this.nome = "";
        this.data = "";
        this.rg = "";
        this.cpf = "";

        this.doenca = "";
        this.alergia = "";
        this.profissao = "";
    }

    public ArrayList<Usuario> getLista(){
        BD bd = new BD();
        ArrayList<Usuario> lista = new ArrayList<>();
        try {
            ResultSet resultSet = bd.select("SELECT * FROM usuario");
            if(resultSet != null ){
                while (resultSet.next()){
                    Usuario obj = new Usuario();
                    obj.setId(resultSet.getInt("id"));
                    obj.setNome(resultSet.getString("nome"));
                    obj.setData(resultSet.getString("data"));
                    obj.setRg(resultSet.getString("rg"));
                    obj.setCpf(resultSet.getString("cpf"));
                    obj.setDoenca(resultSet.getString("doenca"));
                    obj.setAlergia(resultSet.getString("alergia"));
                    obj.setProfissao(resultSet.getString("profissao"));
                    lista.add(obj);
                    obj = null;
                }
            }
        }
        catch (Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());
            this._messagem = e.getMessage();
            this._status = false;

        }
        return lista;
    }

    public void confirmar(){
        String comando = "";
        if(this.getId() == -1){
            comando = String.format("INSERT INTO Usuario(nome, data, rg, cpf, doenca, alergia, profissao) values ('%s', '%d', '%s', '%s', '%s', '%s','%s' );",
                    this.getNome(), this.getData(), this.getRg(), this.getCpf(), this.getDoenca(), this.getAlergia(), this.getProfissao());

        }
        else
        {
            comando = String.format("UPDATE Usuario SET nome ='%s', date = '%d', rg = '%s', cpf = '%s', doenca = '%s', alergia = '%s', profissao = '%s' WHERE id = %d;",
                    this.getNome(), this.getData(), this.getRg(), this.getCpf(), this.getDoenca(), this.getAlergia(), this.getProfissao(), this.getId());
        }
        BD bd = new BD();
       bd.execute(comando);
       this._messagem = bd._messagem;
        this._status = bd._status ;
    }

    public void apagar(){
        String  comando =  String.format("DELETE FROM usuario WHERE id = %d ", this.getId());

        BD bd = new BD();
        bd.execute(comando);
        this._messagem = bd._messagem;
        this._status = bd._status ;    
    }    
}

Class UsuarioAdapter:

public class UsuarioAdapter extends ArrayAdapter<Usuario> {
    private Context context;
    private ArrayList<Usuario> lista;

public UsuarioAdapter(Context context, ArrayList<Usuario> lista)
    {
        super(context,0,lista);
        this.context = context;
        this.lista = lista;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        final Usuario itemPosicao = this.lista.get(position);

        convertView = LayoutInflater.from(this.context).inflate(R.layout.item_lista,null);
        final View layout = convertView;

        TextView textViewNome = (TextView) convertView.findViewById(R.id.textViewNome);
        textViewNome.setText(itemPosicao.getNome());

        TextView textViewData = (TextView) convertView.findViewById(R.id.textViewData);
        textViewData.setText(itemPosicao.getData());

        TextView textViewRg = (TextView) convertView.findViewById(R.id.textViewRg);
        textViewRg.setText(itemPosicao.getRg());

        TextView textViewCpf = (TextView) convertView.findViewById(R.id.textViewCpf);
        textViewCpf.setText(itemPosicao.getCpf());

        TextView textViewDoenca = (TextView) convertView.findViewById(R.id.textViewDoenca);
        textViewDoenca.setText(itemPosicao.getDoenca());

        TextView textViewAlergia = (TextView) convertView.findViewById(R.id.textViewAlergia);
        textViewAlergia.setText(itemPosicao.getAlergia());

        TextView textViewProfissao = (TextView) convertView.findViewById(R.id.textViewProfissao);
        textViewProfissao.setText(itemPosicao.getProfissao());

        Button button = (Button) convertView.findViewById(R.id.buttonEditar);
        button.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            Intent intent = new Intent(context,Novo.class);
            intent.putExtra("nome", itemPosicao.getNome());
            intent.putExtra("data", itemPosicao.getData());
            intent.putExtra("rg", itemPosicao.getRg());
            intent.putExtra("cpf", itemPosicao.getCpf());
            intent.putExtra("doenca", itemPosicao.getDoenca());
            intent.putExtra("alergia", itemPosicao.getAlergia());
            intent.putExtra("profissao", itemPosicao.getProfissao());
            context.startActivity(intent);
           }
        });
    Button buttonDeletar = (Button) convertView.findViewById(R.id.buttonApagar);
        buttonDeletar.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                itemPosicao.apagar();
                if (itemPosicao._status)
                    layout.setVisibility(View.GONE);
                else
                    Toast.makeText(context, itemPosicao.get_messagem(), Toast.LENGTH_LONG).show();
            }
            });

        return convertView;  
    }
}

Classes of the BD

Class ExecuteBD:

public class ExecuteBD extends AsyncTask<String, Void, ResultSet>{
    private Connection connection;
    private String query;

    public ExecuteBD(Connection connection, String query) {
        this.connection = connection;
        this.query = query;
    }


    @Override
    protected ResultSet doInBackground(String... strings) {
        ResultSet resultSet = null;
        try
        {
            resultSet = connection.prepareStatement(query).executeQuery();
        }
        catch(Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());

        }finally {
            try
            {
            connection.close();
            }
            catch (Exception e)
            {
                Log.d("PrivateWalletM", e.getMessage());
            }

        }
        return resultSet;
    }
}

Class BD:

public class BD extends _default implements Runnable {
    private Connection conn;
    private String host = "192.168.0.100";
    private String db = "android";
    private int port = 2345;
    private String user = "androidUser";
    private String pass = "*android*";
    private String url = "jbdc:postgresql://%s:%d/%s";

    public BD (){
        super();
        this.url = String.format(this.url, this.host, this.port, this.db);

        this.conecta();
        this.disconecta();
    }

    @Override
    public void run() {
        try{
            Class.forName("org.postgresql.Driver");
            this.conn = DriverManager.getConnection(this.url, this.user, this.pass);
        }
        catch(Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());
            this._messagem = e.getMessage();
            this._status = false;

        }
    }
    private void conecta(){
        Thread thread = new Thread(this);
        thread.start();
        try
        {
            thread.join();
        }
        catch (Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());
            this._messagem = e.getMessage();
            this._status = false;
        }
    }

    private void disconecta(){
        if(this.conn != null ){
            try
            {
                this.conn.close();
            }
            catch (Exception e)
            {
                Log.d("PrivateWalletM", e.getMessage());
            }finally {
                this.conn = null;
            }
        }
    }
    public ResultSet select (String query){
        this.conecta();
        ResultSet resultSet = null;
        try {
            resultSet = new ExecuteBD(this.conn, query).execute().get();
        }
        catch (Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());
            this._status = false;
            this._messagem = e.getMessage();
        }
        return resultSet;
    }

    public ResultSet execute (String query){
        this.conecta();
        ResultSet resultSet = null;
        try {
            resultSet = new ExecuteBD(this.conn, query).execute().get();
        }
        catch (Exception e)
        {
            Log.d("PrivateWalletM", e.getMessage());
            this._status = false;
            this._messagem = e.getMessage();
        }
        return resultSet;
    }
}

Class Lista:

package com.example.matheus.privatewalletm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;


    public class Lista extends AppCompatActivity {
    private ListView listViewUsuario;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista);

        this.listViewUsuario = (ListView) findViewById(R.id.listViewUsuario);
        this.listViewUsuario.setAdapter(new UsuarioAdapter(this, new Usuario().getLista()));
    }


}

Picture of the BD table:

inserir a descrição da imagem aqui

  • Dude, make sure your button id is instantiated correctly in your XML.

  • Tip put a break point on the final line User itemPosic = this.lista.get(position); and see if this null any of the referenced fields.

  • By stacktrace, the error is here (Usuarioadapter, line 60): layout.setVisibility(View.GONE); I think the layout is coming null because convertView is empty. Give it a whirl to see if it’s right.

  • Well I tried to tidy up here, and here’s the thing: when I open my application without being connected to the database Activity is called normally, but when connected to the database the application simply hangs

1 answer

1

In your DB class I think the url attribute is wrong. You declared:

private String url = "jbdc:postgresql://%s:%d/%s";

But it would have to be:

private String url = "jdbc:postgresql://%s:%d/%s";
  • What’s the difference between them?

  • 1

    The beginning of the string "jbdc" is wrong, should start with "jdbc", I believe the problem is this.

  • I checked a dozen times and couldn’t tell the difference.:)

  • Was this the problem? Did it work? When can test post a comment here.

  • Ricardo, I didn’t ask the question:)

Browser other questions tagged

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