passing object to activity

前端 未结 3 1426
暗喜
暗喜 2021-01-16 20:39

Can i initialize object in my first activity and you it in all activity???

public class Calc{
    int x;
    int y;
    public Calc(int x, int y) {
       th         


        
相关标签:
3条回答
  • 2021-01-16 21:07

    make

    public class Calc implements Serializable {
    int x;
    int y;
    public Calc(int x, int y) {
       this.x = x;
       this.y = y;
    }
    public int sum() {
        return x + y;
    }
    

    }

    and

    When you start your PreviewActivity

    Intent intent = new Intent(mContext, PreviewActivity .class);
    intent.putParcelableArrayListExtra("data",c);
    startActivity(intent);
    

    and in your PreviewActivity do this

    Calc c=(Calc ) getIntent().getSerializableExtra("data");
    
    0 讨论(0)
  • 2021-01-16 21:07

    How can i pass it to another activity or how can i make it share with other activity

    Just use Intent so:

    intent.putExtra("calc" new Calc(3, 4));
    

    for passing this Object when you want to start another Activity.

    Then in your second Activity just call:

    Calc c = getIntent().getParcelableExtra("calc"); // getSerializableExtra("calc");
    

    And your Calc class have to implement Parcelable or Serializable

    public class Calc implements Parcelable { 
     ...
    }
    
    0 讨论(0)
  • 2021-01-16 21:13

    Use Application class by extending it and writing your custom Application class, and keep your objects in this class that you need in your cross Activities

    class MyApplication extends Application{
        Object a;
    
        public void setA(Object a){
             this.a = a;
        }
    
        public Object getA(){
             return a;
        }
    
    }
    

    Now lets suppose in your A activity you create object of class Object and want to use it in your B Activity.

    do it this way,

    class ActivityA extends Activity(){
    
    ...
    // some where in activity, set your object this way.
         Object aObj = new Object();
         ((MyApplication)getApplication()).setA(aObj);
    
    
    ...
    
    }
    
    class ActivityB extends Activity(){
    
    ...
    // some where in activity, get your object this way.
         Object aObj = ((MyApplication)getApplication()).getA( );
    
    
    ...
    
    }
    

    You need to tell your androidManifest.xml about your extended Application class.

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