Android单选按钮值无法存储在phpmysql中:“必填字段缺失”

So i've created several editText fields in Android studio with each connected to the mysql through php (I'm using xampp btw). Now my problem is, **it returns a "Required Fields are Missing"**x after changing the tbuyer from editText view to a 2 RadioButton namely(r_tb; r_ntb) inside a RadioGroup.

Now in order to get a string from those two, I declared a String role=" "; with condition using the RadioGroup:

if (radioGroup.getCheckedRadioButtonId() == r_tb.getId())
        {
            role = "Trade Buyer";
        }
        else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId())
        {
            role = "Non Trade Buyer";
        }

then pass it along the parameters that will be sent to hash map:

@Override
            protected Map<String, String> getParams() throws AuthFailureError { //put all parameters that will be sent to hash map
                Map<String, String> params = new HashMap<>();
                params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50
                params.put("date", date);
                params.put("lname", lname);
                params.put("fname", fname);
                params.put("mi", mi);
                params.put("email", email);
                params.put("city", city);
                params.put("country", country);
                params.put("tbuyer", role); // check code; String created from radio button

                return params;
            }

then call a string request for json, so that we will know if the registration is successful or not. But as I said, it returns **Required fields are missing"

These are my codes for Buyer_Registration_Activity.java:

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

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 com.example.smdojt.manilafame.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Buyer_Registration_Activity extends AppCompatActivity implements View.OnClickListener{

    private EditText editTextCompanyName, editTextDate, editTextLastName, editTextFirstName, editTextMiddleInitial
            , editTextCity, editTextCountry, editTextType, editTextEmail;
    private Button buttonRegister;
    private ProgressDialog progressDialog;
    String role = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_registration);
        //this.setTitle("Buyer Registration");

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);

        editTextCompanyName = (EditText) findViewById(R.id.editTextCompanyName);
        editTextDate = (EditText) findViewById(R.id.editTextDate);
        editTextLastName = (EditText) findViewById(R.id.editTextLastName);
        editTextFirstName = (EditText) findViewById(R.id.editTextFirstName);
        editTextMiddleInitial = (EditText) findViewById(R.id.editTextMiddleInitial);
        editTextCity = (EditText) findViewById(R.id.editTextCity);
        editTextType = (EditText) findViewById(R.id.editTextType);
        editTextCountry = (EditText) findViewById(R.id.editTextCountry);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);

        buttonRegister = (Button) findViewById(R.id.buttonRegister);
        progressDialog = new ProgressDialog(this);
        buttonRegister.setOnClickListener(this);

    }

    private void registerUser(){
        final String cname = editTextCompanyName.getText().toString().trim();
        final String date = editTextDate.getText().toString().trim();
        final String lname = editTextLastName.getText().toString().trim();
        final String fname = editTextFirstName.getText().toString().trim();
        final String mi = editTextMiddleInitial.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();
        final String city = editTextCity.getText().toString().trim();
        final String country = editTextCountry.getText().toString().trim();
        final String tbuyer = editTextType.getText().toString().trim();
        final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        final RadioButton r_tb = (RadioButton) findViewById(R.id.radio_tb);
        final RadioButton r_ntb = (RadioButton) findViewById(R.id.radio_ntb);

        if (radioGroup.getCheckedRadioButtonId() == r_tb.getId())
        {
            role = "Trade Buyer";
        }
        else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId())
        {
            role = "Non Trade Buyer";
        }
        progressDialog.setMessage("Registering User...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                com.example.smdojt.manilafame.sql_demo_2.Constants.URL_REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {//If there are no ERROR this method will be executed
                        progressDialog.dismiss();
                        //we will get the json object
                        try {
                            JSONObject jsonObject = new JSONObject(response);  //create json object
                            Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) { // Else, this method will be executed
                        progressDialog.hide();
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError { //put all parameters that will be sent to hash map
                Map<String, String> params = new HashMap<>();
                params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50
                params.put("date", date);
                params.put("lname", lname);
                params.put("fname", fname);
                params.put("mi", mi);
                params.put("email", email);
                params.put("city", city);
                params.put("country", country);
                params.put("tbuyer", role); // check code; String created from radio button
                //params.put("tbuyer", tbuyer);
                return params;
            }
        };

        //add stringRequest (Line 55)
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View view) {
        if (view==buttonRegister)
        {
            registerUser();
        }
    }
}

These are my codes for DBOperations.php (Crud operations declaration)

