0

I am working on an android project. While registering a user, the data is unable to insert into the database. Here I am using web host and php server. I have checked my php code in postman it works fine.

My code:

RegisterActivity.java

This class is to retrieve the data from the xml file and make required validations for the constraints.

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class RegisterActivity extends AppCompatActivity {
Button bt_register;
TextInputLayout til_name, til_username, til_password, til_confirmPass, til_mobile, til_email;
ImageView iv_profile;

String name, username, password, email, mobile, profile, confirm;
RequestQueue requestQueue;
boolean IMAGE_STATUS = false;
Bitmap profilePicture;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register_activity);
    setTitle("Create An Account");
    initialize();//Function to initialize widgets
    //creating request queue
    requestQueue = Volley.newRequestQueue(RegisterActivity.this);
    //Adding onClickListener to the ImageView to select the profile Picture
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 1000);
            //result will be available in onActivityResult which is overridden
        }
    });
    bt_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = til_name.getEditText().getText().toString();
            username = til_username.getEditText().getText().toString();
            password = til_password.getEditText().getText().toString();
            email = til_email.getEditText().getText().toString();
            mobile = til_mobile.getEditText().getText().toString();
            confirm = til_confirmPass.getEditText().getText().toString();
            if (    //perform validation by calling all the validate functions inside the IF condition
                    validateUsername(username) &&
                            validateName(name) &&
                            validatePassword(password) &&
                            validateConfirm(confirm) &&
                            validateMobile(mobile) &&
                            validateEmail(email) &&
                            validateProfile()
                    ) {
                final ProgressDialog progress = new ProgressDialog(RegisterActivity.this);
                progress.setTitle("Please Wait");
                progress.setMessage("Creating Your Account");
                progress.setCancelable(false);
                progress.show();
                //Validation Success
                convertBitmapToString(profilePicture);
                RegisterRequest registerRequest = new RegisterRequest(username, name, password, mobile, email, profile, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("Response", response);
                        progress.dismiss();
                        try {
                            if (new JSONObject(response).getBoolean("success")) {
                                Toast.makeText(RegisterActivity.this, "Account Successfully Created", Toast.LENGTH_SHORT).show();
                                finish();
                            } else
                                Toast.makeText(RegisterActivity.this, "Something Has Happened. Please Try Again!", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                requestQueue.add(registerRequest);
            }
        }
    });
}
private void convertBitmapToString(Bitmap profilePicture) {
    /*
        Base64 encoding requires a byte array, the bitmap image cannot be converted directly into a byte array.
        so first convert the bitmap image into a ByteArrayOutputStream and then convert this stream into a byte array.
    */
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    profilePicture.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] array = byteArrayOutputStream.toByteArray();
    profile = Base64.encodeToString(array, Base64.DEFAULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1000 && resultCode == Activity.RESULT_OK && data != null) {
        //Image Successfully Selected
        try {
            //parsing the Intent data and displaying it in the imageview
            Uri imageUri = data.getData();//Geting uri of the data
            InputStream imageStream = getContentResolver().openInputStream(imageUri);//creating an imputstrea
            profilePicture = BitmapFactory.decodeStream(imageStream);//decoding the input stream to bitmap
            iv_profile.setImageBitmap(profilePicture);
            IMAGE_STATUS = true;//setting the flag
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
private void initialize() {
    //Initializing the widgets in the layout
    til_name = (TextInputLayout) findViewById(R.id.til_name_reg);
    til_username = (TextInputLayout) findViewById(R.id.til_username_reg);
    til_password = (TextInputLayout) findViewById(R.id.til_password_reg);
    til_confirmPass = (TextInputLayout) findViewById(R.id.til_confirm_reg);
    til_mobile = (TextInputLayout) findViewById(R.id.til_mobile_reg);
    til_email = (TextInputLayout) findViewById(R.id.til_email_reg);
    bt_register = (Button) findViewById(R.id.bt_register);
    iv_profile = (ImageView) findViewById(R.id.im_profile);
}
private boolean validateUsername(String string) {
    if (string.equals("")) {
        til_username.setError("Enter A Username");
        return false;
    } else if (string.length() > 50) {
        til_username.setError("Maximum 50 Characters");
        return false;
    } else if (string.length() < 6) {
        til_username.setError("Minimum 6 Characters");
        return false;
    }
    til_username.setErrorEnabled(false);
    return true;
}
private boolean validateName(String string) {
    if (string.equals("")) {
        til_name.setError("Enter Your Name");
        return false;
    } else if (string.length() > 50) {
        til_name.setError("Maximum 50 Characters");
        return false;
    }
    til_name.setErrorEnabled(false);
    return true;
}
private boolean validatePassword(String string) {
    if (string.equals("")) {
        til_password.setError("Enter Your Password");
        return false;
    } else if (string.length() > 32) {
        til_password.setError("Maximum 32 Characters");
        return false;
    } else if (string.length() < 8) {
        til_password.setError("Minimum 8 Characters");
        return false;
    }
    til_password.setErrorEnabled(false);
    return true;
}
private boolean validateConfirm(String string) {
    if (string.equals("")) {
        til_confirmPass.setError("Re-Enter Your Password");
        return false;
    } else if (!string.equals(til_password.getEditText().getText().toString())) {
        til_confirmPass.setError("Passwords Do Not Match");
        til_password.setError("Passwords Do Not Match");
        return false;
    }
    til_confirmPass.setErrorEnabled(false);
    return true;
}
private boolean validateMobile(String string) {
    if (string.equals("")) {
        til_mobile.setError("Enter Your Mobile Number");
        return false;
    }
    if (string.length() != 10) {
        til_mobile.setError("Enter A Valid Mobile Number");
        return false;
    }
    til_mobile.setErrorEnabled(false);
    return true;
}
private boolean validateEmail(String string) {
    if (string.equals("")) {
        til_email.setError("Enter Your Email Address");
        return false;
    } else if (!Patterns.EMAIL_ADDRESS.matcher(string).matches()) {
        til_email.setError("Enter A Valid Email Address");
        return false;
    }
    til_email.setErrorEnabled(false);
    return true;
}
private boolean validateProfile() {
    if (!IMAGE_STATUS)
        Toast.makeText(this, "Select A Profile Picture", Toast.LENGTH_SHORT).show();
    return IMAGE_STATUS;
}
}

RegisterRequest.java

This class is to connect to php the server

package com.beasportapp.beasport;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_URL = "https://app-1526877802.000webhostapp.com/register.php";
private Map<String, String> parameters;
public RegisterRequest(String username, String name, String password, String mobile, String email, String image, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_URL, listener, null);
    parameters = new HashMap<>();
    parameters.put("username", username);
    parameters.put("name", name);
    parameters.put("password", password);
    parameters.put("mobile", mobile);
    parameters.put("email", email);
    parameters.put("image", image);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
    return parameters;
}
}

