dongxian3852 2017-03-22 06:37
浏览 74

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);

?>
  • 写回答

1条回答 默认 最新

  • duandu2980 2017-03-23 02:48
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择