-2

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

Amit
  • 13,134
  • 17
  • 77
  • 148
Erzi
  • 15
  • 3

3 Answers3

1

Your ConnectionHelper method traps exceptions and instead returns null when something goes wrong. So when calling it, since you've opted out of structured exception handling, you have to allow for a null return value. You're not doing that, you're just using the return value of ConnectionHelper without checking whether it's null first.

Clearly, an error is occurring in ConnectionHelper, which you're trapping and dumping to the log. So that will tell you what's going wrong.


Side note: The overwhelming convention in Java is not to capitalize the first letter of methods.

Side note 2: It would be much better practice to allow the exceptions in ConnectionHelper to propagate to your top level entry point and handle them there.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

It is clear that your connection object is null which means ConnectionHelper() is returning null.. Which further implies that below line is returning null

connection = DriverManager.getConnection(ConnectionURL);

Now this can only happen when either driver name is wrong or ConnectionURL is wrong. Since driver name seems correct the only place of error is your connection url string. I just checked this similar answer here at SO.

To me it looks like, Connetion URl string should be

 ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"
                    + "database=" + database + ";user=" + user
                    + ";password=" + password + ";";

Note the difference in database and databaseName variable in connection String. This should work.

UPDATE All the points mentioned in @T.J. Crowder's answer is correct and you should make a habit of following standard conventions.

Community
  • 1
  • 1
Amit
  • 13,134
  • 17
  • 77
  • 148
0

Its clear from your code that there is something wrong going in your ConnectionHelper its giving back null

Note :its my guess only

you have used net.sourceforge.jtds.jdbc.Driver and thats for MsSql server and you have given 3306 as port of db server, mostly 3306 is used for MySql, so are you sure you have configured your MsSql on 3306

Keval
  • 1,857
  • 16
  • 26