I guess the problem is with the image. Are there any errors in my code? Can anyone please check it and help me to get the data inserted into the database?

Lahari
  • 461
  • 1
  • 3
  • 16
  • From where are you invoking the register request class? – Eldho Paul Konnanal May 23 '18 at 04:34
  • sorry, I've missed some code. Please check my `RegisterActivity.java` @EldhoPaulKonnanal – Lahari May 23 '18 at 05:02
  • reffet this [link](https://www.simplifiedcoding.net/android-volley-tutorial/) – Sam Raju May 23 '18 at 05:16
  • @SamRaju sir, I want the image to be there in the registration page. – Lahari May 23 '18 at 05:18
  • i post a code sample for you from your answer but i recommend to you to use [Retrofit library](https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/) for sending files to backend and its easy to use. because for larger image file its hard to convert bitmap to string – Sam Raju May 23 '18 at 06:05
  • Retrofit is fine , agin if you insist on file upload using volley itself its better to use MultipartRequst instead of converting image to string as its too risky. – Eldho Paul Konnanal May 23 '18 at 06:17

2 Answers2

1

In your code you are trying to convert Bitmap to String and trying to post it as a String parameter. This calls will fail because for a bigger image the length of string will be longer and the string might only get partially uploaded. The correct method to follow for a file/image upload using Volley is by using MultipartRequest which you can refer to in this link .

public class MultipartRequest extends Request<String> {

private MultipartEntity entity = new MultipartEntity();

private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";

private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;




public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, String stringPart) //File- your image file, stringPart- your string parameters.
{
    super(Method.POST, url, errorListener);

    mListener = listener;
    mFilePart = file;
    mStringPart = stringPart;
    buildMultipartEntity();
}

private void buildMultipartEntity()
{
    entity.addPart(FILE_PART_NAME, new FileBody(mFilePart)); //Add your image file parameter here
    try
    {

        entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));//Add your request string parameters one by one here
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
    return Response.success("Uploaded", getCacheEntry());
}

@Override
protected void deliverResponse(String response)
{
    mListener.onResponse(response);
}

}

Further, before uploading the image you can use some compression mechanism so that the entire upload process is faster. Refer this link for image compression.

Eldho Paul Konnanal
  • 500
  • 1
  • 4
  • 23
  • In my code where I have to replace this **MultipartRequest**. @Eldho Paul Konnanal – Lahari May 23 '18 at 05:59
  • You have to replace the entire RegisterRequest class with MultipartRequest class as shown in that link. – Eldho Paul Konnanal May 23 '18 at 06:02
  • In that **RegisterRequest** class itself the image should be compressed and also anything else I should change in **RegisterActivity** sir @Eldho Paul Konnanal – Lahari May 23 '18 at 06:04
  • Please check the updated answer. Image should be compressed from RegisterActivity itself before the network call. And replace your RegisterRequest class with Multipart request class. – Eldho Paul Konnanal May 23 '18 at 06:12
  • This **MultipartRequest** which you gave above takes only the image but not for other details right! I've to write the code for remaining attributes also @Eldho Paul Konnanal – Lahari May 23 '18 at 06:28
  • You can add as many details as you want to that code. I've commented where you should add your other parameters – Eldho Paul Konnanal May 23 '18 at 06:31
-2

Try this code

private void register(){

    loading = new ProgressDialog(RegisterActivity.this);
    loading.setMessage("UpLoading...");
    loading.setCancelable(true);
    loading.show();

    String image = null;
     name = til_name.getEditText().getText().toString();
     username = til_username.getEditText().getText().toString();
     password = til_password.getEditText().getText().toString();
     email = til_email.getEditText().getText().toString();
     mobile = til_mobile.getEditText().getText().toString();
     confirm = til_confirmPass.getEditText().getText().toString();

    if (bitmap!=null){
        image = getStringImage(bitmap);
    }
    if (email.isEmpty()){loading.dismiss();textEmail.setError("Enter Email");
    }else if (name.isEmpty()){loading.dismiss();textUsername.setError("Enter Name");
    }else if (password.isEmpty()){loading.dismiss();textPassword.setError("Enter Password");
    }else if (bio.isEmpty()){loading.dismiss();textBio.setError("Enter something about you");
    }else {
        final String finalImage = image;
        StringRequest stringRequest=new StringRequest(com.android.volley.Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                 try {
                        if (new JSONObject(response).getBoolean("success")) {
                            Toast.makeText(RegisterActivity.this, "Account Successfully Created", Toast.LENGTH_SHORT).show();
                            finish();
                        } else
                            Toast.makeText(RegisterActivity.this, "Something Has Happened. Please Try Again!", Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String
                //String image = getStringImage(thumbnail);

                //Getting Image Name

                String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
                //Creating parameters
                Map<String,String> parameters = new Hashtable<String, String>();

                //Adding parameters

                parameters.put("username", username);
                parameters.put("name", name);
                parameters.put("password", password);
                parameters.put("mobile", mobile);
                parameters.put("email", email);
                parameters.put("image", image);

                //returning parameters
                return parameters ;
            }
        };
        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

}

and code for getting stringimage from bitmap

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}
Sam Raju
  • 189
  • 8
  • I should use this code in **RegisterRequest** class? @SamRaju – Lahari May 23 '18 at 06:10
  • you can use this `register ();` method in register activity button click like ` bt_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { register(); }` @band_cherry – Sam Raju May 23 '18 at 06:14