无法在android中将数据输入数据库

时间:2018-05-23 04:22:49

标签: java android

我正在开展php项目。注册用户时,数据无法插入数据库。这里我使用的是web主机和xml服务器。我已经在邮递员中检查了我的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; } } 代码,它运行正常。

我的代码:

RegisterActivity.java

此类用于从php文件中检索数据,并对约束进行必要的验证。

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

RegisterRequest.java

此类用于连接onClick()服务器

vb.net

我猜问题出在图片上。我的代码中有错误吗?有人可以检查一下,帮我把数据插入数据库吗?

2 个答案:

答案 0 :(得分:1)

在您的代码中,您尝试将Bitmap转换为String并尝试将其作为String参数发布。此调用将失败,因为对于较大的图像,字符串的长度将更长并且字符串可能仅部分上载。 使用Volley进行文件/图像上传的正确方法是使用 MultipartRequest ,您可以在此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);
}

}

此外,在上传图像之前,您可以使用一些压缩机制,以便整个上传过程更快。请参阅此link进行图像压缩。

答案 1 :(得分:-2)

试试此代码

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

}

和从位图

获取stringimage的代码
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;
}