How to pass several variables of different types from one function to another on android?

我是研究僧i 提交于 2019-12-11 15:27:41

问题


I have getFilmsBrowse function and it should return the following field:

  • name (String)
  • description (String)
  • year (Int)
  • etc.

Results of this function to be used in another function displayMovies. How can I pass them and be able to use names of fields in displayMovies? Wanted to use Map for the same, but it is not clear for me how to initialize that.


回答1:


You can use Bundle class for this. It's like a Map, but it can contain values of different types.




回答2:


You could use a collection, but why not create a class called Film, with private member variables called name, description, year etc, and then accessor methods like getYear(). Then you can do this:

Film film = getFilmsBrowse(...);
int year = film.getYear();



回答3:


Create some model classes which will hold data:

public class Page implements Serializable {
    private String name;
    private String description;
    //and so on...
    public Page(String name, String description) {
        this.name = name;
        this.description = description;
    }
    public String getName() {
        return name;
    }
    public String getDescription() {
        return description;
    }
}

Now you can create a Page object and fill it with data(name, description) via the constructor. Optionally make some setters.

Page p = new Page("James", "Hello World");
startActivity(new Intent(context, MyActivity.class).putExtra("Page", p));

Retrieve your Page in MyActivity in its onCreate method:

Page p = (Page)getIntent().getExtras().getSerializable("Page");
Toast.makeText(this, "Name: " + p.getName() + ", Description:" + p.getDescription(), Toast.LENGTH_LONG).show();



回答4:


If you're moving from Activity to Activity you will use Intents and Bundle to pass parameters. If you're calling a function and reutrning to your original activity, then you will use conventional java



来源:https://stackoverflow.com/questions/5437433/how-to-pass-several-variables-of-different-types-from-one-function-to-another-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!