繁体   English   中英

如何将 object 传递给 android 工作室中的新活动?

[英]How to pass an object to a new activity in android studio?

我正在尝试将 object 从一项活动传递到另一项活动。 我尝试过仅使用意图以及如何使用捆绑包,但我不确定出了什么问题。 我在这里查看了类似的解决方案,这就是我获得大部分代码的地方,但似乎我的复制和粘贴不起作用。

这是我的主要 class

    public class MainActivity extends AppCompatActivity {
    Item item;

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

        Button buttonOne = findViewById(R.id.itemButton);
        buttonOne.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), ViewItemDetails.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

    }

    void createNewItem(){
        item=new Item("Pixel 4","https://google.com",1000.00);
    }
}

这是我试图 go 的活动:

    public class ViewItemDetails extends AppCompatActivity {

    Intent intent= getIntent();
    Bundle bundle= intent.getExtras();
    Item item = (Item) bundle.getSerializable("item");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_item_details);
        setStrings();
        setButtons();
    }
    void setStrings() {
        try {
            TextView nameTextView = findViewById(R.id.itemNameid);
            nameTextView.setText(item.getItemName());

            TextView itemInitTV = findViewById(R.id.initalPriceNumID);
            itemInitTV.setText(Double.toString(item.getInitPrice()));

            TextView itemCurrTV = findViewById(R.id.currentPriceNumid);
            itemCurrTV.setText(Double.toString(item.getCurrentPrice()));
        }catch (NullPointerException e){
            //do noting
        }
    }

    void setButtons(){
        Button buyButton = findViewById(R.id.buyButtonid);
        buyButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Uri uriUrl = Uri.parse(item.getWebaddress());
                Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
                startActivity(launchBrowser);
            }
        });

        Button refreshButton= findViewById(R.id.refrechId);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Double newPrice= new GenerateNewPrice().GenerateNewPrice(item.getWebaddress());
                Toast toast = Toast.makeText(getApplicationContext(),Double.toString(newPrice), Toast.LENGTH_SHORT);
                toast.show();
            }
        });

        Button editButton= findViewById(R.id.editid);
        editButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Toast toast = Toast.makeText(getApplicationContext(),"Attempt to edit", Toast.LENGTH_SHORT);
                toast.show();
            }
        });

    }
}

这是我试图在活动之间传递的 object。

    public class Item implements Serializable {
    String itemName, webaddress;
    Double initPrice, CurrentPrice;

    public Item(String itemName, String webaddress, Double initPrice) {
        this.itemName = itemName;
        this.webaddress = webaddress;
        this.initPrice = initPrice;
    }

    public String getItemName() {
        return itemName;
    }

    public String getWebaddress() {
        return webaddress;
    }

    public Double getInitPrice() {
        return initPrice;
    }

    public Double getCurrentPrice() {
        return CurrentPrice;
    }
 }

当我在手机上运行应用程序时,我单击按钮,然后应用程序关闭。

谢谢您的帮助。 如果需要,我可以添加更多代码。 我在这里看到了类似的问题,但它们对我没有用。 我从这些帖子中得到了类似的代码,但还没有解决我的解决方案。 我感谢任何反馈。 感谢您的时间。

对于现在和将来对 SOF 的帮助,请记住,错误日志在这种情况下总是有帮助的。

不过,这里有几点..

  • 您应该遵循 Activity 生命周期规则,在onCreate()中获取数据将是一个好主意。
  • 您应该使用 Parcelable 而不是 Serializable。 它效率更高。

您在 ViewItemDetails.java 活动中对 bundle 和 item 的初始化是错误的。 尝试在 onCreate 方法中初始化并告诉我们..

好像你有一些错误,它应该可以工作,你可以查看一个项目工作示例 //creating the budle

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //String selectedItem = (String) adapterView.getItemAtPosition(i);
            //getting dat from text view and converting to string
           // String textview =((TextView)view.findViewById(R.id.textViewName)).getText().toString();
            //Toast.makeText(DriverInfo.this,"Driver id "+driver_id,Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("DriverID",driver_id);
            bundle.putString("Route",loc_src);
            bundle.putString("Dest",loc_dest);
            bundle.putString("location_address",location_address);
            Toast.makeText(DriverInfo.this, "Driver ID="+driver_id, Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(DriverInfo.this, DirverCurrentLoc.class);
            intent.putExtras(bundle);
            startActivity(intent);

        }
    });

//获取包数据

 String lat, lng, realtime,src,dest;
     location_address=intent.getStringExtra("location_address");
        driver_id=intent.getStringExtra("DriverID");
        src=intent.getStringExtra("Route");
        dest=intent.getStringExtra("Dest");

您必须在 onCreate() 方法中初始化此代码,如下所示:

Item item;

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

Intent intent= getIntent();
Bundle bundle= intent.getExtras();
item = (Item) bundle.getSerializable("item");

setStrings();
setButtons();

}

您可以使用 GSON 将您的 Object 转换为 JSON 格式

Intent intent = new Intent(this, ProjectActivity.class);
intent.putExtra("item", new Gson().toJson(item));
startActivity(intent);

然后在您的第二个活动中,确保您在 onCreate() 生命周期中正确初始化捆绑包。

Item item;

@Override
protected void onCreate(Bundle savedInstanceState) {
    .........
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        item = new Gson().fromJson(extras.getString("item"), Item.class);
    }

注意:我在一篇文章中读到这一点,谷歌在传递捆绑对象时推荐 GSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM