Jak wysłać obiekt z jednej aktywności Androida do drugiej za pomocą Intentów?

Jak mogę przekazać obiekt typu niestandardowego z jednej aktywności do drugiej przy użyciu metody putExtra() klasy Intent?

Author: UMAR, 2010-01-26

30 answers

Jeśli tylko przekazujesz obiekty, Parcelable został do tego zaprojektowany. Wymaga trochę więcej wysiłku w użyciu niż korzystanie z natywnej serializacji Javy, ale jest znacznie szybsza (I mam na myśli sposób, sposób szybciej).

Z docs, prosty przykład jak zaimplementować to:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

Zauważ, że jeśli masz więcej niż jedno pole do pobrania z danej paczki, musisz to zrobić w tej samej kolejności, w jakiej je umieściłeś (czyli w FIFO podejście).

Gdy już masz swoje obiekty zaimplementuj Parcelable to tylko kwestia umieszczenia ich w swoich intencjach z putExtra():

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Następnie możesz wyciągnąć je z powrotem za pomocą getParcelableExtra():

Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

Jeśli twoja klasa obiektu implementuje Parcelable i Serializable, upewnij się, że wykonasz cast do jednego z następujących:

i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
 692
Author: Jeremy Logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-14 16:13:19

Będziesz musiał serializować swój obiekt do pewnego rodzaju reprezentacji ciągu znaków. Jedną z możliwych reprezentacji łańcuchów jest JSON, a jednym z najprostszych sposobów serializacji do / Z JSON w Androidzie, jeśli pytasz mnie, jest Google Gson .

W takim przypadku należy umieścić łańcuch zwracany z {[0] } i pobrać łańcuch i użyć fromJson, aby przekształcić go z powrotem w obiekt.

Jeśli jednak Twój obiekt nie jest zbyt skomplikowany, może nie być wart kosztów i możesz rozważ przekazanie osobnych wartości obiektu.

 165
Author: David Hedlund,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-26 12:24:06

Możesz wysłać obiekt serializowalny przez intent

// send where details is object
ClassName details = new ClassName();
Intent i = new Intent(context, EditActivity.class);
i.putExtra("Editing", details);
startActivity(i);


//receive
ClassName model = (ClassName) getIntent().getSerializableExtra("Editing");

And 

Class ClassName implements Serializable {
} 
 142
Author: Sridhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-18 05:58:16

W sytuacjach, w których wiesz, że będziesz przekazywać dane w ramach aplikacji, użyj "globali" (takich jak Klasy statyczne)

Tutaj {[5] } jest to, co Dianne Hackborn (hackbod - inżynier oprogramowania Google Android) miała do powiedzenia w tej sprawie:

W sytuacjach, gdy wiesz, że działania są prowadzone w tym samym proces, możesz po prostu udostępniać dane za pośrednictwem globals. Na przykład, ty może mieć globalny HashMap<String, WeakReference<MyInterpreterState>> i kiedy stworzysz nową MyInterpreterState wymyślić z unikalna nazwa dla niego i umieścić go na mapie hash; aby wysłać ten stan do innego aktywności, wystarczy wpisać unikalną nazwę na mapie hash i gdy druga aktywność jest uruchomiona, może pobrać MyInterpreterState z Mapa hash z nazwą, którą otrzymuje.

 63
Author: Peter Ajtai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-03 13:48:57

Twoja klasa powinna zaimplementować Serializable lub Parcelable.

public class MY_CLASS implements Serializable

Po wykonaniu można wysłać obiekt na putExtra

intent.putExtra("KEY", MY_CLASS_instance);

startActivity(intent);

Aby dostać dodatki musisz tylko zrobić

Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");

Jeśli twoja klasa implementuje Parcelable użyj next

MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");

Mam nadzieję, że to pomoże: d

 46
Author: Pedro Romão,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-23 09:58:12

Jeśli klasa obiektu implementuje Serializable, nie musisz robić nic innego, możesz przekazać obiekt serializowalny. Tego właśnie używam.

 27
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-24 19:56:41

Krótka odpowiedź na szybką potrzebę

1. Zaimplementuj swoją klasę do Serializowalnego.

Jeśli masz jakieś wewnętrzne klasy, nie zapomnij zaimplementować ich również do Serializable!!

public class SportsData implements  Serializable
public class Sport implements  Serializable

List<Sport> clickedObj;

