![](/img/trans.png)
[英]How to pass Class of Class in ArrayList from one Activity to Another Activity
[英]How do I pass ArrayList<Object> from one Activity to another Activity
我想將 Object 的 ArrayList 從一個活動傳遞到另一個活動。
這是示例代碼:
{
ArrayList<object> list=new ArrayList<>();
Object value[]=new Object[m.size()];
int n=0;
value[]=new Object[n];
value[n]=data.getName("name");
value[n]=data.getLocation("location");
list.add(value[n]);
n++; //Since there are "n" number of object
}
//here the value a which is ArrayList Object
// which I want to pass it from here to another activity.
那么現在我將如何將 object 從這里傳遞給另一個活動。 但是,我可以使用Gson獲得值。 通過將值轉換為json並將其作為字符串傳遞給SharedPreference並從另一個活動中檢索,然后使用類型從Json轉換回來以支持其原始形式。
我想知道是否可以使用Parceable傳遞值。 因為我在使用它時得到了 null 值。
這是我試圖使我的 Object 變量 Parceable 的代碼:
public class ProductList implements Parcelable {
private String NAME;
private String LOCATION;
public ProductList() {
}
protected ProductList(Parcel in) {
LOCATION= in.readString();
NAME= in.readString();
}
public static final Creator<ProductList> CREATOR = new Creator<ProductList>() {
@Override
public ProductList createFromParcel(Parcel in) {
return new ProductList(in);
}
@Override
public ProductList[] newArray(int size) {
return new ProductList[size];
}
};
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME= NAME;
}
public String getLOCATION() {
return LOCATION;
}
public void setITEM_IMAGE(String LOCATION) {
this.LOCATION= LOCATION;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(NAME);
dest.writeString(LOCATION);
}
}
您可以使用活動結果
鏈接https://developer.android.com/training/basics/intents/result
代碼示例
活動主體代碼
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
在其他活動中
可以使用 json 格式來傳遞數據
Gson gson = new Gson(); 字符串 json = gson.toJson(myObj);
Intent intent=new Intent();
intent.putExtra("MESSAGE",json);
setResult(2,intent);
finish();//finishing activity
如果您不想使用活動結果,可以使用 singleton class
class MyClass{
companion object {
val staticField = "This is an example of static field Object Decleration"
fun getStaticFunction(): String {
return "This is example of static function for Object Decleration"
}
}
}
請參閱此鏈接以了解。
活動一:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
ArrayList<object> list=new ArrayList<>();
intent.putExtra("LIST", list);
startActivity(intent);
活動二:
ArrayList<object> list = (ArrayList<object>)getIntent().getSerializableExtra("LIST");
還要在您的自定義 class 中實現 Serializable。
public class ProductList implements Parcelable, Serializable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.