问题
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
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);
}
}
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.
回答1:
You can make your companyList
static
static ArrayList<Company> companyList;
and call it like this :
AllTask.companyList
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");
回答2:
First, make your Company object as Serializable
public class Company implements Serializable {
//Your code
}
From AllTask Activity you should open AllReports like this,
Intent intent = new Intent(this, AllReports.class);
intent.putExtra("companyList", companyList);
startActivity(intent);
You can get in AllReports, like this,
ArrayList<Company> companyList = (ArrayList<Company>)getIntent().getSerializableExtra("companyList");
回答3:
You should send it through intent.
first of all make your Company bean implements Serializable
then in your firstActivity do this :
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("array",companyList);
startActivity(intent);
And then in your SecondActitvity in your onCreate do it like this:
ArrayList<Company> companyList = (ArrayList<Company>) getIntent().getSerializableExtra("array");
回答4:
You can pass Parcelable array to your activity. It is more efficient than Serializable, for Android at least. But your company should implement Parcelable for that.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, SecondActivity.class);
ArrayList<Company> companies = new ArrayList<>();
//fill companies
i.putParcelableArrayListExtra("EXTRA", companies);
startActivity(i);
}
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Company> companies = getIntent().getParcelableArrayListExtra("EXTRA");
}
}
回答5:
A good way to do this using Application class it allows you to use the same object using in various Activity, Fragment or Dialog.
Only one object creates and it may use in multiple times Access from anywhere of the Application I am adding a sample code which I have used:
public class Application extends Application {
ArrayList<Filepath> arrayFilePath;
@Override
public void onCreate() {
super.onCreate();
this.sharedPreferences = getSharedPreferences(Constant.Userdata.USER_PREF.name(), Context.MODE_PRIVATE);
}
public ArrayList<Filepath> getArrayListForImagePath() {
String fileurl = sharedPreferences.getString(Constant.Userdata.ARRAYLISTFILEPATH.name(), "");
Gson gson = new Gson();
if (fileurl.isEmpty()) {
arrayFilePath = new ArrayList<Filepath>();
} else {
Type type = new TypeToken<ArrayList<Filepath>>() {
}.getType();
arrayFilePath = gson.fromJson(fileurl, type);
}
return arrayFilePath;
}
public void setArrayListForImagePath(ArrayList<Filepath> imagePath) {
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String jsonFilepath = gson.toJson(imagePath);
editor.putString(Constant.Userdata.ARRAYLISTFILEPATH.name(), jsonFilepath);
editor.commit();
}
public void clearArrayListForImagePath() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(Constant.Userdata.ARRAYLISTFILEPATH.name()).commit();
}
Constant Class:
public class Constant {
enum Userdata {
USER_PREF, USER_ID, ARRAYLISTFILEPATH
}
}
回答6:
I'm going to answer with a non-native solution.
You could also use Green Robot's EventBus to achieve what you want, without having to work with Serializable
or the boilerplate of Parcelable
. With the advantage of being much faster than both when you're dealing with large datasets, or many Activity calls. It also have the advantage of not having to write too much boilerplate code if your pojo/bean/class have many fields.
First, add the dependency on your build.gradle
.
compile 'org.greenrobot:eventbus:3.0.0'
Then, define an Event class that will be responsible to carry your data through the app. Note that this could be from one Activity
to another. From a Fragment
to another. A Service
back to an Activity
, and so on.
MessageEvent.java
public class MessageEvent {
public ArrayList<Company> mCompanyList;
// Add additional fields here if needed
public MessageEvent(ArrayList<Company> list) {
this.mCompanyList = list;
}
}
Now, you can either define a subscriber, or just post an stickyEvent
and get it on ActivityB
. Like the two examples below.
Option 1: Defining subscriber
ActivityB.java
public class ActivityB extends AppCompatActivity {
// ...
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
EventBus.getDefault().removeStickyEvent(event);
ArrayList<Company> list = event.mCompanyList;
// Do whatever you want to do with the data.
};
}
ActivityA.java
public class ActivityA extends AppCompatActivity {
// ...
private void startActB(ArrayList<Company> list) {
Intent it = new Intent(ActivityA.this, ActivityB.class);
EventBus.getDefault().postSticky(new MessageEvent(list));
startActivity(it);
}
}
Option 2: Getting sticky event on ActivityB
without subscribing
ActivityA.java
Just do like the sample above and post the MessageEvent
and start ActivityB
.
ActivityB.java
public class ActivityB extends AppCompatActivity {
private ArrayList<Company> mCompanyList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
// Other stuff you might want to do here.
// Get the event that was posted on Activity A.
MessageEvent event = EventBus.getDefault().removeStickyEvent(MessageEvent.class);
// Check if it exists.
if (event != null) {
mCompanyList = event.mCompanyList;
// Do whatever you want with it.
}
else {
// Do something if the event wasn't posted prior to this Activity call.
}
}
// ...
}
You can refer to this link to check how fast the EventBus can run compared with Serializable
and Parcelable
.
For more details, you can check the project page, or this tutorial.
来源:https://stackoverflow.com/questions/45548223/how-to-get-contents-of-arraylist-from-first-activity-in-second-activity