My login is working properly, but my registration seems to not add the data to my database. I have tried to solve the problem for a long time with no luck. Maybe some of you "bright" people can help my dumb ass lol! Nevertheless here is everything: If you do help me, thanks in advance, btw I think it is a problem in the Register.php!
LoginActivity.java:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final Button bLogin = (Button) findViewById(R.id.bSignIn);
tvRegisterLink.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();
// Response received from the server
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");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
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);
}
});
}
}
LoginRequest.java:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "https://mysite567356ht7ieyjr6u7je.000webhostapp.com/Login.php";
private Map<String, String> params;
public LoginRequest(String username, String password, Response.Listener<String> listener) {
super(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;
}
}
Login.php:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $username, $password);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
RegisterActivity.java:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
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 etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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);
} 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(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
RegisterRequest.java:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://mysite567356ht7ieyjr6u7je.000webhostapp.com/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;
}
}
Register.php:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$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, "siss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
mysqli_stmt_bind_param($statement, "siss", $name, $username, $password);
In this line change siss to sss.
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
Having some trouble, this was weird because out of nowhere I'm getting this error:
If you do help me, thanks in advance! I don't think it is coming from the php, I suspect the LoginActivity or LoginRequest!
Full Error Code:
W/System.err: org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err: at com.tonikamitv.loginregister.LoginActivity$1.onResponse(LoginActivity.java:46)
W/System.err: at com.tonikamitv.loginregister.LoginActivity$1.onResponse(LoginActivity.java:42)
W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
LoginActivity.java:
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import com.startapp.android.publish.video.VideoListener;
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.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final Button bLogin = (Button) findViewById(R.id.bSignIn);
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String username = sharedPref.getString("username", "");
String password = sharedPref.getString("password", "");
if (username.length() > 0 && password.length() > 0) {
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");
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
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);
tvRegisterLink.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();
// Response received from the server
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");
String username = jsonResponse.getString("username");
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
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);
}
});
}
}
}
LoginRequest.java:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://gamerduo1.byethost15.com/Login.php";
private Map<String, String> params;
public LoginRequest(String username, String password, Response.Listener<String> listener) {
super(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;
}
}
Login.php:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $username, $password, $points, $time);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
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.
I am making an android application using android studio for Login/Register and i failed to send the Register information to the .php file.
Here is my code:
For LoginActivity :
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
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 etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.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);
} 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(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
For RegisterActivity:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
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 etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.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);
} 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(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
For RegisterRequest:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://mydomain.hostei.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int age, String password, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("age", age + "");
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
And the Register.php:
$con = mysqli_connect("mysql10.000webhost.com", "a3288368_user", "abcd1234", "a3288368_data");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
The communication between my database and the Register.php file working properly putting values by hand in the Register.php file.
But when i am waiting the values form the POST method i failed to communicate between my application and the Register.php
I have added internet permission to my project already,also compiled the volley library.
Any ideas what is going wrong?
Maybe there is a mistake on my Java code?
Thanks
Problem fixed.The error was on the php code
I changed echo json_encode($response);
with print_r(json_encode($response));