How to pass several variables of different types from one function to another on android?
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 s开发者_运维百科ame, but it is not clear for me how to initialize that.
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();
You can use Bundle
class for this. It's like a Map
, but it can contain values of different types.
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();
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
精彩评论