I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.
While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so. I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.
This is the doInbackground method in my BackgroundTask class:
@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
// the ip is default for localhost
String reg_url = "http://**MyIP**/webapp/register.php";
String login_url = "http://**MyIP**/webapp/login.php";
String method = params[0];
if (Objects.equals(method, "register")){
String userName = params[1];
String userPass = params[2];
String gender = params[3];
try {
URL url = new URL(reg_url);
// run the register php script.
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
// applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
// the info the user typed.
String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
// write the data to server
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Successs";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}