简体   繁体   中英

Android App- Passing object as intent extra vs using public member variable

I have an android app that has a ListView as its main activity. When one of the items is clicked, a new activity is launched, showing a detail view. The ListView has an ArrayList of objects of a class that I defined.

Currently I pass in these objects to the detail view activity like so:

Intent intent=new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra(TAG,myList.get(position));
startActivity(intent);

where 'myList' is a private member variable of MainActivity. However, the detail view takes some time to load, and I am wondering if that is because the objects in 'myList' contain a Bitmap, which may take some time to read. The lag might just be due to the emulator running slowly, I am not sure.

I figured it would be faster to make myList public, and then pass in the position like so:

Intent intent=new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra(TAG,position);
startActivity(intent);

and then access the object in DetailActivity like this:

MyObject object=MainActivity.myList.get(getIntent().getIntExtra(TAG));

However, I believe I have read that there is a chance that my MainActivity may be destroyed when DetailActivity starts, and then wouldn't MainActivity.myList be null?

Try to launch your application on a real mobile phone. I had the same problem with the emulator and I think that it was only its fault, because on a real device my code ran really quickly and there was no lag. The extras on the intent are not such a load that the application gets slow.

I figured it would be faster to make myList public

it is not just public but also static . Don't do that. It could lead to severe memory leak. Keep providing the object in the Intent , as you are already doing. If you believe that bitmap could cause some lag, provide just the path to it and have an AsyncTask to load it asynchronously

Creating a public fields in Activity is not recomendable. Check activity lifecycle.

But, I would ask you:

¿Do you need pass the Bitmap in the intent? ¿Can you not obtain it in the second activity, with the position of first?

If you answer is yes. Maybe you can load it in a asynchronous way, with a Handler or a AsyncTask .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM