Android Bulk upload pictures

Source: Internet
Author: User
Tags response code

Additional netutil and server-side uploadpicture are required

Package com.example.girdviewtest;

Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import android.app.Activity;
Import Android.app.ActionBar;
Import Android.app.AlertDialog;
Import Android.app.AlertDialog.Builder;
Import android.app.Fragment;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.content.pm.ActivityInfo;
Import Android.database.Cursor;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.text.TextUtils;
Import Android.view.LayoutInflater;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.view.WindowManager;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;
Import Android.widget.Button;
Import Android.widget.GridView;
Import Android.widget.ImageView;
Import Android.widget.SimpleAdapter;
Import Android.widget.SimpleAdapter.ViewBinder;
Import Android.widget.Toast;
Import Android.os.Build;
Import Android.provider.MediaStore;

Import Java.io.DataOutputStream;
Import Java.io.File;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Map;

Import org.json.JSONException;
Import Org.json.JSONObject;

Import Sun.geoffery.uploadpic.NetUtil;
Import android.app.Activity;
Import Android.app.ProgressDialog;
Import android.content.ContentValues;
Import Android.content.Context;
Import android.content.Intent;
Import Android.database.Cursor;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.net.Uri;
Import Android.os.Build;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.provider.MediaStore;
Import Android.provider.MediaStore.MediaColumns;
Import Android.text.TextUtils;
Import android.view.Gravity;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.view.Window;
Import Android.widget.Button;
Import Android.widget.ImageView;
Import Android.widget.TextView;
Import Android.widget.Toast;

public class Mainactivity extends Activity {

Private GridView gridView1;//grid display thumbnail
private button buttonpublish;//Publish button
Private final int image_open = 1;//Open Picture tag
Private String pathimage;//Select picture path
Private Bitmap bmp;//import temporary picture
Private arraylist Private Simpleadapter Simpleadapter;//adapter

Private String imgurl = "Http://59.78.93.208:9095/UpLoadPicture ";
Private Context Mcontext;
Private String ResultStr = "";
list<string> List = new arraylist<string> ();


@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
/*
* Prevents the keyboard from blocking the input box
* Do not want occlusion set activity property android:windowsoftinputmode= "Adjustpan"
* Want to dynamically adjust height android:windowsoftinputmode= "Adjustresize"
*/
GetWindow (). Setsoftinputmode (Windowmanager.layoutparams.
Soft_input_adjust_pan);
Lock screen
Setrequestedorientation (activityinfo.screen_orientation_portrait);
Setcontentview (R.layout.activity_main);
Get Control Object
GridView1 = (GridView) Findviewbyid (R.ID.GRIDVIEW1);
Buttonpublish= (Button) Findviewbyid (R.id.button1);
Buttonpublish.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (View v) {
New Thread (uploadimagerunnable). Start ();
}
});

/*
* Load default picture add picture Plus
* Through adapter implementation
* Simpleadapter parameter Imageitem for data source r.layout.griditem_addpic to layout
*/
BMP = Bitmapfactory.decoderesource (Getresources (), r.drawable.gridview_addpic); Plus
Imageitem = new arraylisthashmap<string, object> map = new hashmap<string, object> ();
Map.put ("Itemimage", BMP);
Imageitem.add (map);
Simpleadapter = new Simpleadapter (This,
Imageitem, R.layout.griditem_addpic,
New string[] {"Itemimage"}, new int[] {r.id.imageview1});
/*
* HashMap loaded BMP images are not displayed in the GridView, but if the load resource ID can be displayed as
* Map.put ("Itemimage", r.drawable.img);
* Workaround:
* 1. Custom Inheritance Baseadapter implementation
* 2.ViewBinder () interface implementation
* Reference http://blog.csdn.net/admin_/article/details/7257901
*/
Simpleadapter.setviewbinder (New Viewbinder () {
@Override
public Boolean setviewvalue (view view, Object data,
String textrepresentation) {
TODO auto-generated Method Stub
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView i = (ImageView) view;
I.setimagebitmap ((Bitmap) data);
return true;
}
return false;
}
});
Gridview1.setadapter (Simpleadapter);

/*
* Monitor GridView Click events
* ERROR: The function must be abstract method, it is necessary to manually import Android.view.View;
*/
Gridview1.setonitemclicklistener (New Onitemclicklistener () {
@Override
public void Onitemclick (adapterview<?> parent, View v, int position, long ID)
{
if (imageitem.size () = = 10) {//First picture is default
Toast.maketext (Mainactivity.this, "the number of pictures is 9 full", Toast.length_short). Show ();
}
else if (position = = 0) {//Click the picture position for + 0 for 0 pictures
Toast.maketext (Mainactivity.this, "Add Picture", Toast.length_short). Show ();
Select picture
Intent Intent = new Intent (Intent.action_pick,
Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Startactivityforresult (Intent, Image_open);
Refresh data with Onresume ()
}
else {
dialog (position);
Toast.maketext (Mainactivity.this, "click on" + (position + 1) + "picture",
Toast.length_short). Show ();
}

}
});
}

Get Picture Path response Startactivityforresult
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Super.onactivityresult (Requestcode, ResultCode, data);
Open picture
if (RESULTCODE==RESULT_OK && requestcode==image_open) {
Uri uri = Data.getdata ();
if (! Textutils.isempty (Uri.getauthority ())) {
Query Select Picture
cursor cursor = getcontentresolver (). Query (
Uri
New string[] {MediaStore.Images.Media.DATA},
Null
Null
NULL);
Return not found select picture
if (null = = cursor) {
Return
}
Move the cursor to the beginning to get the picture path
Cursor.movetofirst ();
Pathimage = cursor.getstring (cursor
. Getcolumnindex (MediaStore.Images.Media.DATA));
}
}//end if Open picture
}

