问题
i have a list of object in an activity in which a button in the same activity adds an object to it on every click i want to be capable to access that list and iterate it from any other activity i made it public but it gave me an error !
package com.fawzyx.movie_rental_store;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MovieReg_activity extends Activity {
public List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
movies.add(new movie(movName , dvdNo) );
Toast.makeText(MovieReg_activity.this, "Movie Added", Toast.LENGTH_LONG).show();
}
});
}
}
is there a way to access and iterate the list movies from any other activity ?
回答1:
You can use a static way to access to this list :
public static List<movie> movies = new ArrayList<movie>();
Then from the other activity :
int size = MovieReg_activity.movies.size(); // exp: check the size
for(movie m : MovieReg_activity.movies){
// do something with m
}
回答2:
if you want to make a global list, create a static variable or put it in your application class and access it via context.
Search about creating a custom application class.
回答3:
Maybe use a singleton class that holds your movie list.
Then you'll be able to access it everywhere.
http://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/
来源:https://stackoverflow.com/questions/21724447/iterating-a-global-list-from-any-activity