Beginner Android Four months not to me, may not be a beginner. Learning while groping, slowly can find the correct code on Baidu, this should be I learned so long to get the progress.
Today it took a day to achieve the ability to upload avatars and change avatars. Most of the code is copy over, probably can read, know how to use, only this!
OK, a busy day, do a self-summary ~
Here first summarizes the implementation of the upload Avatar feature:
Ideas:
Create an activity that simply associates a layout with ImageView and buttons. When clicking on the ImageView, pop up a dialog, the dialog can call the system's photos, albums, so that you can choose to upload the picture, and then call the system cropping, the picture is cropped to show the picture in the ImageView; When you click the button, The upload function is performed.
(Well, it is necessary to note that the xutils is used here to handle HTTP requests for uploading.) So need to xutils rack package, because to request the network and access to the phone SD card, so do not forget to add the corresponding permissions. Yes, it also implements the ability to save the cropped picture in the phone's SD card. )
Code section:
First, the client
①oncreate part
Private ImageView img;
Private Button btnupload;
Private Httputils httputils;
Private String url= "http://10.50.8.33:8080/Person_proj/servlet/UploadServlet";//server path
Private string[] items = {"Take photos", "albums"};
Private String title = "Select Photo";
private static final int photo_carmera = 1;
private static final int photo_pick = 2;
private static final int photo_cut = 3;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
img = (ImageView) Findviewbyid (r.id.main_img);
Btnupload = (Button) Findviewbyid (r.id.upload);//button to upload a picture
Btnupload.setonclicklistener (Clicklistener);
Img.setonclicklistener (Clicklistener);
Httputils=new Httputils (10000);//Create and Instantiate Httputils class
}
② Click event Monitoring
Private Onclicklistener Clicklistener = new Onclicklistener () {
@Override
public void OnClick (View v) {
Switch (V.getid ()) {
Case R.id.main_img://imageview Monitoring
Alertdialog.builder dialog = Androidutil.getlistdialogbuilder (//The static method of Androidutil is called here, so you need to write another class (add to the back)
Mainactivity.this, items, title, dialoglistener);//Popup dialog, where items, title can be customized, here to define it as a global variable;
Dialoglistener is the monitoring of the dialog (the way to listen for photos: photos, albums)
Dialog.show ();
Break
Case r.id.upload://upload image button monitor
Upload ();//Call upload Method
Break
Default
Break
}
}
};
③ Upload Method (uploaded to the server)
protected void upload () {
Requestparams params=new requestparams ();
Params.addbodyparameter (Tempfile.getpath (). Replace ("/", ""), tempfile);//This tempfile is created with the current system time as the name, preventing duplicates
Prevent duplication of purpose: enable each user to get their own uploaded avatar
System.out.println (Tempfile);
Httputils.send (Httpmethod.post,url, Params,new requestcallback<string> () {
@Override
public void OnFailure (HttpException E, String msg) {
Toast.maketext (Mainactivity.this, "Upload failed, check the server address is correct", Toast.length_short). Show ();
LOG.I ("Mainactivity", E.getexceptioncode () + "====="
+ msg);
}
@Override
public void onsuccess (responseinfo<string> responseinfo) {
Toast.maketext (Mainactivity.this, "upload success, go to the server to see now!" ", Toast.length_short). Show ();
LOG.I ("Mainactivity", "====upload_error====="
+ Responseinfo.result);
}
});
}
④tempfile Creation (This method I put in front of the OnCreate method, put in the back should also have no relationship)
Create a file with the current system time name to prevent duplication
Private file Tempfile = new file (Environment.getexternalstoragedirectory (),
Getphotofilename ());
Use the system's current date to adjust the name of the photo
Private String Getphotofilename () {
Date date = new Date (System.currenttimemillis ());
SimpleDateFormat SDF = new SimpleDateFormat ("' PNG ' _yyyymmdd_hhmmss");
Picname=sdf.format (date) + ". png";
return Sdf.format (date) + ". png";
}
⑤dialog Listening (there are several methods called here)
Private Android.content.DialogInterface.OnClickListener Dialoglistener = new Dialoginterface.onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
The variable value of switch (which) {//case, defined as a global variable
Case 0://Array The subscript value of the items, here is of course the photo
Call to take pictures
Startcamera (Dialog);
Break
Case 1:
Call album
Startpick (Dialog);
Break
Default
Break
}
}
};
Calling the system camera
protected void Startcamera (Dialoginterface dialog) {
Dialog.dismiss ();
Recall the camera function of the system
Intent Intent = new Intent (mediastore.action_image_capture);
Intent.putextra ("Camerasensortype", 2); Call the front-facing camera
Intent.putextra ("Autofocus", true); Auto Focus
Intent.putextra ("fullscreen", false); Fullscreen
Intent.putextra ("Showactionicons", false);
Specifies the storage path of the photo after the camera is called
Intent.putextra (Mediastore.extra_output, Uri.fromfile (tempfile));
Startactivityforresult (Intent, Photo_carmera);
}
Call System Albums
protected void Startpick (Dialoginterface dialog) {
Dialog.dismiss ();
Intent Intent = new Intent (Intent.action_pick, NULL);
Intent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
Startactivityforresult (Intent, Photo_pick);
}
Override return Result Code method: Select the image and then return to the interface, corresponding to display the selected picture
@Override
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Switch (Requestcode) {//The case variable value here, defined as a global variable
Case photo_carmera://Photo Mode
Startphotozoom (Uri.fromfile (tempfile), 300);//Call clipping method
Break
Case photo_pick://Album method
if (null! = data) {
Startphotozoom (Data.getdata (), 300);//Call clipping method
}
Break
Case photo_cut://Picture Clipping success
if (null! = data) {
Setpictoview (data);//Display the picture on the ImageView
}
Break
Default
Break
}
Super.onactivityresult (Requestcode, ResultCode, data);
}
Call system cropping
private void Startphotozoom (URI uri, int size) {
Intent Intent = new Intent ("Com.android.camera.action.CROP");
Intent.setdataandtype (URI, "image/*");
Crop true is set to set the displayed view in the open intent to crop
Intent.putextra ("Crop", true);
Aspectx,aspecty is the ratio of width to height
Intent.putextra ("Aspectx", 1);
Intent.putextra ("Aspecty", 1);
Outputx,outputy is the width height of the cropped picture
Intent.putextra ("Outputx", size);
Intent.putextra ("Outputy", size);
Sets whether to return data
Intent.putextra ("Return-data", true);
Startactivityforresult (Intent, photo_cut);
}
Display the cropped picture on the ImageView
private void Setpictoview (Intent data) {
Bundle bundle = Data.getextras ();
if (null! = bundle) {
Final Bitmap bmp = bundle.getparcelable ("Data");
Img.setimagebitmap (BMP);
Savecroppic (BMP);//Call Saved in SDcard method (can also not be saved, or saved locally on the phone)
LOG.I ("Mainactivity", Tempfile.getabsolutepath ());
}
}
Save the cropped picture to the SDcard
private void Savecroppic (Bitmap bmp) {
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
FileOutputStream FIS = null;
Bmp.compress (Bitmap.CompressFormat.PNG, BAOs);
try {
FIS = new FileOutputStream (tempfile);
Fis.write (Baos.tobytearray ());
Fis.flush ();
} catch (Exception e) {
E.printstacktrace ();
} finally {
try {
if (null! = BAOs) {
Baos.close ();
}
if (null! = FIS) {
Fis.close ();
}
} catch (IOException e) {
E.printstacktrace ();
}
}
}
Androidutil class
public class Androidutil {
Returns a list dialog box
public static Alertdialog.builder Getlistdialogbuilder (context context,
string[] items, String title, Onclicklistener clicklistener) {
return new Alertdialog.builder (context). Settitle (title). Setitems (items, clicklistener);
}
}
Second, server-side (Uploadservlet)
public class Androiduploadservlet extends HttpServlet {
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Request.setcharacterencoding ("Utf-8");
Response.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Smartupload smartupload = new Smartupload ();
String msg=request.getparameter ("msg");
Out.print (msg);
try {
Smartupload.initialize (This.getservletconfig (), request, response);
Smartupload.upload ();
Com.jspsmart.upload.File smartfile = Smartupload.getfiles (). GetFile (0);
if (!smartfile.ismissing ()) {
String savefilename = "images/" + smartfile.getfilename (); The picture is saved under the Images folder in the Webroot directory
Smartfile.saveas (Savefilename, smartupload.save_virtual);
System.out.println ("OK:" + savefilename+ ", msg:" + smartupload.getrequest (). GetParameter ("MSG"));
} else {
Out.print ("Missing ...");
}
} catch (Exception e) {
System.out.println (e+ "," +msg);
}
Out.flush ();
Out.close ();
}
}
My first blog in life, to this end ~ Yes Yes ~ ~ Another day to summarize from the server to get pictures displayed on the client.
Phone Select image upload to Server