说明: 在这里,我试图通过我的Android应用程序使用volley库将用户数据插入到MySQL数据库表中。我几乎完成了所有操作,但我的代码无效。
这是我的Registration.java活动
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);
}
}
}
在上面的类中,我有registeruser()方法,在单击注册按钮后执行。
我在statckoverflow中到处搜索但没有得到有效的解决方案。
如果我使用传统的http,那么它的工作正常。
这是我的http遗留代码
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);
}
}
以上班级工作得很好。没有使用凌空图书馆工作。
如果我使用REST api客户端add-one插入数据,那么我的数据已成功插入数据库。
这是我的日志
05-04 15:02:06.585 32275-32275/com.angelnx.angelnx.holidays E/name values: keyurkeyur.hirani@gmail.comkeyur
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
请帮我解决这个问题
答案 0 :(得分:1)
不要在标题上设置内容类型,而是尝试在正文内容上更改内容类型。
替换它:
@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;
}
用这个:
@Override
public String getBodyContentType() {
return "application/json";
}
您还可以尝试将内容类型设置为:application/x-www-form-urlencoded
,这是默认的内容类型。
答案 1 :(得分:0)
请尝试以下代码,看看它是否有效。我在发出请求时删除了getParams()方法并在新的JSONObject(params)中设置了参数。
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);
}
答案 2 :(得分:0)
要在Volley中调用post方法,请按照以下步骤操作。
将此方法放入您的应用程序类
private RequestQueue mRequestQueue;
public static synchronized BatooniApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
此代码写入您要调用Web服务的位置
/**
* 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);
}
准备传入post方法的json对象的方法
/**
* 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, "abc@gmail.com");
}
}catch (Exception ex){
ex.printStackTrace();
}
return params;
}
确保根据您的Web服务响应确定响应侦听器的传递对象,否则您不会回调该方法。