Android Picture Upload
Background: Picture upload is a function of general projects. This article extracts the process of picture upload in the project and makes a record, so as not to have nowhere to refer to in the future.
1. MainActivity 1 Interface Style: Click on the Add button to jump to the picture selection interface, this business logic is very simple, no code. But the blank part below is a recycleView, which is used to display pictures.
2. Click on the button to add pictures
It's used here.
https://github.com/yanzhenjie/Album The old man's encapsulated frame for reading pictures of mobile phones
You can choose local pictures or videos, or take pictures of recorded files, one line of code to get complex pictures.
If you are interested, you can refer to his usage documents.
Album.image(OnlineBookingUI3.this) // Select the picture.
.multipleChoice()
.requestCode(200 )
.camera(false)//Photographs are not allowed
.columnCount(3)//Column number
.widget(getWight())//Setting the title bar
.selectCount(20-//Default number mAdapter. getDatas (). size ()+1)
.listener(new AlbumListener<ArrayList<AlbumFile>>() {//Listen for the results of the selection, asynchronous
@Override
public void onAlbumResult(int requestCode, @NonNull ArrayList<AlbumFile> result) {
showHideText();
}
@Override
public void onAlbumCancel(int requestCode) {
}
})
.start();
Look at the widget (getWight ()// method of setting the title bar. When the selection is completed, we will call the method of the title bar when we return or confirm our choice.
/**
* Change the title of the picture selector
* @return
*/
public Widget getWight() {
return Widget.newDarkBuilder(context)
.statusBarColor(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimaryDark))
.toolBarColor(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimary))
.navigationBarColor(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimaryBlack))
.title("Photo list")
.mediaItemCheckSelector(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_WhiteGray),
ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimary))
.bucketItemCheckSelector(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_WhiteGray),
ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimary))
.buttonStyle(
Widget.ButtonStyle.newDarkBuilder(context)
.setButtonSelector(ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimary),
ContextCompat.getColor(context, com.yanzhenjie.album.R.color.album_ColorPrimaryDark))
.build()
)
.build();
}
Well, there is no call, just set the title bar, click back or confirm, the internal itself will listen, give us callbacks.
3. Complete the addition and display of pictures, and then need to consider the upload of pictures...
Using AsyncTask (Overall Code)
private class MyTask extends AsyncTask<Object, Object, RequestParams> {
@Override//Processing uploaded data
protected RequestParams doInBackground(Object... params) {
PurchaseParamsBean purchaseParamsBean = new PurchaseParamsBean();
purchaseParamsBean.setPurchaseFiles(getAllBase64Img());
RequestParams requestParams = new RequestParams();
requestParams.add("Source", 2 + "");
requestParams.add("tokenID", SPUtils.get(context, Constants.tokenID, "").toString());
requestParams.add("OpenId", "");
String value = new Gson().toJson(purchaseParamsBean);
requestParams.add("PurchaseParams", value);
for (int i = 0; i < mAdapter.getDatas().size(); i++) {
try {
String path = mAdapter.getDatas().get(i).getPath();
if (!TextUtils.isEmpty(path)) {
requestParams.put("files" + i, CompressUtil.getCompressPic(path, getCacheDir().getPath()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return requestParams;
}
//Make network requests
@Override
protected void onPostExecute(RequestParams requestParams) {
sendRequest(Http_Url.InsertHirePurchase, requestParams, OnlyIntModelBean.class, "", false, btn_perfectdata_submit, new BaseCallBack<OnlyIntModelBean>() {
@Override
public void onSuccess(OnlyIntModelBean onlyIntModelBean) {
if (onlyIntModelBean != null) {
if (onlyIntModelBean.getStatu() == 1) {
ToastL.show("Successful Booking");
AbsUI.startUI(context, MyOrderUI.class);
mAdapter.getDatas().clear();
mAdapter = null;
mRv = null;
stopUI(ui);
} else if (onlyIntModelBean.getStatu() == -2) {
ToastL.show(onlyIntModelBean.getMsg());
// StringUtils.IsOUTOFtime(context, OnlineBookingUI3.this.ui);
} else {
ToastL.show(onlyIntModelBean.getMsg());
}
}
}
}
(Code parsing)
Step by step, the Purchase ParamsBean adds a field of the image group, represented by an ArrayList.
public class PurchaseParamsBean {
. . .
public ArrayList purchaseFiles= null;//Enclosure
public ArrayList getPurchaseFiles() {
return purchaseFiles;
}
public void setPurchaseFiles(ArrayList purchaseFiles) {
this.purchaseFiles = purchaseFiles;
}
. . .
}
purchaseFiles are assigned in AysnTask.
purchaseParamsBean.setPurchaseFiles(getAllBase64Img());
public ArrayList<String> getAllBase64Img() {
ArrayList<String> arr = new ArrayList<>();
for (AlbumFile file : mAdapter.getDatas()) {
if (!TextUtils.isEmpty(file.getPath())) {
arr.add(getBase64String4Loader(file.getPath()));
}
}
if (arr.size() == 0) {
return null;
} else {
return arr;
// return new Gson().toJson(arr);
}
}
/**
* Create an array of images -- via Image Loader
*
* @return
*/
private String getBase64String4Loader(Object tag) {
Bitmap bitmap = null;
if (tag instanceof Uri) {// Take out the local uri
Uri uri = (Uri) tag;
Log.e(TAG, "uri:" + uri.toString());
bitmap = CompressUtil.getimage(BitmapUtils.getImageAbsolutePath(
OnlineBookingUI3.this, uri));
} else {
// Extract the absolute path (parse the file type from the path)
String path = (String) tag;
Log.e(TAG, "path:" + path);
bitmap = CompressUtil.getimage(path);
}
byte[] bytes = CompressUtil.compressImage(bitmap);
Log.e(TAG, bytes.length + "");
String base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
// recovery
bitmap.recycle();
Log.e(TAG, "getBase64String4Loader Recovered bitmap");
return base64;
}
Ultimately, the url is converted into a string, encoding base64, which is interesting to understand.
sendRequest Implementation
public <T> void sendRequest(String url, RequestParams param, final Class<T> clazz, String showText, boolean isdialogShow, View view, final BaseCallBack<T> baseCallBack) {
if (null == param) param = new RequestParams();
AsyncCallBackHandler res = new AsyncCallBackHandler(ui, showText, isdialogShow, view) {
@Override
public void mySuccess(int arg0, Header[] arg1, String arg2) {
String s = arg2;
if (arg2.startsWith("<?xml") || arg2.startsWith("<string")) {
s = parseXMLwithPull(arg2);
}
// Bean bean = GJson.parseObject(s, Bean.class);
T t = null;
try {
// t = new Gson().p(s, clazz);
t = new Gson().fromJson(s, clazz);
} catch (Exception e) {
e.printStackTrace();
baseCallBack.onFailure("json Analytical anomaly", new IllegalStateException("json Analytical anomaly"));
}
baseCallBack.onSuccess(t);
}
@Override
public void myFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
baseCallBack.onFailure(arg2, arg3);
}
@Override
public void onStart() {
super.onStart();
baseCallBack.onStart();
}
@Override
public void onFinish() {
super.onFinish();
baseCallBack.onFinish();
}
};
AsyncHttpUtil.post(url, context, param, res);
}
//Eventually, the onsUCCESS above will be called back.
AsyncHttpUtil.post(url, context, param, res);Implementation
/**
* post Has key,value form parameter, return a string data
*
* @param urlString
* @param params
* @param res
*/
public static void post(String urlString, Context context, RequestParams params, AsyncHttpResponseHandler res) // url with parameters
{
NetworkState state = new NetworkState(context);
if (state.isConnected() == false) {
Prompt.showWarning(context, "Please check your network");
return;
}
client.post(urlString, params, res);
}
This is mainly to pay attention to format, callback, image compression, these aspects