How to send objects through bundle

前端 未结 11 1165
我寻月下人不归
我寻月下人不归 2020-11-27 13:15

I need to pass a reference to the class that does the majority of my processing through a bundle.

The problem is it has nothing to do with intents or contexts and ha

相关标签:
11条回答
  • 2020-11-27 13:34

    Possible solution:

    Bundle bundle = new Bundle();
    bundle.putSerializable("key", new CustomObject());
    

    Class CustomObject:

    class CustomObject implements Serializable{
     private SubCustomObject1 sc1;
     private SubCustomObject2 sc2;
    }
    

    Subcustom objects:

    class SubCustomObject1 implements Serializable{ }
    
    class SubCustomObject2  implements Serializable{ }
    
    0 讨论(0)
  • 2020-11-27 13:36

    This is a very belated answer to my own question, but it keep getting attention, so I feel I must address it. Most of these answers are correct and handle the job perfectly. However, it depends on the needs of the application. This answer will be used to describe two solutions to this problem.

    Application

    The first is the Application, as it has been the most spoken about answer here. The application is a good object to place entities that need a reference to a Context. A `ServerSocket` undoubtedly would need a context (for file I/o or simple `ListAdapter` updates). I, personally, prefer this route. I like application's, they are useful for context retrieving (because they can be made static and not likely cause a memory leak) and have a simple lifecycle.

    Service

    The Service` is second. A `Service`is actually the better choice for my problem becuase that is what services are designed to do:
    A Service is an application component that can perform long-running operations in
    the background and does not provide a user interface.
    
    Services are neat in that they have a more defined lifecycle that is easier to control. Further, if needed, services can run externally of the application (ie. on boot). This can be necessary for some apps or just a neat feature.

    This wasn't a full description of either, but I left links to the docs for those who want to investigate more. Overall the Service is the better for the instance I needed - running a ServerSocket to my SPP device.

    0 讨论(0)
  • 2020-11-27 13:36

    I came across this question when I was looking for a way to pass a Date object. In my case, as was suggested among the answers, I used Bundle.putSerializable() but that wouldn't work for a complex thing as the described DataManager in the original post.

    My suggestion that will give a very similar result to putting said DataManager in the Application or make it a Singleton is to use Dependency Injection and bind the DataManager to a Singleton scope and inject the DataManager wherever it is needed. Not only do you get the benefit of increased testability but you'll also get cleaner code without all of the boiler plate "passing dependencies around between classes and activities" code. (Robo)Guice is very easy to work with and the new Dagger framework looks promising as well.

    0 讨论(0)
  • 2020-11-27 13:38

    1.A very direct and easy to use example, make object to be passed implement Serializable.

    class Object implements Serializable{
        String firstName;
       String lastName;
    }
    

    2.pass object in bundle

    Bundle bundle = new Bundle();
    Object Object = new Object();
    bundle.putSerializable("object", object);
    

    3.get passed object from bundle as Serializable then cast to Object.

    Object object = (Object) getArguments().getSerializable("object");
    
    0 讨论(0)
  • 2020-11-27 13:39

    One More way to send objects through bundle is by using bundle.putByteArray
    Sample code

    public class DataBean implements Serializable {
    private Date currentTime;
    
    public setDate() {
        currentTime = Calendar.getInstance().getTime();
     }
    
    public Date getCurrentTime() {
        return currentTime;
     }
    }
    

    put Object of DataBean in to Bundle:

    class FirstClass{
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Your code...
    
    //When you want to start new Activity...
    Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
                Bundle dataBundle=new Bundle();
                DataBean dataObj=new DataBean();
                dataObj.setDate();
                try {
                    dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));
    
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
    
                }
    
                dataIntent.putExtras(dataBundle);
    
                startActivity(dataIntent);
    }
    

    Converting objects to byte arrays

    /**
     * Converting objects to byte arrays
     */
    static public byte[] object2Bytes( Object o ) throws IOException {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream( baos );
          oos.writeObject( o );
          return baos.toByteArray();
        }
    

    Get Object back from Bundle:

    class SecondClass{
    DataBean dataBean;
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Your code...
    
    //Get Info from Bundle...
        Bundle infoBundle=getIntent().getExtras();
        try {
            dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    Method to get objects from byte arrays:

    /**
     * Converting byte arrays to objects
     */
    static public Object bytes2Object( byte raw[] )
            throws IOException, ClassNotFoundException {
          ByteArrayInputStream bais = new ByteArrayInputStream( raw );
          ObjectInputStream ois = new ObjectInputStream( bais );
          Object o = ois.readObject();
          return o;
        }
    

    Hope this will help to other buddies.

    0 讨论(0)
提交回复
热议问题