Android delivers bitmap objects between two activity _android

Source: Internet
Author: User
Tags serialization

Through internal storage, the bitmap objects are passed between two activity and other Java objects that support serialization, and the key points are as follows:

1. HTTP client downloads picture, displayed by ImageView object

2. The bitmap object on the ImageView is passed from the current activity to another activity and displayed

3. Passing Java object data based on serialization

First see how I implemented HTTP client download picture, through the asynchronous task interface to implement HTTP client download picture and through handler to update ImageView, the code is as follows:

Package Com.example.sharedemo; 
Import java.io.IOException; 
 
Import Java.io.InputStream; 
Import org.apache.http.HttpEntity; 
Import Org.apache.http.HttpResponse; 
Import Org.apache.http.HttpStatus; 
Import org.apache.http.client.ClientProtocolException; 
Import org.apache.http.client.HttpClient; 
Import Org.apache.http.client.methods.HttpGet; 
 
Import org.apache.http.impl.client.DefaultHttpClient; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.os.AsyncTask; 
Import Android.os.Handler; 
Import Android.os.Message; 
 
Import Android.util.Log; 
 
  public class Imageloadtask extends Asynctask<string, Void, bitmap> {private Handler Handler; 
  Public Imageloadtask (Handler Handler) {this.handler = Handler; 
    } protected void OnPostExecute (Bitmap Bitmap) {msg = new message (); 
    Msg.obj = bitmap; 
  Handler.sendmessage (msg); } @Override protected Bitmap doinbackground (String ... urls) {BitmaP bitmap = null; 
    Create HTTP client HttpClient httpclient = new Defaulthttpclient (); 
      try {//Get request LOG.I ("Image-url", Urls[0]); 
      HttpGet HttpRequest = new HttpGet (urls[0]); 
      HttpResponse HttpResponse = Httpclient.execute (HttpRequest); if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get entity from response Http 
        Entity httpentity = httpresponse.getentity (); 
        Read stream InputStream is = httpentity.getcontent (); 
        Bitmap = Bitmapfactory.decodestream (IS); 
        Is.close (); 
      LOG.I ("image", "already get the image by URL:" + urls[0]); 
    } catch (Clientprotocolexception e) {e.printstacktrace (); 
    catch (IOException e) {e.printstacktrace (); 
    finally {Httpclient.getconnectionmanager (). Shutdown (); 
  return bitmap; 
 } 
 
}

The

Toggles the view into the corresponding activity through the event response implementation on the button in the current session, while implementing Java serialization data transfer. The code for Mainactivity is as follows:

Package Com.example.sharedemo; 
Import Java.io.ByteArrayOutputStream; 
 
Import Java.io.FileOutputStream; 
Import android.app.Activity; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.graphics.Bitmap; 
Import Android.graphics.Matrix; 
Import android.graphics.drawable.BitmapDrawable; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.os.Message; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
 
Import Android.widget.ImageView; public class Mainactivity extends activity implements onclicklistener{public final static String Share_bitmap_command 
  = "Share-image"; 
  Public final static String Share_text_data_command = "Share-text-data"; 
 
  Private Handler Handler; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_main); 
  Setuponclicklistener (); }
 
  private void Setuponclicklistener () {button bitmapbtn = (button) This.findviewbyid (R.ID.BITMAPSHAREBTN); 
    Bitmapbtn.settag (Share_bitmap_command); 
    Bitmapbtn.setonclicklistener (this); 
    Button textdatabtn = (button) This.findviewbyid (R.ID.MAPSHAREBTN); 
    Textdatabtn.settag (Share_text_data_command); 
    Textdatabtn.setonclicklistener (this); 
     
    Final ImageView ImageView = (imageview) This.findviewbyid (R.ID.IMAGEVIEW1); 
        Handler = new Handler () {public void Handlemessage (msg) {Bitmap Bitmap = (Bitmap) msg.obj; if (bitmap!= null) {///*//To prevent the original picture from being too large to cause memory overflow, reduce the original display first, and then release the memory occupied by the raw bitmap B 
          Itmap Smallbitmap = Zoombitmap (Bitmap, Bitmap.getwidth ()/5, Bitmap.getheight ()/5); 
          Releasing resources bitmap.recycle (); 
          Display Picture Imageview.setimagebitmap (SMALLBITMAP); 
          Imageview.invalidate (); 
  * * IMAGEVIEW.SETIMAGEBITMAP (bitmap);      } 
      } 
    }; 
    Imageloadtask task = new Imageloadtask (handler); 
  Task.execute ("http://img.blog.csdn.net/20150607143208238"); 
    public static Bitmap Zoombitmap (Bitmap Bitmap, int width, int height) {int w = bitmap.getwidth (); 
    int h = bitmap.getheight (); 
    Matrix matrix = new Matrix (); 
    float ScaleWidth = ((float) width/w); 
    float ScaleHeight = ((float) height/h); Matrix.postscale (ScaleWidth, ScaleHeight); 
    Do not change the original image size Bitmap newbmp = Bitmap.createbitmap (Bitmap, 0, 0, W, h, Matrix, true); 
  return newbmp; 
    @Override public void OnClick (View v) {Object tag = V.gettag (); 
    LOG.I ("command", Tag.tostring ()); if (share_bitmap_command.equals (tag)) {Intent Intent = new Intent (This.getapplicationcontext (), Imageprocessac 
      Tivity.class); 
      ImageView ImageView = (imageview) This.findviewbyid (R.ID.IMAGEVIEW1); 
    Bitmap Bitmap = ((bitmapdrawable) imageview.getdrawable ()). Getbitmap ();  Intent.putextra ("SelectedImage", bitmap); 
      Intent.putextra ("name", "Lena"); 
      Intent.putextra ("description", "Super Big Beauty");      
    This.startactivity (Intent);  else if (share_text_data_command.equals (tag)) {Intent Intent = new Intent (This.getapplicationcontext (), 
      Imageprocessactivity.class); 
      ImageView ImageView = (imageview) This.findviewbyid (R.ID.IMAGEVIEW1); 
      Bitmap Bitmap = ((bitmapdrawable) imageview.getdrawable ()). Getbitmap (); 
      Save it then pass URI imageinfobean dto = new Imageinfobean (); 
      String uri = Createimagefrombitmap (bitmap); 
      Dto.setdescription ("Super Big Beauty"); 
      Dto.setname ("Lena"); 
       
      Dto.seturi (URI); 
      Intent.putextra ("Tiger", DTO);  
    This.startactivity (Intent); 
    } public String Createimagefrombitmap (Bitmap Bitmap) {string fileName = ' myimage '; 
      try {bytearrayoutputstream bytes = new Bytearrayoutputstream (); Bitmap.compress (BITMAp.CompressFormat.JPEG, bytes); 
      FileOutputStream fo = openfileoutput (FileName, context.mode_private); 
      Fo.write (Bytes.tobytearray ()); 
    Fo.close (); 
      catch (Exception e) {e.printstacktrace (); 
    FileName = null; 
    } log.i ("filename", filename); 
  return fileName; 
 } 
}

The code to read and assemble the bitmap object in a different activity is as follows:

Package Com.example.sharedemo; 
 
Import java.io.FileNotFoundException; 
Import android.app.Activity; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.os.Bundle; 
Import Android.widget.ImageView; 
 
Import Android.widget.TextView; public class Imageprocessactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) 
    {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.share_info); 
  Backfilldata (); 
    private void Backfilldata () {Object obj = this.getintent (). Getextras (). Get ("Tiger"); 
    ImageView ImageView = (imageview) This.findviewbyid (R.ID.IMAGEVIEW1); 
    TextView Text1 = (TextView) This.findviewbyid (R.ID.TEXTVIEW1); 
    TextView Text2 = (TextView) This.findviewbyid (R.ID.TEXTVIEW2); try {if (obj!= null && obj instanceof imageinfobean) {Imageinfobean dto = (Imageinfobean) 
        Obj Bitmap Bitmap = Bitmapfactory.decodestream (This. Openfileinput (Dto.geturi ()); 
        Imageview.setimagebitmap (bitmap); Imageview.invalidate (); 
        Refresh Text1.settext ("Name:" + dto.getname ()); 
        Text2.settext ("description:" + dto.getdescription ()); 
      Return 
    } catch (FileNotFoundException e) {e.printstacktrace (); 
    } Bitmap Bitmap = (Bitmap) this.getintent (). Getparcelableextra ("SelectedImage"); 
    String name = This.getintent (). Getextras (). getString ("name"); 
    String description = This.getintent (). Getextras (). GetString ("description"); 
      if (bitmap!= null) {Imageview.setimagebitmap (bitmap); Imageview.invalidate (); 
    The refresh} if (name!= null) {Text1.settext ("name:" + name); 
    } if (description!= null) {Text2.settext ("description:" + description); 
 } 
  } 
 
}

The corresponding Java serialization object class code is as follows:

Package Com.example.sharedemo; 
 
Import java.io.Serializable; 
 
public class Imageinfobean implements Serializable { 
  /** 
   * */ 
  private static final long Serialversionuid = 1L; 
 
  Public String GetName () {return 
    name; 
  } 
 
  public void SetName (String name) { 
    this.name = name; 
  } 
 
  Public String GetDescription () {return 
    description; 
  } 
 
  public void SetDescription (String description) { 
    this.description = description; 
  } 
 
  Public String GetURI () {return 
    uri; 
  } 
 
  public void Seturi (String uri) { 
    This.uri = uri; 
  } 
 
  private String name; 
  Private String description; 
  Private String URI; 
 
 

Final statement:
Don't forget to add Network access permissions on manifest files

 
 

The first button "pass Picture" will show me that I encountered the error, the second button "Pass text data"
The correct processing results will be demonstrated as follows:

The above is the entire content of this article, I hope to help you learn.

Related Article

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.