问题描述
所有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 是空的.第二个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
类中实现 Serializable
或 Parcelable
并像这样传递数据:
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");
这篇关于如何从第二个活动的第一个活动中获取数组列表的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!