使用Volley

时间:2017-08-31 16:04:22

标签: php android android-volley

我正在尝试更新具有以下属性的数据库 -

username first_name last_name email password

使用以下php代码:

<?php
    $con = mysqli_connect("localhost", "id2748657_users", "users", "id2748657_users");

    $username = $_POST["username"];
    $first_name = $_POST["first_name"];
    $last_name = $_POST["last_name"];
    $email = $_POST["email"];
    $password = $_POST["password"];

    $statement = mysqli_prepare($con, "INSERT INTO users (username, first_name, last_name, email, password) VALUES (?, ?, ?, ?,?)");
    mysqli_stmt_bind_param($statement, "sssss", $username, $first_name, $last_name, $email, $password);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;  

    echo json_encode($response);
?>

这是我用来发出请求的类:

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_REQUEST_URL = "http://fibi.000webhostapp.com/register.php";
    private Map<String,String> params;

    public RegisterRequest(String username, String first_name, String last_name,
                           String email, String password,

                           Response.Listener<String> listener){

        super(Method.POST, REGISTER_REQUEST_URL,listener, null);
        params = new HashMap<>();

        params.put("username", username);
        params.put("first_name", first_name);
        params.put("last_name", last_name);
        params.put("email", email);
        params.put("password", password);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}

这是注册活动:

package com.android.fiby;

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 etFirstname = (EditText) findViewById(R.id.etFirstname);
        final EditText etLastname = (EditText) findViewById(R.id.etLastname);
        final EditText etEmail = (EditText) findViewById(R.id.etEmail);
        final EditText etPassword = (EditText) findViewById(R.id.etPassword);


        final Button bSignUp = (Button) findViewById(R.id.btSignUp);

        bSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String username = etUsername.getText().toString();
                final String first_name = etFirstname.getText().toString();
                final String last_name = etLastname.getText().toString();
                final String email = etEmail.getText().toString();
                final String password = etPassword.getText().toString();

                Response.Listener<String> response = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject json_response = new JSONObject(response);
                            boolean success = json_response.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(username, first_name, last_name, email, password, response);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);

            }
        });

    }
}

除了按下按钮无效外,我在浏览器中收到以下错误/警告:

Notice: Undefined index: username in /storage/ssd1/657/2748657/public_html/register.php on line 4

Notice: Undefined index: first_name in /storage/ssd1/657/2748657/public_html/register.php on line 5

Notice: Undefined index: last_name in /storage/ssd1/657/2748657/public_html/register.php on line 6

Notice: Undefined index: email in /storage/ssd1/657/2748657/public_html/register.php on line 7

Notice: Undefined index: password in /storage/ssd1/657/2748657/public_html/register.php on line 8
{"success":true}

我试图通过&#34;硬编码&#34; php文件中的字符串,并更新了数据库。似乎Volley不会更新params或其他东西。

2 个答案:

答案 0 :(得分:2)

执行:

<?php

//Always check that you are receiving a POST|GET request before running your codes.
if( !empty( $_POST ) )
{
    $con = mysqli_connect("localhost", "id2748657_users", "users", "id2748657_users");
    $response = array(); //set it to empty 

    $username    = $_POST["username"];
    $first_name = $_POST["first_name"];
    $last_name  = $_POST["last_name"];
    $email   = $_POST["email"];
    $password   = $_POST["password"];

    //Create your query
    $query="INSERT INTO users (username, first_name, last_name, email, password) VALUES (?, ?, ?, ?,?)";

    $statement = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($statement, "sssss", $username, $first_name, $last_name, $email, $password);

    //Get boolean `true | false` as resposne
    $response["success"] = mysqli_stmt_execute($statement);  

    echo json_encode($response);
}
?>

根据您的错误,这应该不会修复undefined index用户名,blah,blah

答案 1 :(得分:1)

我认为getParams()无法在你的截击请求中工作。您可以使用loopj库而不是凌空。它易于使用。请尝试下面的代码

在您的gradle中添加依赖

 compile 'com.loopj.android:android-async-http:1.4.9'

请求您的网络Api

     RequestParams params = new RequestParams();
    params.put("username", username);
    params.put("first_name", first_name);
    params.put("last_name", last_name);
    params.put("email", email);
    params.put("password", password);

        String url="http://fibi.000webhostapp.com/register.php";

        new AsyncHttpClient().post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
              String rs = new String(responseBody);

               // do whatever you want

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });