Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法将数据输入android中的数据库_Java_Android - Fatal编程技术网

Java 无法将数据输入android中的数据库

Java 无法将数据输入android中的数据库,java,android,Java,Android,我正在从事一个android项目。注册用户时,数据无法插入数据库。这里我使用的是web主机和phpserver。我已经在postman中检查了我的php代码,它工作正常 我的代码: RegisterActivity.java 此类用于从xml文件中检索数据,并对约束进行必要的验证 import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android

我正在从事一个
android
项目。注册用户时,数据无法插入数据库。这里我使用的是web主机和
php
server。我已经在postman中检查了我的
php
代码,它工作正常

我的代码:

RegisterActivity.java

此类用于从
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;
}
}

我想问题在于图像。我的代码中有错误吗?任何人都可以检查它并帮助我将数据插入数据库吗?

在您的代码中,您正在尝试将位图转换为字符串,并尝试将其作为字符串参数发布。此调用将失败,因为对于更大的图像,字符串的长度将更长,并且字符串可能只能部分上载。 使用Volley上传文件/图像的正确方法是使用MultipartRequest,您可以在本文中参考

public类MultipartRequest扩展请求{
私有多方实体=新多方实体();
私有静态最终字符串文件\u PART\u NAME=“FILE”;
私有静态最终字符串字符串\u PART\u NAME=“text”;
私人最终回应。监听器;
私有最终文件mFilePart;
私有最终字符串mStringPart;
公共多部分请求(字符串url,Response.ErrorListener ErrorListener,
Response.Listener-Listener,File-File,stringPart)//File-您的图像文件,stringPart-您的字符串参数。
{
super(Method.POST、url、errorListener);
mListener=监听器;
mFilePart=文件;
mStringPart=stringPart;
buildMultipartEntity();
}
私有void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME,new FileBody(mFilePart));//在此处添加图像文件参数
尝试
{
entity.addPart(STRING_PART_NAME,new StringBody(mStringPart));//在此处逐个添加请求字符串参数
}
捕获(不支持的编码异常e)
{
截击日志(UnsupportedEncodingException);
}
}
@凌驾
公共字符串getBodyContentType()
{
返回实体.getContentType().getValue();
}
@凌驾
公共字节[]getBody()抛出AuthFailureError
{
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
尝试
{
实体书面形式(bos);
}
捕获(IOE异常)
{
e(“向ByteArrayOutputStream写入IOException”);
}
返回bos.toByteArray();
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应)
{
返回Response.success(“上传”,getCacheEntry());
}
@凌驾
受保护的void deliverResponse(字符串响应)
{
mListener.onResponse(response);
}
}

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

请尝试此代码

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

}

从哪里调用register request类?抱歉,我遗漏了一些代码。请检查我的
注册活动。java
@eldhopaulkonanalreffet this@SamRaju先生,我希望图像出现在注册页面中。我根据您的回答为您发布了一个代码示例,但我建议您使用该示例将文件发送到后端,并且易于使用。因为对于较大的图像文件,在我的代码中很难将位图转换为字符串,我必须替换这个多部分请求@Eldho Paul Konnanal您必须将整个RegisterRequest类替换为该链接中所示的MultipartRequest类。在该RegisterRequest类本身中,应压缩映像,以及我应在RegisterActivity sir@Eldho Paul Konnanal中更改的任何内容。请检查更新的答案。在网络调用之前,应该从RegisterActivity本身压缩映像。并将RegisterRequest类替换为Multipart请求类。您上面给出的MultipartRequest仅获取图像,而不获取其他详细信息,对吧!我还必须为其余属性编写代码@Eldho Paul KonnanalI是否应该在RegisterRequest类中使用此代码@SamRajuyou可以使用这个
寄存器()方法单击类似“bt_register.setOnClickListener(新视图.OnClickListener(){@Override public void onClick(视图v){register();}`@band_
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);
}
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);
    }

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