2. Umieść swój obiekt w intencji

 Intent intent = new Intent(SportsAct.this, SportSubAct.class);
            intent.putExtra("sport", clickedObj);
            startActivity(intent);

3. I odbierz swój obiekt w innej klasie aktywności

Intent intent = getIntent();
    Sport cust = (Sport) intent.getSerializableExtra("sport");
 26
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-04 09:43:00

Możesz użyć android BUNDLE, aby to zrobić.

Stwórz pakiet ze swojej klasy w stylu:

public Bundle toBundle() {
    Bundle b = new Bundle();
    b.putString("SomeKey", "SomeValue");

    return b;
}

Następnie przekaż ten pakiet z zamiarem. Teraz możesz odtworzyć swój obiekt klasowy, przekazując pakiet w postaci

public CustomClass(Context _context, Bundle b) {
    context = _context;
    classMember = b.getString("SomeKey");
}

Zadeklaruj to w swojej klasie niestandardowej i użyj.

 16
Author: om252345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-15 02:31:18

Dzięki za pomoc parcelable ale znalazłem jeszcze jedno opcjonalne rozwiązanie

 public class getsetclass implements Serializable {
        private int dt = 10;
    //pass any object, drwabale 
        public int getDt() {
            return dt;
        }

        public void setDt(int dt) {
            this.dt = dt;
        }
    }

W Ćwiczeniu Pierwszym

getsetclass d = new getsetclass ();
                d.setDt(50);
                LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
                obj.put("hashmapkey", d);
            Intent inew = new Intent(SgParceLableSampelActivity.this,
                    ActivityNext.class);
            Bundle b = new Bundle();
            b.putSerializable("bundleobj", obj);
            inew.putExtras(b);
            startActivity(inew);

Pobierz Dane W Ćwiczeniu 2

 try {  setContentView(R.layout.main);
            Bundle bn = new Bundle();
            bn = getIntent().getExtras();
            HashMap<String, Object> getobj = new HashMap<String, Object>();
            getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
            getsetclass  d = (getsetclass) getobj.get("hashmapkey");
        } catch (Exception e) {
            Log.e("Err", e.getMessage());
        }
 15
Author: user1140237,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-25 16:47:34

Zaimplementuj serializable w swojej klasie

        public class Place implements Serializable{
        private int id;
        private String name;

        public void setId(int id) {
           this.id = id;
        }
        public int getId() {
           return id;
        }
        public String getName() {
           return name;
        }

        public void setName(String name) {
           this.name = name;
        }
        }

Następnie możesz przekazać ten obiekt w intencji

     Intent intent = new Intent(this, SecondAct.class);
     intent.putExtra("PLACE", Place);
     startActivity();

Int drugie działanie możesz uzyskać dane w ten sposób

     Place place= (Place) getIntent().getSerializableExtra("PLACE");

Ale gdy dane staną się duże,ta metoda będzie powolna.

 15
Author: Ishan Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-22 06:18:49

Istnieje kilka sposobów dostępu do zmiennych lub obiektów w innych klasach lub aktywności.

A. Baza Danych

B. wspólne preferencje.

C. serializacja obiektów.

D. Klasa, która może przechowywać wspólne dane, może być nazwana jako wspólne narzędzia, zależy to od Ciebie.

E. Przekazywanie danych przez Intenty i interfejs Parcelowalny.

To zależy od potrzeb Twojego projektu.

A. Baza Danych

SQLite jest bazą danych Open Source który jest wbudowany w Androida. SQLite obsługuje standardowe funkcje relacyjnej bazy danych, takie jak składnia SQL, transakcje i przygotowane instrukcje.

Tutoriale -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Wspólne Preferencje

Załóżmy, że chcesz zapisać nazwę użytkownika. Więc teraz będą dwie rzeczy klucz Nazwa Użytkownika, wartość wartość.

Jak przechowywać

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

za pomocą putString (), putBoolean (), putInt (), putFloat (), putLong () możesz zapisać żądany dtatype.

Jak aportować

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

Http://developer.android.com/reference/android/content/SharedPreferences.html

C. Serializacja Obiektów

Object serlization jest używany, jeśli chcemy zapisać stan obiektu, aby wysłać go przez sieć lub możesz go również użyć do swojego celu.

Użyj java beans i przechowuj w nim jako jedną z jego dziedzin i używaj getters and setter for that

