0

I am working on creating an Android app that will be connecting to a MySQL database that is hosted through the Google Cloud Platform. I've created an API method that will interact with the database. As shown below.

MyEndpoint.java (Holds the definition for the API method used to call database.)

package com.google.ProjectName.app.backend;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.inject.Named;

/**
* An endpoint class we are exposing
*/
@Api(
    name = "myApi",
    version = "v1",
    namespace = @ApiNamespace(
            ownerDomain = "backend.app.ProjectName.google.com",
            ownerName = "backend.app.ProjectName.google.com",
            packagePath = ""
    )
)
public class MyEndpoint {

@ApiMethod(name="createUser")
public void createUser(@Named("username") String username, @Named("email") String email, @Named("password") String password, @Named("phonenumber") String phonenumber){
    //try connecting to the database, and inserting the record....need to check that the username, email, phone number don't exist in database
    String databaseName = "dbname";
    String instanceConnectionName = "googlecloudinstance";
    String databaseUser = "user";
    String databasePassword = "password";

    String jdbcUrl = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&"+"socketFactory=com.google.cloud.sql.mysql.SocketFactory", databaseName, instanceConnectionName);

    try{
        Connection connection = DriverManager.getConnection(jdbcUrl, databaseUser, databasePassword);

        try(Statement statement = connection.createStatement()){
            ResultSet resultSet = statement.executeQuery("show tables");
            while(resultSet.next()){
                System.out.println(resultSet.getString(1));
            }
        }
    }
    catch(SQLException sqlerr) {
        System.out.println("Issue with database connection.");
    }
}
}

RegisterActivity.java (Contains the method that will be called to invoke the API.)

package ProjectName.app;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.os.AsyncTask;
import android.util.Pair;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.*;
import com.google.ProjectName.app.backend.myApi.MyApi;
import com.google.ProjectName.app.backend.myApi.model.User;

class EndpointsAsyncTask extends AsyncTask<Pair<Context, User>, Void, String> {
private static MyApi myApiService = null;
private Context context;

@Override
protected String doInBackground(Pair<Context, User>... params) {
    if(myApiService == null) {  // Only do this once
        MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(), null)
                // options for running against local devappserver
                // - 10.0.2.2 is localhost's IP address in Android emulator
                // - turn off compression when running against local devappserver
                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });
        // end options for devappserver

        myApiService = builder.build();
    }

    context = params[0].first;
    String email = params[1].second.getEmail();
    String password = params[1].second.getPassword();
    String username = params[1].second.getUsername();
    String phonenumber = params[1].second.getPhonenumber();
    try {
        myApiService.createUser(email, password, username, phonenumber).execute();
        return null;

    } catch (IOException e) {
        return e.getMessage();
    }
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

public void attemptRegister(View view) throws IOException, SQLException {
    Log.i("System.out", "Reached Attempted Registration."); <----Does not show in the log when clicking on button.

    EditText userText = (EditText) findViewById(R.id.username);
    EditText emailText = (EditText) findViewById(R.id.emailaddress);
    EditText phoneText = (EditText) findViewById(R.id.phonenumber);
    EditText passText = (EditText) findViewById(R.id.password);

    User user = new User();
    user.setUsername(userText.getText().toString());
    user.setEmail(emailText.getText().toString());
    user.setPhonenumber(phoneText.getText().toString());
    user.setPassword(passText.getText().toString());

    new EndpointsAsyncTask().execute(new Pair<Context, User>(this, user));

}
}

User.java

public class User {
private String email;
private String password;
private String username;
private String phonenumber;

public void setEmail(String email){
    this.email = email;
}

public void setPassword(String password){
    this.password = password;
}

public void setUsername(String username){
    this.username = username;
}

public void setPhonenumber(String phonenumber){
    this.phonenumber = phonenumber;
}

public String getEmail(){
    return email;
}

public String getPassword(){
    return password;
}

public String getUsername(){
    return username;
}

public String getPhonenumber(){
    return phonenumber;
}

}

Could anyone provide some insight as to why the database is not being called? Am I not invoking the API method correctly? If you need me to clarify anything please let me know.

user2659117
  • 17
  • 1
  • 1
  • 8
  • 1
    Please read [JDBC vs Web Service for Android](http://stackoverflow.com/questions/15853367/jdbc-vs-web-service-for-android) – Morrison Chang Apr 26 '17 at 03:44
  • Based off of what I was able to gather from reading the information in the link you provided, I need to scratch my current approach, and create a RESTful API to communicate with the database. It makes sense that my current approach is not desirable as it leaves way too many variables out in the open. Do you have any experience with creating an API to connect to a MySQL database hosted on the Google Cloud Platform? – user2659117 Apr 27 '17 at 02:04
  • *"I need to scratch my current approach"* That's correct. – Michael - sqlbot Apr 27 '17 at 03:18
  • @user2659117 if u found a solution, can you explain it ? – Jerin A Mathews Jul 13 '17 at 13:02

0 Answers0