Reputation: 970
Explanation: Here, i am tried to insert user data into MySQL database table through my android application using volley library.I almost done everything but my code not working.
Here is my Registration.java activity
public class Registration extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout inputLayoutName,inputLayoutEmail,inputLayoutPassword;
private Button btnSignUp,btn_image;
private EditText inputName,inputEmail,inputPassword;
private Bitmap bitmap;
private ImageButton imageButton;
private CircleImageView circularImageView;
private int PICK_IMAGE_REQUEST = 1;
private String url="http://My_ip_add/test/v1/register";
private String KEY_NAME="name";
private String KEY_EMAIL="email";
private String KEY_PASSWORD="password";
private String name="";
private String email="";
private String password="";
private String image="";
// Map<String,String> params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.back_button));
}
circularImageView=(CircleImageView)findViewById(R.id.circleView);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password);
inputName = (EditText) findViewById(R.id.input_name);
inputEmail = (EditText) findViewById(R.id.input_email);
inputPassword = (EditText) findViewById(R.id.input_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
imageButton=(ImageButton)findViewById(R.id.imageButton);
btnSignUp.setOnClickListener(this);
imageButton.setOnClickListener(this);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword));
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public String getStringImage(Bitmap bmp){
String encodedImage = encodeToBase64(bmp,Bitmap.CompressFormat.JPEG,100);
return encodedImage;
}
public static String encodeToBase64(Bitmap image,Bitmap.CompressFormat compressFormat,int quality){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(compressFormat,quality,baos);
return Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.circularimage);
Bitmap circularBitmap = ImageConverter.getRoundedCornerBitmap(bitmap, 100);
circularImageView.setImageBitmap(circularBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private boolean validatePassword() {
if (inputPassword.getText().toString().trim().isEmpty()) {
inputLayoutPassword.setError(getString(R.string.err_msg_password));
requestFocus(inputPassword);
return false;
} else {
inputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void submitForm() {
if (!validateName()) {
return;
}
if (!validateEmail()) {
return;
}
if (!validatePassword()) {
return;
}
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.btn_signup) {
submitForm();
name=inputName.getText().toString().trim();
email=inputEmail.getText().toString().trim();
password=inputPassword.getText().toString().trim();
Log.e("res",""+password);
RegisterUser();
}
if(v.getId()==R.id.imageButton){
showFileChooser();
}
}
private void RegisterUser(){
JsonObjectRequest JsonObjReq=new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(Registration.this, response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Registration.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//return super.getParams();
name=inputName.getText().toString().trim();
email=inputEmail.getText().toString().trim();
password=inputPassword.getText().toString().trim();
Log.e("name values",""+name);
Map<String,String> params=new HashMap<>();
params.put(KEY_NAME,name);
params.put(KEY_EMAIL,email);
params.put(KEY_PASSWORD,password);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
//Adding request to the queue
requestQueue.add(JsonObjReq);
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name:
validateName();
break;
case R.id.input_email:
validateEmail();
break;
case R.id.input_password:
validatePassword();
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
In above class i have registeruser() method which execute after click on sign up button.
I search everywhere in statckoverflow but didn't got valid solution.
If i used a legacy http then it's working correctly.
Here is my http legacy code
private class Register extends AsyncTask<String,String,String>{
ServiceHandler sh=new ServiceHandler();
@Override
protected String doInBackground(String... params) {
List<NameValuePair> param=new ArrayList<>();
param.add(new BasicNameValuePair("name",name));
param.add(new BasicNameValuePair("email",email));
param.add(new BasicNameValuePair("password",password));
String jsonstr=sh.makeServiceCall(url,ServiceHandler.POST,param);
return jsonstr;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("RESPONSE",""+s);
}
}
Above class working very well.Not working using volley library.
if i insert the data using REST api client add-one then my data inserted successfully into the database.
Here is my log
05-04 15:02:06.585 32275-32275/com.angelnx.angelnx.holidays E/name values: [email protected]
05-04 15:02:06.684 32275-4459/com.angelnx.angelnx.holidays E/Volley: [200] BasicNetwork.performRequest: Unexpected response code 400 for http://ip_Addr/test/v1/register
05-04 15:02:10.197 32275-32345/com.angelnx.angelnx.holidays E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2c97bd0
Please help me to solve out this problem
Upvotes: 0
Views: 569
Reputation: 1764
Instead of setting the content type on the header, try to change it on the body contents.
Replace this:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
with this:
@Override
public String getBodyContentType() {
return "application/json";
}
You could also try setting the content type to: application/x-www-form-urlencoded
which is the default content type.
Upvotes: 1
Reputation: 244
For calling post method in Volley follow below steps.
Put this Method in Your Application Class
private RequestQueue mRequestQueue;
public static synchronized BatooniApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
This code write where you want to call web service
/**
* Making json object request
*/
private void makeRegistrationRequest() {
String url = "your url"
JSONObject requestJson = getJsonRequest();
// here we pass into Response.Listener JSONObject if you are getting jsonarray or string change it accordingly
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, requestJson,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// parse your response here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// TODO future task
return params;
}
};
// Adding request to request queue
Application.getInstance().addToRequestQueue(jsonObjReq,
AppConstant.METHOD_REGISTRATION);
}
Method for prepare json object for passing into post method
/**
* make json request
*
* @return
*/
private JSONObject getJsonRequest() {
JSONObject params = new JSONObject();
try {
params.put(KEY_FIRST_NAME, "Rohitashv");
params.put(KEY_LAST_NAME, "Jain");
params.put(KEY_PHONE_NUMBER, "12121212");
params.put(KEY_EMAIL_ADDRESS, "[email protected]");
}
}catch (Exception ex){
ex.printStackTrace();
}
return params;
}
Make sure pass object of Response Listener according to your web service response other wise you not get call back into the method.
Upvotes: 0
Reputation: 439
Please try the below code and see if it work. I removed the getParams() method and setting the parameters in the new JSONObject(params) when making the request.
private void RegisterUser(){
name=inputName.getText().toString().trim();
email=inputEmail.getText().toString().trim();
password=inputPassword.getText().toString().trim();
Log.e("name values",""+name);
Map<String,String> params=new HashMap<>();
params.put(KEY_NAME,name);
params.put(KEY_EMAIL,email);
params.put(KEY_PASSWORD,password);
JsonObjectRequest JsonObjReq=new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(Registration.this, response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Registration.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
//Adding request to the queue
requestQueue.add(JsonObjReq);
}
Upvotes: 0