JavaBeans są klasami Javy, które mają właściwości. Pomyśl o właściwości jako zmienne instancji prywatnych. Ponieważ są prywatne, jedynym sposobem mogą być dostępne z zewnątrz ich klasy jest za pomocą metod w klasie. Na metody, które zmieniają wartość właściwości nazywane są metodami setter, a metody pobieranie wartości właściwości nazywa się metodami getter.

public class VariableStorage implements Serializable  {

    private String inString ;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }


}

Ustaw zmienną w metodzie mail używając

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Następnie użyj serializacja obiektu w celu serializacji tego obiektu i w innej klasie deserializacji tego obiektu.

W serializacji obiekt może być reprezentowany jako sekwencja bajtów, która zawiera dane obiektu, a także informacje o typie obiektu i typach danych przechowywanych w obiekcie.

Po zapisaniu serializowanego obiektu do pliku można go odczytać z pliku i deserializować, czyli informacje o typie i bajty, które reprezentują obiekt i jego dane mogą być służy do odtworzenia obiektu w pamięci.

Jeśli chcesz tutorial dla tego odwołania link

Http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Get variable in other classes

D. Commonty

Możesz zrobić klasę samodzielnie, która może zawierać wspólne dane, które często potrzebujesz w swoim projekcie.

Próbka

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E. Przekazywanie danych przez Intencje

Proszę zapoznać się z tym samouczkiem dla tej opcji przekazywania danych.

Http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

 14
Author: Nikhil Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:44

Używam Gson z jego tak potężnym i prostym api do wysyłania obiektów między działaniami,

przykład

// This is the object to be sent, can be any object
public class AndroidPacket {

    public String CustomerName;

   //constructor
   public AndroidPacket(String cName){
       CustomerName = cName;
   }   
   // other fields ....


    // You can add those functions as LiveTemplate !
    public String toJson() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    public static AndroidPacket fromJson(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, AndroidPacket.class);
    }
}

2 funkcje, które dodajesz do obiektów, które chcesz wysłać

użycie

Wyślij obiekt z A do B

    // Convert the object to string using Gson
    AndroidPacket androidPacket = new AndroidPacket("Ahmad");
    String objAsJson = androidPacket.toJson();

    Intent intent = new Intent(A.this, B.class);
    intent.putExtra("my_obj", objAsJson);
    startActivity(intent);

Otrzymać W B

@Override
protected void onCreate(Bundle savedInstanceState) {        
    Bundle bundle = getIntent().getExtras();
    String objAsJson = bundle.getString("my_obj");
    AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);

    // Here you can use your Object
    Log.d("Gson", androidPacket.CustomerName);
}

Używam go prawie w każdym projekcie i nie mam problemów z wydajnością.

 12
Author: MBH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-26 12:40:06

Zmagałem się z tym samym problemem. Rozwiązałem to używając klasy statycznej, przechowującej dowolne dane w Hashmapie. Na górze używam rozszerzenia standardowej klasy Activity, gdzie mam nadpisane metody onCreate an onDestroy zrobić transport danych i dane clearing Ukryte. Niektóre śmieszne ustawienia muszą zostać zmienione np. orientacja-obsługa.

Przypisy: Niepodanie ogólnych przedmiotów do przekazania innej czynności jest wrzodem na dupie. To jak strzelanie sobie w kolano. w biegu na 100 metrów. "Parcable" nie jest wystarczającym substytutem. To mnie rozśmiesza... Nie chcę implementować tego interfejsu do mojego wolnego od technologii API, ponieważ mniej chcę wprowadzić nową warstwę... Jak to możliwe, że jesteśmy w programowaniu mobilnym tak daleko od nowoczesnego paradygmatu...

 9
Author: oopexpert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-10 23:13:34

W twojej pierwszej aktywności:

intent.putExtra("myTag", yourObject);

A w drugim:

myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");

Nie zapomnij, aby Twój niestandardowy obiekt mógł zostać serializowany:

public class myCustomObject implements Serializable {
...
}
 9
Author: Rudi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-19 08:35:38

Innym sposobem na to jest użycie Application object (android.app.Aplikacji). Definiujesz to w pliku AndroidManifest.xml jako:

<application
    android:name=".MyApplication"
    ...

Możesz wywołać to z dowolnej aktywności i zapisać obiekt do klasy Application.

