Boa tarde me chamo Guilherme de Castro , estou desenvolvendo um app para android aonde conecto diretamente a um banco de dados existente ( PostgreSQL ) .
estou recebendo o seguinte erro ao executar o sistema
java.lang.NullPointerException: Attempt to invoke interface method ‘int java.sql.CallableStatement.executeUpdate(java.lang.String)’ on a null object reference
segue abaixo as classes criadas :
Classe de Conexao ao Banco
package castro.conexaoDB;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BancoNovo{
public String Conectar(){
String retorno = null;
String url;
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
Log.e("#OK","Classe OK!!!");
} catch (ClassNotFoundException e) {
retorno = "Onde está o seu PostgreSQL Driver JDBC ? " + "Inclui a LIB no path !";
e.printStackTrace();
Log.e("#Erro Driver",e.getMessage());
return retorno;
}
try {
url = "jdbc:postgresql://192.168.5.132:5432/spacoeletro";
DriverManager.setLoginTimeout(5);
Log.e("#OK","Conectado Com Sucesso!!!");
conn = DriverManager.getConnection(url, "postgres", "1234");
} catch (Exception e) {
Log.e("#Erro JDBC",e.getMessage());
retorno = "Erro de conexão !!! - " + e.getMessage() + " ::004";
}
if (conn != null) {
Log.e("#Conectado","PostgreSQL");
retorno = "Você fez isso, assumir o controle do banco de dados agora!";
}
return retorno;
}
}
Classe MainActivity
package castro.conexaoDB;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private String nome;
private String telefone;
private EditText nomeEdit;
private EditText nomeTelefone;
private TextView nomeResultado;
private String sql;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
BancoNovo bn = new BancoNovo();
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.btnConsultar);
b1.setOnClickListener(consultarBTN);
nomeEdit = findViewById(R.id.editTextResultadoNome);
nomeResultado = findViewById(R.id.editTextResultado);
}
public void consultar(View view) throws SQLException, ClassNotFoundException {
nome = nomeEdit.getText().toString();
nomeResultado.setText("Nome: " + nome);
buscar(nome);
}
View.OnClickListener consultarBTN = new View.OnClickListener() {
public void onClick(View view) {
nome = nomeEdit.getText().toString();
nomeResultado.setText("Nome: " + nome);
buscar(nome);
}
};
public void inicioDB(View view){
Connection c = null;
try{
conn();
Toast.makeText(getApplicationContext(),"Conectado ao Banco",Toast.LENGTH_LONG).show();
}catch (Exception ex){
Toast.makeText(getApplicationContext(),"Erro dentro do onclick "+ex.getMessage(),Toast.LENGTH_LONG).show();
Log.e("#Erro onClick",ex.getMessage());
Log.e("#String",sql);
}
}
public void conn(){
bn.Conectar();
}
public void buscar(String nome){
Connection conn = null;
bn.Conectar();
sql=null;
PreparedStatement pst = null;
CallableStatement cst = null;
try {
//pst = conn.prepareStatement("select email from teste where nome='"+nome+"'");
cst.executeUpdate("select email from teste where nome='"+nome+"'");
}catch (SQLException ex){
Log.e("Erro SQL",ex.getMessage());
}
}
}
ocorreu o seguinte erro ao executar o código abaixo
Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement(int, int)’ on a null object reference
W/System.err: java.lang.NullPointerException: Attempt to invoke interface method ‘java.sql.Statement java.sql.Connection.createStatement(int, int)’ on a null object reference
W/System.err: at castro.conexaoDB.BancoNovo.executaSQL(BancoNovo.java:62)
linha que esta dando o erro
stm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
package castro.conexaoDB;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class BancoNovo {
public Statement stm;
public ResultSet rs;
public Connection conn;
public String retorno;
public String url;
public void Conectar() {
try {
Class.forName("org.postgresql.Driver");
Log.e("#OK", "Classe OK!!!");
} catch (ClassNotFoundException e) {
retorno = "Onde está o seu PostgreSQL Driver JDBC ? " + "Inclui a LIB no path !";
e.printStackTrace();
Log.e("#Erro Driver", e.getMessage());
//return retorno;
}
try {
url = "jdbc:postgresql://192.168.5.132:5432/spacoeletro";
DriverManager.setLoginTimeout(60);
Log.e("#OK", "Conectado Com Sucesso!!!");
conn = DriverManager.getConnection(url, "postgres", "spaco0225");
} catch (Exception e) {
Log.e("#Erro JDBC", e.getMessage());
retorno = "Erro de conexão !!! - " + e.getMessage() + " ::004";
}
if (conn != null) {
Log.e("#Conectado", "PostgreSQL");
retorno = "Você fez isso, assumir o controle do banco de dados agora!";
}
//return retorno;
}
public void executaSQL(String SQL) {
try {
stm = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stm.executeQuery(SQL);
Log.e("#Statement", stm.toString());
Log.e("#ResultSet", rs.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("#Erro SQL", e.getMessage());
}
}
public ResultSet query() {
//Connection c = this.Conectar();
ResultSet rs = null;
Dados data = new Dados();
List<Dados> ld = new ArrayList<Dados>();
try {
String sql = "Select * from teste";
//PreparedStatement pst = c.prepareStatement(sql);
//rs = pst.executeQuery();
while (rs.next()) {
data.setNome(rs.getString("nome"));
data.setEmail(rs.getString("email"));
data.setEmail(rs.getString("telefone"));
ld.add(data);
Log.e("#ResultSet OK", rs.toString());
}
} catch (SQLException ex) {
Log.e("#Erro Result: ", ex.getMessage());
}
return null;
}
}
e veio o seguinte erro no log:
W/System.err: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:116)
at java.net.SocketOutputStream.write(SocketOutputStream.java:161)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at org.postgresql.core.PGStream.flush(PGStream.java:531)
at org.postgresql.core.v3.QueryExecutorImpl.sendSync(QueryExecutorImpl.java:1182)
W/System.err: at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:254)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:405)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:285)
at castro.conexaoDB.BancoNovo.executaSQL(BancoNovo.java:62)
at castro.conexaoDB.MainActivity.chamarMetodo(MainActivity.java:120)
at castro.conexaoDB.MainActivity.query(MainActivity.java:112)
at castro.conexaoDB.MainActivity$1.onClick(MainActivity.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14966)
W/System.err: at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7857)
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:1076)
W/System.err: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.e(Log.java:323)
at castro.conexaoDB.BancoNovo.executaSQL(BancoNovo.java:67)
at castro.conexaoDB.MainActivity.chamarMetodo(MainActivity.java:120)
at castro.conexaoDB.MainActivity.query(MainActivity.java:112)
at castro.conexaoDB.MainActivity$1.onClick(MainActivity.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14966)
at android.view.View.performClickInternal(View.java:7839)
W/System.err: at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7857)
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:1076)
show veio os dados
E/#Conectado: PostgreSQL
E/#Statement: org.postgresql.jdbc3g.Jdbc3gStatement@a261835
E/#ResultSet: org.postgresql.jdbc3g.Jdbc3gResultSet@b96a4ca
D/#Result:: guilherme@formatto.com.b simone_c29@hotmail.com
agora vou tratar o resultado desse resultset . Muito Obrigado