Refresh Picture
@Override
protected void Onresume () {
Super.onresume ();
if (! Textutils.isempty (Pathimage)) {
Bitmap Addbmp=bitmapfactory.decodefile (pathimage);
hashmap<string, object> map = new hashmap<string, object> ();
Map.put ("Itemimage", addbmp);
Imageitem.add (map);
Simpleadapter = new Simpleadapter (This,
Imageitem, R.layout.griditem_addpic,
New string[] {"Itemimage"}, new int[] {r.id.imageview1});
Simpleadapter.setviewbinder (New Viewbinder () {
@Override
public Boolean setviewvalue (view view, Object data,
String textrepresentation) {
TODO auto-generated Method Stub
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView i = (ImageView) view;
I.setimagebitmap ((Bitmap) data);
return true;
}
return false;
}
});
Gridview1.setadapter (Simpleadapter);
Simpleadapter.notifydatasetchanged ();
Release after refresh prevents the phone from automatically adding after hibernation
List.add (Pathimage);
Pathimage = null;
}
}

/*
* Dialog dialog box prompts the user to delete the action
* Position to delete picture location
*/
protected void dialog (final int position) {
Alertdialog.builder builder = new Builder (mainactivity.this);
Builder.setmessage ("Are you sure you want to remove the added picture?" ");
Builder.settitle ("hint");
Builder.setpositivebutton ("Confirm", new Dialoginterface.onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
Dialog.dismiss ();
Imageitem.remove (position);
Simpleadapter.notifydatasetchanged ();
}
});
Builder.setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
Dialog.dismiss ();
}
});
Builder.create (). Show ();
}


Runnable uploadimagerunnable = new Runnable () {
@Override
public void Run () {
for (int i = 0; I <list.size (); i++) {
if (Textutils.isempty (Imgurl)) {
Toast.maketext (Mcontext, "The path to the upload server has not been set! ", Toast.length_short). Show ();
Return
}

map<string, string> textparams = new hashmap<string, string> ();
map<string, file> fileparams = new hashmap<string, file> ();

try {
Create a URL object
Imgurl= "http://59.78.93.208:9095/UpLoadPicture?num=" +i;
URL url = new URL (imgurl);
Textparams = new hashmap<string, string> ();
Fileparams = new hashmap<string, file> ();
The picture file to upload
Pathimage=list.get (i);
File File = new file (pathimage);
Fileparams.put ("image", file);
Fetching Web page data from the network using HttpURLConnection objects
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Set the connection timeout (remember to set the connection timeout, and if the network is not good, the Android system will retract the resource interrupt operation over the default time)
Conn.setconnecttimeout (5000);
Set allow output (send POST request must set allow output)
Conn.setdooutput (TRUE);
Set to send using post
Conn.setrequestmethod ("POST");
Set not to use cache (problem prone)
Conn.setusecaches (FALSE);
Starting with the Setrequestproperty () setting of the HttpURLConnection object is to generate the HTML file header
Conn.setrequestproperty ("Ser-agent", "Fiddler");
Set ContentType
Conn.setrequestproperty ("Content-type", "multipart/form-data; boundary= "+ netutil.boundary);
OutputStream OS = Conn.getoutputstream ();
DataOutputStream ds = new DataOutputStream (OS);
Netutil.writestringparams (Textparams, DS);
Netutil.writefileparams (Fileparams, DS);
Netutil.paramsend (DS);
When you are done with the file stream, remember to close it promptly
Os.close ();
Is the response returned by the server?
int code = Conn.getresponsecode (); Get a webpage from the Internet, send a request, read the page back in a stream
To determine the response code
if (code = = 200) {//Return response code 200, is successful
Get the input stream returned by the network
InputStream is = Conn.getinputstream ();
ResultStr = Netutil.readstring (IS);
} else {
Toast.maketext (mcontext, "Request URL failed! ", Toast.length_short). Show ();
}

} catch (Exception e) {
E.printstacktrace ();
}
Toast.maketext (Mcontext, "Send Success", Toast.length_short). Show ();
Handler.sendemptymessage (0);//execute time-consuming method after sending to handler
}
}
};

Handler Handler = new Handler (new Handler.callback () {

@Override
public boolean handlemessage (Message msg) {
Switch (msg.what) {
Case 0:
Pd.dismiss ();

try {
Jsonobject jsonobject = new Jsonobject (RESULTSTR);
The service ends with the string "1" as the Operation success Token
if (jsonobject.optstring ("status"). Equals ("1")) {

Used to splice the distribution of the picture path used to say
The network URL path to the picture that is extracted from the Jsonobject object returned by the server
String IMAGEURL = jsonobject.optstring ("ImageUrl");
Get the picture path in the cache
Toast.maketext (Mcontext, IMAGEURL, Toast.length_short). Show ();
} else {
Toast.maketext (Mcontext, jsonobject.optstring ("StatusMessage"), Toast.length_short). Show ();
}

} catch (Jsonexception e) {
E.printstacktrace ();
}
Break
Default
Break
}
return false;
}
});

}

Android Bulk upload pictures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.