W pierwszej kolejności:

MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);

W drugiej części do:

MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);

Jest to przydatne, jeśli masz obiekty, które mają zakres z poziomu aplikacji, tzn. muszą być używane w całej aplikacji. Metoda Parcelable jest jeszcze lepsza, jeśli chcesz Jawna kontrola nad zakresem obiektu lub jeśli zakres jest ograniczony.

Pozwala to uniknąć użycia Intents w ogóle. Nie wiem, czy ci odpowiadają. Innym sposobem, w jaki to wykorzystałem, jest posiadanie int identyfikatorów obiektów wysyłanych przez intenty i pobieranie obiektów, które mam w Mapach w obiekcie Application.

 7
Author: Saad Farooq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-18 23:11:38

W swojej klasie model (obiekt) zaimplementuj Serializowalny, dla Przykład:

public class MensajesProveedor implements Serializable {

    private int idProveedor;


    public MensajesProveedor() {
    }

    public int getIdProveedor() {
        return idProveedor;
    }

    public void setIdProveedor(int idProveedor) {
        this.idProveedor = idProveedor;
    }


}

I twoja pierwsza aktywność

MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
                i.putExtra("mensajes",mp);
                startActivity(i);

I twoja druga aktywność (NewActivity)

        MensajesProveedor  mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
Powodzenia!!
 6
Author: David Hackro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-26 01:22:22
public class SharedBooking implements Parcelable{

    public int account_id;
    public Double betrag;
    public Double betrag_effected;
    public int taxType;
    public int tax;
    public String postingText;

    public SharedBooking() {
        account_id = 0;
        betrag = 0.0;
        betrag_effected = 0.0;
        taxType = 0;
        tax = 0;
        postingText = "";
    }

    public SharedBooking(Parcel in) {
        account_id = in.readInt();
        betrag = in.readDouble();
        betrag_effected = in.readDouble();
        taxType = in.readInt();
        tax = in.readInt();
        postingText = in.readString();
    }

    public int getAccount_id() {
        return account_id;
    }
    public void setAccount_id(int account_id) {
        this.account_id = account_id;
    }
    public Double getBetrag() {
        return betrag;
    }
    public void setBetrag(Double betrag) {
        this.betrag = betrag;
    }
    public Double getBetrag_effected() {
        return betrag_effected;
    }
    public void setBetrag_effected(Double betrag_effected) {
        this.betrag_effected = betrag_effected;
    }
    public int getTaxType() {
        return taxType;
    }
    public void setTaxType(int taxType) {
        this.taxType = taxType;
    }
    public int getTax() {
        return tax;
    }
    public void setTax(int tax) {
        this.tax = tax;
    }
    public String getPostingText() {
        return postingText;
    }
    public void setPostingText(String postingText) {
        this.postingText = postingText;
    }
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(account_id);
        dest.writeDouble(betrag);
        dest.writeDouble(betrag_effected);
        dest.writeInt(taxType);
        dest.writeInt(tax);
        dest.writeString(postingText);

    }

    public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
    {
        public SharedBooking createFromParcel(Parcel in)
        {
            return new SharedBooking(in);
        }
        public SharedBooking[] newArray(int size)
        {
            return new SharedBooking[size];
        }
    };

}

Przekazywanie danych:

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);

Pobieranie danych:

Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
 6
Author: Adnan Abdollah Zaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-08 21:38:55

Najprostszym rozwiązaniem, jakie znalazłem jest.. aby utworzyć klasę ze statycznymi składnikami danych z seterami getters.

Ustaw z jednej aktywności i pobierz z innej aktywności ten obiekt.

Aktywność A

mytestclass.staticfunctionSet("","",""..etc.);

Aktywność b

mytestclass obj= mytestclass.staticfunctionGet();
 5
Author: UMAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-04 12:07:22

Możesz użyć putExtra (Serializowalny..) i metody getSerializableExtra () do przekazywania i pobierania obiektów typu klasy; będziesz musiał zaznaczyć swoją klasę Serializable i upewnić się, że wszystkie Twoje zmienne członkowskie również są serializowalne...

 4
Author: null,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-06 16:00:09

Tworzenie Aplikacji Na Androida

Plik > > Nowy > > Aplikacja Na Androida

Wpisz nazwę projektu: android-pass-object-to-activity

Pakcage: com.hmkcode.android

