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();
}
}
}
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
I have a problem here ..My app is supposed to send 3 values to the database, from text box etName,etEmailand etPassword
but instead, it is not send anything ...I'm new in android and I don't know some of the things I wrote in my code as I am following some tutorials
this in my code for register
package com.xulucreatives.taxisiyaya;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RegisterActivity extends AppCompatActivity {
EditText etName,etEmail,etPassword;
Button btnReg;
final String url_Register ="http://taxinote.000webhostapp.com/register_user.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.RM);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
btnReg = findViewById(R.id.btn_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = etName.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
new RegisterUser().execute(Name,Email,Password);
// Toast.makeText(RegisterActivity.this,"Im working you bitch",Toast.LENGTH_LONG).show();
}
});
}
public class RegisterUser extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
String Name = strings[0];
String Email = strings[1];
String Password = strings[2];
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(finalURL)
.build();
Response response = null;
try{
response = okHttpClient.newCall(request).execute();
if(response.isSuccessful())
{
String result = response.body().string();
if(result.equalsIgnoreCase("uaser registered successfully"))
{
Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
else if(result.equalsIgnoreCase("user already exists")){
Toast.makeText(RegisterActivity.this,"User Already Exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(RegisterActivity.this,"Ooops ! Ran into a problem , try again",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"response not successful!! :/",Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public void showToast(final String Text){
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this,Text,Toast.LENGTH_LONG).show();
}
});
}
}
user_name, user_id and user_password are from my php file in the server
<?php
require_once('connect.php');
$userName = $_GET['user_name'];
$userID = $_GET['user_id'];
$userPassword = $_GET['user_password'];
$query = "select * from users where email = '$userID'";
$recordExists = mysqli_fetch_array(mysqli_query($conn, $query));
if(isset($recordExists)){
echo 'User already exists';
}else{
$query = "INSERT INTO users (name, email, password) VALUES ('$userName', '$userID', '$userPassword')";
if(mysqli_query($conn, $query)){
echo 'User registered successfully';
}else{
echo 'oops! please try again!';
}
}
?>
but its not working i dont know why
You are creating an invalid url
which is
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
and should be like this
String finalURL = url_Register + "?user_name=" + Name +
"&user_id="+ Email +
"&user_password="+ Password;
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
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));