-3

I have a simple registration script, but android studio isnt properly putting data into the php script. I ran the php script on a browser, and it puts data in just fine, but android studio isnt doing it right.

Here is the registerrequest script.

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
    private Map<String, String> params;
    public RegisterRequest(String username, String password,String isAdmin,
                           Response.Listener<String> listener,
                           Response.ErrorListener errListener){
        super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
        params = new HashMap<>();
        params.put("username",username);
        params.put("password",password);
        params.put("isAdmin",isAdmin+"");
    }

    public Map<String, String> getparams() {
        return params;
    }
}

here is the create user script

public class CreateUser extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user);
        this.setTitle("Create User");
        final EditText username1 = findViewById(R.id.Createusername);
        final EditText password1 = findViewById(R.id.CreatePassword);
        final Switch isAdmin = findViewById(R.id.isadmin);
        final Button createuser = findViewById(R.id.createuserbtn);
        if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
            isAdmin.setVisibility(View.GONE);
        }
        createuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username = username1.getText().toString();
                final String password = password1.getText().toString();
                final String isadmin = isAdmin.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response Value: ", response);
                            if (response.equals("success")){
                                Intent intent = new Intent(CreateUser.this, MainActivity.class);
                                CreateUser.this.startActivity(intent);
                            }else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry",null)
                                        .create()
                                        .show();
                        }
                    }
                };Response.ErrorListener errorListener = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
                    }
                };
                RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
                RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
                queue.add(registerRequest);
            }
        });

    }

here is the php script

<?php
    $db_host = '192.168.*.*:3306';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'test';
    var_dump($_POST["username"]);//line 6
    $con = mysqli_connect($db_host,'root',$db_pass,$db_name);
    if($con){
        echo "connection successful";
    }
    if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
    }
    if(isset($_POST["isAdmin"]) &&  isset($_POST["username"]) && isset($_POST["password"]))
{
    $username = $_POST["username"];
    $password = $_POST["password"];
    $isAdmin = $_POST["isAdmin"];

    $statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($statement,'ssi',$username,$password,$isAdmin);
    mysqli_stmt_execute($statement);

    if(!$statement) 
    {
         printf("Prepare failed: %s\n", mysqli_error($con)); 
    }

    echo "success";
}
else
 echo "values not set";
?>

When i run this, the app creates the retry error popup message. And the output is this;

Notice: Undefined index: username in C:\xampp\htdocs\phptesting\Register.php on line 6 NULL connection successfulvalues not set

I believe its complaining that username isnt anything. Which is a huge problem because other variables are defined below, and I do not know if they got through if the script stopped this early I appreciate all help, thank you

RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
Alec Harvey
  • 113
  • 10
  • Not an Android guy, but obviously either you are posting nothing or you are not posting. Are you sure this is configured to use a POST and not a GET – RiggsFolly Nov 16 '18 at 13:51
  • Isn't this basically the same question as https://stackoverflow.com/questions/53303346/php-returns-undefined-index-to-android-studio – Patrick Q Nov 16 '18 at 13:51
  • 1
    @PatrickQ Yes and a few other, need to take pity on this guy and find him a Android person – RiggsFolly Nov 16 '18 at 13:52
  • @PatrickQ no, actually, this error only returns 1 undefined index. That question wasnt even answered properly to begin with. My actual problem is with Android studio, not PHP. Everyone on the question thought otherwise – Alec Harvey Nov 16 '18 at 13:53
  • Your Java code look nothing like [this answer](https://stackoverflow.com/a/2938787/2310830) are you sure you are doing the Java stuff correctly? – RiggsFolly Nov 16 '18 at 13:54
  • initialise params in getParams method – Imtiyaz Khalani Nov 16 '18 at 13:54
  • 2
    Welp, there goes any chance of anyone here helping you. Good luck my friend. – Patrick Q Nov 16 '18 at 13:56
  • @RiggsFolly are you sure you know what you are talking about? there are multiple ways to slice a cake, so just because my script may not LOOK like theirs doesnt mean it has to. – Alec Harvey Nov 16 '18 at 13:56
  • @ImtiyazKhalani isnt params already initialized in its constructor? – Alec Harvey Nov 16 '18 at 13:58
  • No of course not, but as yours is obviously not doing what you hoped it would possibly you would move forward by comparing it to code that apparently does work. _Small Note_ I get no Rep for spending time and effort making question more readable and understandable – RiggsFolly Nov 16 '18 at 13:59
  • @RiggsFolly I understand, and apologize for being irrational. This project has me heated – Alec Harvey Nov 16 '18 at 14:02
  • @RiggsFolly I cannot use that answer since most of the syntax has become deprecated and doesn't seem to contain the proper solution – Alec Harvey Nov 16 '18 at 14:18

1 Answers1

0

Try to get your json like that in php file

$json = json_decode(file_get_contents('php://input'), true);
Benjamin
  • 371
  • 1
  • 2
  • 16
  • Will this change the incoming data from android to json? Because im sure android is sending strings, so it sounds like i need to change it to json in android – Alec Harvey Nov 16 '18 at 14:01
  • No this have only effect on how your PHP get the POST parameter, that was the solution for me when I had the same problem than you – Benjamin Nov 16 '18 at 14:05
  • Nothing happened – Alec Harvey Nov 16 '18 at 14:15
  • How did you get the param after that? Its something like $json->['NameOfParam']; – Benjamin Nov 16 '18 at 14:22
  • If I don't say mistake, I had the same problem month only with POST method, because the param was not supported with POST method, try to see inside the class if the POST method correctly add param to request ( It's possible I tell you mistake, I've bad memory aha) – Benjamin Nov 16 '18 at 15:25