Zachowaj inne opcje defualt, idź dalej, aż dojdziesz do końca

Przed rozpoczęciem tworzenia aplikacji musimy utworzyć klasę POJO "Person", której będziemy używać do wysyłania obiektów z jednej aktywności do drugiej. Zauważ, że klasa implementuje Serializable interfejs.

Osoba.java
package com.hmkcode.android;
import java.io.Serializable;

public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;

        // getters & setters....

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }   
}

Dwa Layouty dla dwóch działań

Activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/tvName"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_horizontal"
        android:text="Name" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:ems="10" >
        <requestFocus />
    </EditText>
</LinearLayout>

<LinearLayout
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
<TextView
    android:id="@+id/tvAge"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
    android:text="Age" />
<EditText
    android:id="@+id/etAge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10" />
</LinearLayout>

<Button
    android:id="@+id/btnPassObject"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Pass Object to Another Activity" />

</LinearLayout>

Activity_another.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
 >

<TextView
    android:id="@+id/tvPerson"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
 />

</LinearLayout>

Dwie Klasy Aktywności

1)ActivityMain.java

package com.hmkcode.android;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnPassObject = (Button) findViewById(R.id.btnPassObject);
    etName = (EditText) findViewById(R.id.etName);
    etAge = (EditText) findViewById(R.id.etAge);

    btnPassObject.setOnClickListener(this);
}

@Override
public void onClick(View view) {

    // 1. create an intent pass class name or intnet action name 
    Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");

    // 2. create person object
    Person person = new Person();
    person.setName(etName.getText().toString());
    person.setAge(Integer.parseInt(etAge.getText().toString()));

    // 3. put person in intent data
    intent.putExtra("person", person);

    // 4. start the activity
    startActivity(intent);
}

}
[[5]}2) inna aktywność.java
package com.hmkcode.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class AnotherActivity extends Activity {

TextView tvPerson;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_another);

    // 1. get passed intent 
    Intent intent = getIntent();

    // 2. get person object from intent
    Person person = (Person) intent.getSerializableExtra("person");

    // 3. get reference to person textView 
    tvPerson = (TextView) findViewById(R.id.tvPerson);

    // 4. display name & age on textView 
    tvPerson.setText(person.toString());

}
}
 3
Author: MFP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 05:53:41
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
 3
Author: Manas Ranjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 09:51:17

Wiem, że jest późno, ale to bardzo proste.Wszystko, co musisz zrobić, to pozwolić klasie zaimplementować Serializable jak

public class MyClass implements Serializable{

}

Następnie można przejść do intencji jak

Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);

Aby go dostać należy zadzwonić

MyClass objec=(MyClass)intent.getExtra("theString");
 3
Author: suulisin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-13 12:44:02

Używając biblioteki GSON google możesz przekazać obiekt do innej aktywności.W rzeczywistości przekonwertujemy obiekt w postaci ciągu json i po przejściu do innej aktywności ponownie przekonwertujemy obiekt w ten sposób

Rozważ taką klasę fasoli

 public class Example {
    private int id;
    private String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Musimy przekazać obiekt klasy przykładowej

Example exampleObject=new Example(1,"hello");
String jsonString = new Gson().toJson(exampleObject);
Intent nextIntent=new Intent(this,NextActivity.class);
nextIntent.putExtra("example",jsonString );
startActivity(nextIntent);

Do czytania musimy wykonać operację odwrotną w następnej

 Example defObject=new Example(-1,null);
    //default value to return when example is not available
    String defValue= new Gson().toJson(defObject);
    String jsonString=getIntent().getExtras().getString("example",defValue);
    //passed example object
    Example exampleObject=new Gson().fromJson(jsonString,Example .class);

Dodaj tę zależność w gradle

compile 'com.google.code.gson:gson:2.6.2'
 3
Author: Jinesh Francis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-07 04:57:11

Najprościej byłoby użyć następującego, gdzie element jest ciągiem znaków:

intent.putextra("selected_item",item)

Za otrzymanie:

String name = data.getStringExtra("selected_item");
 2
Author: ankish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-01 20:20:58

Jeśli masz klasę singleton (FX Service) działającą jako brama do warstwy modelu, można ją rozwiązać, mając zmienną w tej klasie z getterami i setterami dla niej.

W Ćwiczeniu 1:

Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);

W Ćwiczeniu 2:

