When I run the emulator, it woks perfectly with no errors, but when I press the Login button, I get error "java.lang.NullPointerException: Attempt to invoke interface method".
This is my code:
public class MainActivity extends ActionBarActivity {
Button add;
TextView errorlbl;
EditText name, address, pincode;
Connection connect;
PreparedStatement preparedStatement;
Statement st;
String ipaddress, db, username, password;
@SuppressLint("NewApi")
private Connection ConnectionHelper(String user, String password,
String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"
+ "databaseName=" + database + ";user=" + user
+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return connection;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.btnadd);
errorlbl = (TextView) findViewById(R.id.lblerror);
name = (EditText) findViewById(R.id.txtname);
address = (EditText) findViewById(R.id.txtaddress);
pincode = (EditText) findViewById(R.id.txtpincode);
ipaddress = "92.244.93.250:3306";
db = "lokal";
username = "lokal";
password = "12lokal34";
connect = ConnectionHelper(username, password, db, ipaddress);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
st = connect.createStatement();
preparedStatement = connect
.prepareStatement("insert into studentRecord(Name,Address,Pincode) values ('"
+ name.getText().toString()
+ "','"
+ address.getText().toString()
+ "','"
+ pincode.getText().toString() + "')");
preparedStatement.executeUpdate();
errorlbl.setText("Data Added successfully");
} catch (SQLException e) {
errorlbl.setText(e.getMessage().toString());
}
}
});
}
}
Logcat error says:
2182-2182/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: app.mysqlapp, PID: 2182 java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference