Using a volley library I am sending a post request to a file register.php which should perform user registration and return JSONResponse after success. The code I have written is working fine in the local server(MAMP) but is not working in the live server. Logcat shows {success = 0} in the live server.
package com.example.androidregisterandlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
RequestQueue requestQueue;
private static String URL_REGIST = "https://domainname.com.np/mentordai/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
Log.d("TAG",response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")) {
Toast.makeText(MainActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Server code
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO student_users_table (name, email, password) VALUES ('$name', '$email', '$password')";
if ( mysqli_query($connection, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($connection);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
```
I'm not an php expert but it looks like your server is the one who return the 'success=0'
And it looks like you have some problem with the if ( mysqli_query($connection, $sql) ) statement, your code going to the else who return the success = 0.
Try to debug the server to see what happens when you send register request.
I think you should put validation at both end (Client as well as server end) on all of your form field . If any one of the field is kept empty your query will not be able to run.
For Validation in server use this at the start of your code
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']))
{
}
To Validate data in Client side use
if(this.name.getText().toString().trim().equals(""))
{
Toast.makeText(MainActivity.this, "Please Enter Name " + e.toString(), Toast.LENGTH_SHORT).show();
}
also for password and email
Related
I know, i know, it's an old question to ask but I'm totally stuck. I've been trying to solve it using all those answer on Stackoverflow but still helpless. So, this is my code:
[Java]:
package com.projectbengkelin;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
EditText Edtnama,Edtemail,Edtalamat,EdtnoHp,Edtpassword;
Button btnLanjut;
Button btnKembali;
ProgressBar loading;
String nama, email, alamat, noHp, password;
//private static String URL_REGISTER = "http://192.168.56.1/finals-mobile/register.php";
String URL_REGISTER = "https://bengkelinteam.000webhostapp.com/api/insert_user.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Edtnama = findViewById(R.id.nama);
Edtemail = findViewById(R.id.email);
Edtalamat = findViewById(R.id.alamat);
EdtnoHp = findViewById(R.id.noHp);
Edtpassword = findViewById(R.id.password);
loading = findViewById(R.id.loading);
btnLanjut = findViewById(R.id.btnLanjut);
btnKembali = findViewById(R.id.btnKembali);
btnKembali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
}
});
btnLanjut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register();
}
});
}
private void Register() {
loading.setVisibility(View.VISIBLE);
btnLanjut.setVisibility(View.GONE);
nama = Edtnama.getText().toString();
email = Edtemail.getText().toString();
alamat = Edtalamat.getText().toString();
noHp = EdtnoHp.getText().toString();
password = Edtpassword.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int sukses = jsonObject.getInt("success");
// Toast.makeText(Register.this, "Setelah jsonObject", Toast.LENGTH_SHORT).show();
if (sukses == 1) {
Toast.makeText(Register.this, "Register Success!", Toast.LENGTH_SHORT).show();
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Register.this, "Register Failed!" + e.toString(), Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, "Register Failed!" + error.toString(), Toast.LENGTH_SHORT).show();
//error.printStackTrace();
Log.e("Error", error.getMessage());
loading.setVisibility(View.GONE);
btnLanjut.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("nama", nama);
params.put("email", email);
params.put("alamat", alamat);
params.put("noHp", noHp);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
And then, here is my PHP code which is I'd put on 000webhost:
[PHP]:
<?php
header('Content-type:application/json;chartset=utf-8');
include 'conn.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$noHp = $_POST['noHp'];
$email = $_POST['email'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$password = $_POST['password'];
// $password = password_hash($password, PASSWORD_DEFAULT);
// require_once 'connect.php';
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
echo json_encode($response);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($response);
mysqli_close($conn);
}
}
Everytime I tried to insert the data using that API JSON, I always get this error messange:
value connected of type java.lang.string cannot be converted to jsonobject
Please help me.
there is simple issue in your php code - do like that :
$response=array();
$q = mysqli_query($conn, "INSERT INTO user (noHp, email ,nama, alamat, password) VALUES ('$nohp','$email','$nama','$alamat','$password')");
if ($q) {
$response["success"] = "1";
$response["message"] = "success";
} else {
$response["success"] = "0";
$response["message"] = "error";
}
echo json_encode($response);
mysqli_close($conn);
use Postman to check your response
Hi i'm building an app on android studio which requires register and login,
My registration working fine while i'm having troubles with my login,I'm getting false boolean instead of true even if the username and password are correct,
Here my PHP file:
`$con = mysqli_connect("localhost", "id1013905_trhtkv", "my password",` "id1013905_user");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colAge, $colPassword);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
?>
My login activity:
package com.ben.owner.say_something;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
final EditText etUsername = (EditText)findViewById(R.id.etUsername);
final EditText etPassword = (EditText)findViewById(R.id.etPassword);
final Button bLogin = (Button)findViewById(R.id.bLogin);
final TextView registerLink = (TextView)findViewById(R.id.tvRegisterHere);
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final Response.Listener<String>responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
String name = jsonResponse.getString("name");
int age = jsonResponse.getInt("age");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name",name);
intent.putExtra("username",username);
intent.putExtra("age",age);
LoginActivity.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
And my login request:
package com.ben.owner.say_something;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by owner on 09/03/2017.
*/
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "https://saysomething.000webhostapp.com/Login.php";
private Map<String, String> params;
public LoginRequest(String username,String password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
To find your bug I just would suggest to retrieve server values in the responce.
I mean
instead of
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
use
$response = array();
$response["success"] = false;
echo $statement;//or something like
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
echo $password;
echo $colPassword;
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
or debug your server side. It seems your server code is wrong.
check this example
http://php.net/manual/en/mysqli-stmt.fetch.php
Im going to make a database in php my sql using android studio
but this error is in the way
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
I receive the error cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import prefs.UserInfo;
import prefs.UserSession;
public class Login extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Login.class.getSimpleName();
private EditText email, password;
private Button login;
private TextView signup;
private ProgressDialog progressDialog;
private UserSession session;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//check for error node in json
if (!error) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
addToRequestQueue is a method defined for the volley application controller which seems to be AndroidLoginController in your case. Change the line to
AndroidLoginController.getInstance().addToRequestQueue(strReq,tag_string_req)
This is assuming you have created the singleton using standard volley tutorials or android developer documentation
I was following this tutorial in which I was building login and registration app:
https://www.youtube.com/watch?v=T7Z4GVFaT4A
I've changed PHP and tested it by passing some arguments through address field, but when I'm clicking register button nothing happens.
There are some things in OnResponse function that should be doing something, something should be added to database, but nothing happens.
I was wondering if maybe anything at all is being send from app if I'm not getting any response.
Also, what's troubling me, function OnResponse is never called, but it should be.
Instead of using some ASP I create server using WAMP. Below there are Java and PHP files that are crucial to this problem.
RegisterRequest.java
package com.example.dominik.praca;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Dominik on 28.12.2016.
*/
public class RegisterRequest extends StringRequest {
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.ugu.pl/Register.php";
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.byethost3.com/Register2.php";
private static final String REGISTER_REQUEST_URL = "http://127.0.0.1/kulturnik/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java
package com.example.dominik.praca;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etName = (EditText) findViewById(R.id.etName);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
AlertDialog.Builder builderSuccess = new AlertDialog.Builder(RegisterActivity.this);
builderSuccess.setMessage("Rejestracja zakończona powodzeniem")
.create()
.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Błąd rejestracji")
.setNegativeButton("Ponów", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
And Register.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$con = mysqli_connect("localhost", "root", "", "kulturnik");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
print_r(json_encode($response));
?>
Use Async task for faster send & retrieval to/fro server. Just create an object of the class and use execute function to pass parameters and start asynchronous sending and retrieval to/fro the server.
eg:- SendtoPhp stp = new SendtoPhp();
stp.execute(tname, phone)
public class SendtoPhp extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String tname = params[0]; //parameters you need to send to server
String phone = params[1];
String data = "";
int tmp;
try {
URL url = new URL("http://your.server.com/"); //url to php code
String urlParams = "tname=" + tname + "&tphone=" + phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
//System.out.println(data);
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
try {
//You might receive something on server code execution using JSON object
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have been working on creating a login/register feature for an app I'm working on (NOTE: this app is for my own personal use right now, so I'm not looking to make my passwords super secure as of now). When I click the register button when running my app on an emulated Android device, Android Studio doesn't throw any errors, but nothing shows up when I check PHP MyAdmin. I've used different username and password combos (the ones here are obviously examples), a bunch of different localhost/127.0.0.1/10.0.2.2 combinations, and nothing seems to be working. When testing it online, 10.0.2.2:8080/android_login_api/register.php says the page cannot be displayed. localhost:8080/android_login_api/register.php at least displays, but with errors saying there is an unknown host (being 10.0.2.2:8080). Also, I am using Port 8080 with WAMP. Any help would be greatly appreciated, thank you!
register.php:
<?php
$con = mysqli_connect("10.0.2.2:8080" , "EXAMPLE_USERNAME" , "EXAMPLE_PASSWORD" , "android_api");
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
RegisterRequest.java:
package example.com.musicapptest;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Carter Klein on 6/26/2016.
*/
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:8080/android_login_api/register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java:
package example.com.musicapptest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText name = (EditText) findViewById(R.id.name);
final EditText email = (EditText) findViewById(R.id.email);
final EditText password = (EditText) findViewById(R.id.password);
final Button registerButton = (Button) findViewById(R.id.btnRegister);
final Button toLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clickName = name.getText().toString();
final String clickEmail = email.getText().toString();
final String clickPassword = password.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
boolean success = jsonResponse.getBoolean(Integer.parseInt("success"));
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(clickName, clickEmail, clickPassword, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
Apparently you are trying to connect to an invalid mysql host. In the first line of your PHP code the first parameter should be the MySql server address, not the WebServer address.