<?php
//manage all php and db operations

    class DbOperations
    {
        private $con;

        function __construct()
        {
            require_once dirname(__FILE__).'/DbConnect.php'; //import dbconnect to dboperations

            $db = new DbConnect(); //create db connect object

            $this->con = $db->connect();
        }

        //CRUD Operations below
        //Create-----------------------------------------------------------------------------------------------

        function registerBuyer($cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer)
        {
        //$password = md5($password); //encrypt password
        $stmt = $this->con->prepare("INSERT INTO `mfmis_buyers`.`buyers` (`id`, `cname`, `date`, `lname`, `fname`, `mi`, `email`, `country`, `city`, `tbuyer`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); //statement

        //find actual parameters /bind param

        $stmt->bind_param("sssssssss", $cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer); //bind to query

        //execute query below
        if ($stmt->execute()) //as soon as this line is called, data will be inserted into DB
        {
            return true;
        }
        else 
        {
            return false;
        }
        }

        //-----------------------------------------------------------------------------------------------------
    }
?>

and these are my codes for registerBuyer.php (where all my error statements comes from including "REQUIRED FIELDS ARE MISSING")

<?php

require_once '../includes/DbOperations.php';
$response = array();

if($_SERVER['REQUEST_METHOD']=='POST')
{
    if(
        isset($_POST['cname']) and
        isset($_POST['date']) and
        isset($_POST['lname']) and
        isset($_POST['fname']) and
        isset($_POST['mi']) and
        isset($_POST['email']) and
        isset($_POST['country']) and
        isset($_POST['city']) and
        isset($_POST['tbuyer']))
        {
        //operate the data further

        $db = new DbOperations();

        if($db->registerBuyer(
            $_POST['cname'],
            $_POST['date'],
            $_POST['lname'],
            $_POST['fname'],
            $_POST['mi'],
            $_POST['email'],
            $_POST['country'],
            $_POST['city'],
            $_POST['tbuyer']
            ))
        {
            $response['error'] = false;
            $response['message'] = "Buyer Registered Successfully";
        }
        else
        {
            $response['error'] = true;
            $response['message'] = "Some error occured try again";
        }

    }
    else
    {
        $response['error'] = true;
        $response['message'] = "Required fields are missing";
    }
}
else
{
    $response['error'] = true;
    $response['message'] ="Invalid request";
}

echo json_encode($response);

?>
dongnao1908
dongnao1908 缺少必填字段是来自Android设备的Toast消息。这就是为什么我从java调用jsonObject.getString(“message”)来从$Response中提取消息。role变量返回一个空字符串,这意味着单选按钮没有根据条件集正确获取字符串。
3 年多之前 回复
dongzhun8449
dongzhun8449 嗯,你可能是对的,你能在发送到服务器之前显示角色变量的内容吗?只是为了看它是否为空
3 年多之前 回复
dongyou9373
dongyou9373 我不这么认为,如果没有从服务器收到字符串,客户端如何知道字符串必填字段?
3 年多之前 回复
dsfs587465
dsfs587465 是的,他们正确地接收所有数据字符串。也许问题出在客户端(Android工作室)
3 年多之前 回复
dongqian6484
dongqian6484 我正在使用邮递员通过网络测试POST和GET,但这一次,我正在通过android测试它们。我应该做什么样的调试?它们都在我使用edittext时工作,但在使用1个变量的单选按钮时却没有
3 年多之前 回复
dongxun3777
dongxun3777 让我们在聊天中继续讨论。
3 年多之前 回复
duanfu3884
duanfu3884 什么是StringRequest?我只是想看看你的服务器端是否收到了所需的$_POST参数;也许你的客户端代码没有发送它们
3 年多之前 回复
dongliuxia9495
dongliuxia9495 我为.java添加了另一个代码
3 年多之前 回复
dongningwen1146
dongningwen1146 它没有返回任何东西,只有来自StringRequest的空白吐司
3 年多之前 回复
doujie4050
doujie4050 只有在$response['message']=“缺少必填字段”之后;调试这个;找到解决方案后,您将删除该语句
3 年多之前 回复
dongxixian7803
dongxixian7803 全部$回应?所以在每一行响应消息中,生病只需添加$response['post']=$_POST;?
3 年多之前 回复
drh47606
drh47606 请在$response中包含$_POST数据,如下所示:$response['post']=$_POST;看看你在服务器端获得了什么,让我知道
3 年多之前 回复

1个回答



因此,基于 role </ code>字符串,它甚至不会推送单个数据,因为连接在 第一个地方甚至都不正确。</ p>

所以我上面提到的代码正在运行,唯一阻碍的是我的 Constants.java </ strong >。 确保设置本地或在线连接并与xampp服务器保持一致。</ p>

  public class Constants {

public static final String ROOT_URL =“http:// 192.168.15.186/MFMIS/register/";
nn public static final String URL_REGISTER = ROOT_URL +“registerBuyer.php”;
}
</ code> </ pre>

确保你的 String ROOT_URL </ code>和 URL_REGISTER </ code>或任何其他本地和在线连接都是正确的。 否则,如果问题仍然存在,那么您的活动或xampp方面就会出现问题。</ p>
</ div>

展开原文

原文

So based on the role string, it doesn't push even a single data, because the connections in the first place aren't even correct.

So the codes I've mentioned above are working, the only one that is in the way is my Constants.java. Make sure your local or online connections are set and in line with the xampp server.

public class Constants {

    public static final String ROOT_URL = "http://192.168.15.186/MFMIS/register/";

    public static final String URL_REGISTER = ROOT_URL+"registerBuyer.php";
}

make sure your String ROOT_URL and URL_REGISTER or any other local and online connections are correct. Else if the problem persists, then there is something wrong with your activity or xampp side.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问