如何从第二个活动的第一个活动中获取arraylist的内容 [英] How to get contents of arraylist from first activity in second activity

查看:120
本文介绍了如何从第二个活动的第一个活动中获取arraylist的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有Task.java

All Task.java

public class AllTask extends AppCompatActivity{


    ArrayList<Company> companyList;
    Bundle extras;

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


        companyList=new ArrayList<>();
        companyList.add(new Company("Kony Labs","10:30","Good"));
        companyList.add(new Company("Delloite","12:30","Very Good"));
        companyList.add(new Company("Accenture","14:30","Average"));
        companyList.add(new Company("Microsoft","16:30","Very Good"));
        companyList.add(new Company("TCS","18:30","Good"));


    }
}

AllReports.java

AllReports.java

public class AllReports extends AppCompatActivity {

    ArrayList<Company> report_companyList;
    Bundle extras;

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


        getSupportActionBar().setTitle("Reports");

        AllTask all_tasks=new AllTask();
        report_companyList=new ArrayList<>(all_tasks.companyList);



        ListView listView = (ListView) findViewById(R.id.report_list);

        MyAdapterResults myAdapter=new MyAdapterResults(this,R.layout.list_view_row_item,report_companyList);
        listView.setAdapter(myAdapter);
    }
}

我想在第二个活动的ListView中的第一个活动中显示ArrayList中的数据,但是当我尝试在第二个活动中从第一个活动中获取数据时,则给出NullPointerException ArrayList为空.如何在第二个活动中获取ArrayList的内容.

I want to show data in ArrayList in first activity in ListView from the second activity but when I am trying to get data from first activity in second it is giving NullPointerException that ArrayList is empty. How to get the contents of ArrayList in the second activity.

推荐答案

您可以将companyList设置为静态

static ArrayList<Company> companyList;

并这样称呼它:

AllTask.companyList

不推荐这种方法.相反,您应该在Company类中实现SerializableParcelable并像这样传递数据:

This approach is not recommended. You should instead implement Serializable or Parcelable in your Company class and pass the data like this:

Bundle bundle = new Bundle();
bundle.putSerializable("data", companyList);
intent.putExtras(bundle);

并从这样的第二个活动中读取它:

and read it from second activity like this:

Bundle bundle = getIntent.getExtras();
List<Company> data= (List<Company>)bundle.getSerializable("data");

这篇关于如何从第二个活动的第一个活动中获取arraylist的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