我正在尝试使用Volley更新包含图片和其他详细信息的个人资料。
我必须转换图像文件并将其作为参数发送到url。
我还必须解析所有其他细节以更新个人资料。
如何更新个人资料图片?
url = "http://192.168.1.30:1021/mobileapi/profile_update.html?&user_id="+user+"&firstname="+First.getText().toString()+
"&lastname="+last.getText().toString()+"&secondaryemail="+sEmail.getText().toString()+
"&phonemobile="+mob.getText().toString()+"&aboutus="+work.getText().toString()+"&phonework="+phone.getText().toString()+
"&skypeid="+skypeid.getText().toString()+"&gender="+gender+"&smtp_password="+mpass.getText().toString()+"&image="+fos;
url=url.trim().replaceAll("\\s+","");
System.out.println("url" + url);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.dismiss();
queue = Volley.newRequestQueue(getActivity());
request = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
System.out.println("updaa" + response.toString());
JSONObject update = response.getJSONObject(0);
int httpcode = Integer.parseInt(update.getString("status"));
if (httpcode == 200) {
String mess = update.getString("message");
Toast.makeText(getActivity(), mess, Toast.LENGTH_LONG).show();
int userid = Integer.parseInt(update.getString("user_id"));
String fname = update.getString("firstname");
String lname = update.getString("lastname");
String mail = update.getString("email");
String smail=update.getString("secondary_email");
/* String ph= String.valueOf(Integer.parseInt(update.getString("phone_work")));
String phone= String.valueOf(Integer.parseInt(update.getString("phone_mobile")));*/
String skype_id = update.getString("skype_id");
String user_title = update.getString("user_title");
String imgUrl = update.getString("image");
editor.putString("name", fname);
editor.putString("userid", String.valueOf(userid));
editor.putString("lname",lname);
editor.putString("mail",mail);
editor.putString("skype",skype_id);
editor.putString("image",imgUrl);
// editor.putString("phone", String.valueOf(ph));
editor.putString("work",user_title);
editor.putString("smail",smail);
// editor.putString("phone", String.valueOf(phone));
editor.commit();
} else {
JSONObject typ = response.getJSONObject(0);
String message = typ.getString("message");
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("result" + error.getLocalizedMessage()+"__"+error.getMessage());
Log.e("Volley", "Error");
}
}){
};
queue.add(request);
}
}
});
return view;
}
private void opengallery() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == PICK_IMAGE_REQUEST && intent != null && intent.getData() != null) {
Uri uri = intent.getData();
try {
/*Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));*/
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
Log.d("TAG", String.valueOf(bitmap));
Bpro.setImageBitmap(bitmap);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(uri + ".png");
file = new File(extStorageDirectory, uri + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + uri);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);
/* fos = new FileOutputStream(f);
fos.write(bitmapdata);*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON回复
[{
"smtp_password":"abdul",
"status":"200",
"user_type":"2",
"skype_id":"skype",
"emp_id":"N0418",
"phone_work":"9864545454",
"image":"http:\/\/192.168.1.30:1021\/uploads\/Nandha\/profile_image\/180_200\/45571.png",
"lastname":"Rahman",
"firstname":"Abdul",
"user_title":"android",
"message":"Profile has been updated successfully",
"email":"4dZR9RLF@gmail.com",
"gender":"1",
"user_id":"45571",
"secondary_email":"abdul@gmail.com",
"phone_mobile":"9892545454"
}]
答案 0 :(得分:1)
使用此代码..对我有用。它发送多部分图像。
private void saveProfileDetails() {
// loading or check internet connection or something...
// ... then
String url = "http://51.76.27.90:8080/post/new/";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
System.out.println("statuscode is " + response.statusCode);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message + " Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message + " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message + " Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", "a@a.com");
params.put("category", "product");
params.put("type", "product");
params.put("title", "i am done ");
params.put("content", "contentssssssssssssssssssssssss");
params.put("location", "Bangalore");
return params;
}
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("imageC", new DataPart("file_avatar.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), colorImage.getDrawable()), "image/jpeg"));
params.put("imageBW", new DataPart("file_cover.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), blackAndWhiteImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
这是你的VollySingleton功能
/**
* Created by snehasish on 29/7/16.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Singleton volley to populate request into single queue.
*/
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
/**
* Private constructor, only initialization from getInstance.
*
* @param context parent context
*/
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruBitmapCache(mCtx);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
/**
* Singleton construct design pattern.
*
* @param context parent context
* @return single instance of VolleySingleton
*/
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
/**
* Get current request queue.
*
* @return RequestQueue
*/
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
/**
* Add new request depend on type like string, json object, json array request.
*
* @param req new request
* @param <T> request type
*/
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
/**
* Get image loader.
*
* @return ImageLoader
*/
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
如果它有帮助请让这个答案正确!