private Service service;
private Order order;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quality);

    service = Service.getInstance();
    order = service.getSavedOrder();
    service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}

W Służbie:

private static Service instance;

private Service()
{
    //Constructor content
}

public static Service getInstance()
{
    if(instance == null)
    {
        instance = new Service();
    }
    return instance;
}
private Order savedOrder;

public Order getSavedOrder()
{
    return savedOrder;
}

public void setSavedOrder(Order order)
{
    this.savedOrder = order;
}

To rozwiązanie nie wymaga żadnej serializacji ani innego "opakowania" danego obiektu. Ale będzie to korzystne tylko wtedy, gdy używasz tego rodzaju architektury i tak.

 2
Author: Kitalda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-24 07:42:04

Zdecydowanie najprostszy sposób IMHO do paczkowania obiektów. Wystarczy dodać znacznik adnotacji nad obiektem, który chcesz parcelować.

Przykład z biblioteki znajduje się poniżej https://github.com/johncarl81/parceler

@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
 2
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-07 21:42:09

Najpierw zaimplementuj Parcelable w swojej klasie. Następnie podaj obiekt w ten sposób.

/ align = "left" / java

ObjectA obj = new ObjectA();

// Set values etc.

Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);

startActivity(i);

/ align = "left" / java

Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");

Łańcuch pakietów nie jest konieczny, tylko łańcuch musi być taki sam w obu działaniach

Bibliografia

 2
Author: Arpit Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-08 07:30:06

Uruchom inną aktywność z tej aktywności przekazując parametry za pomocą obiektu Bundle

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Pobierz na innej aktywności (your activity)

String s = getIntent().getStringExtra("USER_NAME");

To jest ok dla typu danych typu simple kind. Ale jeśli chcesz przekazać złożone dane pomiędzy aktywnością, najpierw musisz je serializować.

Tutaj mamy Model pracownika

class Employee{
    private String empId;
    private int age;
    print Double salary;

    getters...
    setters...
}

Możesz użyć Gson lib dostarczonego przez google do serializacji złożonych danych like this

String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);

Bundle bundle = getIntent().getExtras();
    String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            }.getType();
            Employee selectedEmp = gson.fromJson(empStr, type);
 2
Author: user1101821,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-12 21:00:09

Jeśli nie jesteś zbytnio zainteresowany używaniem funkcji putExtra i chcesz po prostu uruchomić kolejną aktywność z obiektami, możesz sprawdzić GNLauncher ( https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher ) biblioteka, którą napisałem, próbując uprościć ten proces.

GNLauncher sprawia, że wysyłanie obiektów / danych do aktywności z innej aktywności itp. jest tak proste, jak wywołanie funkcji w aktywności z wymaganymi danymi jako parametrami. Wprowadza wpisz Bezpieczeństwo i usuwa wszystkie problemy związane z serializacją, dołączanie do intencji za pomocą kluczy łańcuchowych i cofanie tego samego na drugim końcu.

 1
Author: jinais,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-02 15:29:19

Klasa POJO " Post "(zauważ, że jest zaimplementowana Serializowalna)

package com.example.booklib;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;

public class Post implements Serializable{
    public String message;
    public String bitmap;
    List<Comment> commentList = new ArrayList<Comment>();
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getBitmap() {
        return bitmap;
    }
    public void setBitmap(String bitmap) {
        this.bitmap = bitmap;
    }
    public List<Comment> getCommentList() {
        return commentList;
    }
    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

}

Klasa POJO "komentarz" (ponieważ jest członkiem klasy Post, konieczne jest również zaimplementowanie Serializable)

    package com.example.booklib;

    import java.io.Serializable;

    public class Comment implements Serializable{
        public String message;
        public String fromName;
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        public String getFromName() {
            return fromName;
        }
        public void setFromName(String fromName) {
            this.fromName = fromName;
        }

    }

Następnie w klasie activity możesz wykonać następujące czynności, aby przekazać obiekt do innej aktywności.

ListView listview = (ListView) findViewById(R.id.post_list);
listview.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Post item = (Post)parent.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this,CommentsActivity.class);
            intent.putExtra("post",item);
            startActivity(intent);

        }
    });

W klasie odbiorcy "CommentsActivity" możesz uzyskać dane w następujący sposób

Post post =(Post)getIntent().getSerializableExtra("post");
 0
Author: zawhtut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-21 07:24:18