iterating a global list from any activity

泪湿孤枕 提交于 2021-02-11 18:15:53

问题


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

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