What would be the simplest way of posting data using Volley?

断了今生、忘了曾经 提交于 2019-12-25 03:29:10

问题


I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;

RegisterRequest;

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

This is CreateUser;

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

    }

Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?


回答1:


Never mess with code or else it will be confusing for you to handle things properly.

So just make another class and use it in your activity.

Have a look at this class i have written, you can use it anywhere and for any type of data request.

public class SendData {

private Context context;
private String url;
private HashMap<String, String> data;

private OnDataSent onDataSent;

public void setOnDataSent(OnDataSent onDataSent) {
    this.onDataSent = onDataSent;
}

public SendData(Context context, String url, HashMap<String, String> data) {
    this.context = context;
    this.url = url;
    this.data = data;
}

public void send(){
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(onDataSent != null){
                onDataSent.onSuccess(response);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if(onDataSent != null){
                onDataSent.onFailed(error.toString());
            }
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            map.putAll(data);
            return map;
        }

    };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
    RequestQueue requestQueue =  Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

public interface OnDataSent{
    void onSuccess(String response);
    void onFailed(String error);
}

}

and now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way

HashMap<String, String> data = new HashMap<>();
    data.put("username", "");//define the value
    data.put("password", "");//define the value
    data.put("is_admin", "");//define the value

    SendData sendData = new SendData(this, "", data); //defie the context and url properly
    sendData.setOnDataSent(new SendData.OnDataSent() {
        @Override
        public void onSuccess(String response) {
            //parse the response 
        }

        @Override
        public void onFailed(String error) {
            //something went wrong check the error
        }
    });
    sendData.send();

hope it helps

happy coding

if some problem occur lemme Know :)



来源:https://stackoverflow.com/questions/53375894/what-would-be-the-simplest-way-of-posting-data-using-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!