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

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

问题描述

所有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 中的数据,但是当我试图从第二个活动中的第一个活动获取数据时,它给出了 NullPointerExceptionArrayList 是空的.第二个activity中如何获取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 设为静态

You can make your companyList static

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");

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

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