I'm trying to pass an array of custom objects to an activity. I've implemented parcelable as such:
public class WidgetState {
static class Light implements Parcelable
{
int id;
String text;
int offColor,onColor;
boolean on=false;
boolean isRows;
int size;
public static final Parcelable.Creator<Light> CREATOR = new Parcelable.Creator<Light>() {
public Light createFromParcel(Parcel in) {
return new Light(in);
}
public Light[] newArray(int size) {
return new Light[size];
}
};
#Override
public int describeContents() {
return 0;
}
public Light(Parcel src)
{
id = src.readInt();
text = src.readString();
offColor = src.readInt();
onColor = src.readInt();
on = src.readInt()==1;
isRows = src.readInt()==1;
size = src.readInt();
}
public Light() { }
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(text);
dest.writeInt(offColor);
dest.writeInt(onColor);
dest.writeInt(on?1:0);
dest.writeInt(isRows?1:0);
dest.writeInt(size);
}
}
}
I can put a single object in the bundle in the launching activity and retrieve it via
bundle.putParcelable(new WidgetState.Light(),"light");
and retrieve it in the resulting activity via
WidgetState.Light light = (WidgetState.Light)getIntent().getExtras().getParcelable("light")
but when packing and array like this
bundle.putParcelableArray(new WidgetState.Light[4],"lights");
I can do this just fine on the first activity
WidgetState.Light[] lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
but in the second activity i get a RuntimeException when I call
WidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
Here's all the code in the first activity
Intent intent = new Intent(MainActivity.this,GuiActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("light", new WidgetState.Light());
bundle.putParcelableArray("lights", new WidgetState.Light[4]);
WidgetState.Light[]lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
And the second
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gui);
Bundle state = (savedInstanceState!=null)?savedInstanceState:getIntent().getExtras();
try {
WidgetState.Light light = (WidgetState.Light) state.getParcelable("light");
// Throws RuntimeException on next line
WidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
Toast.makeText(this, "Good bundle", Toast.LENGTH_SHORT).show();
}
catch ( RuntimeException e)
{
Toast.makeText(this, "Failed to read bundle", Toast.LENGTH_SHORT).show();
}
}
What am I missing?
Related
I am trying to send my object Product from Activity B to Activity A, when the app close without any error message:
Activity A:
public class MainActivity extends AppCompatActivity {
Intent addManualProduct;
TextView name;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.tv_name);
img = (ImageView) findViewById(R.id.iv_product);
addManualProduct = new Intent(this, Main2Activity.class);
setTitle("ACTIVITY A");
Button openB = (Button) findViewById(R.id.bt_OpenActB);
openB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addManualProduct, 2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK){
Product p = data.getParcelableExtra("product_new");
name.setText(p.getName());
img.setImageBitmap(p.getImg());
}
}
}
Activity B:
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("ACTIVITY B");
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Product product = new Product("arroz", img);
Intent toA = new Intent();
toA.putExtra("product_new", product);
setResult(RESULT_OK, toA);
finish();
}
}
Product object:
public class Product implements Parcelable{
String name;
Bitmap img;
public Product() {}
public Product(String name, Bitmap img){
this.name = name;
this.img = img;
}
protected Product(Parcel in) {
name = in.readString();
img = in.readParcelable(Bitmap.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeParcelable(img, flags);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Product> CREATOR = new Creator<Product>() {
#Override
public Product createFromParcel(Parcel in) {
return new Product(in);
}
#Override
public Product[] newArray(int size) {
return new Product[size];
}
};
public String getName() {
return name;
}
public Bitmap getImg() {
return img;
}
}
If I only make parcelable the String name its works ok but when I try to put the Bitmap it close all application.
I can say the error its because the Bitmap, but I don't know why.
Parcelling large data can cause issues in your application. Instead of parcelling the Bitmap, I suggest parcelling the resource instead.
public class Product implements Parcelable {
String name;
int bitmapResource;
public Product(String name, int resource){
this.name = name;
this.bitmapResource = resource;
}
}
Then you can use your Product like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("ACTIVITY B");
Product product = new Product("arroz", R.drawable.no_image);
Intent toA = new Intent();
toA.putExtra("product_new", product);
setResult(RESULT_OK, toA);
finish();
}
If you need to load Bitmaps in a more dynamic fashion, you can store the Uri to your Bitmap so that it can be loaded from raw resources, assets, or from a service.
Bitmap which you are passing might too big.
So try to compress bitmap.
Try below example :-
http://www.android-examples.com/compress-bitmap-image-in-android-and-reduce-image-size/
My application makes a webservice call using volley, in order to update recyclerView every 10 seconds. Besides memory usage increase in 10 seconds constantly until it hits the max heap size. Then GC starts doing its job, but the memory usage does not come back down like at the beginning.
Using Eclipse MAT or Android Studio analyzer tasks, I could'nt find a single leak in my code.
I want to know that if there are suspects of leaking in my code. Any help will be appreciated.
Below I have 3 classes:
EventService send a message to MainActivity using sendBroadcast() in every 10 seconds.
MainActiviy will get message from EventService using BroadcastReceiver and calls update operation within its Fragment
EventListFragment, which is inside the MainActivity, contains a RecyclerView, that needs to be updated.
Here is my EventService:
public class EventService extends Service {
private volatile boolean isCanceled = false;
public static final String KEY_MESSAGE = "connection";
public EventService() {}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
while (!isCanceled) {
try {
Intent i = new Intent("android.intent.action.MAIN");
AppController.getInstance().cancelPendingRequests("json_obj_req");
i.putExtra(KEY_MESSAGE, MESSAGE);
sendBroadcast(i);
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread eventThread = new Thread(r);
eventThread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
isCanceled = true;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
private Intent intent;
private BroadcastReceiver mReceiver;
private EventListFragment eventListFragment;
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setView() {
eventListFragment = (EventListFragment) getSupportFragmentManager().findFragmentById(R.id.frgEventList);
}
#Override
protected void onResume() {
intent = new Intent(this, EventService.class);
mReceiver = new MyReceiver(eventListFragment);
this.registerReceiver(mReceiver, intentFilter);
intent = new Intent(this, EventService.class);
startService(intent);
}
#Override
protected void onPause() {
super.onPause();
stopService(intent);
unregisterReceiver(mReceiver);
}
private static class MyReceiver extends BroadcastReceiver {
private WeakReference<EventListFragment> eventListFragment = null;
public MyReceiver(EventListFragment eventFragment) {
this.eventListFragment = new WeakReference<>(eventFragment);
}
#Override
public void onReceive(Context context, Intent intent) {
String mssg = intent.getStringExtra(KEY_MESSAGE);
EventListFragment eventFragment = eventListFragment.get();
if (mssg.equals(MESSAGE) && eventFragment != null) {
//Update recyclerView
eventFragment.eventToList();
}
}
}
}
And here is my EventListFragment:
public class EventListFragment extends Fragment {
private View view;
private RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
private EventAdapter eventAdapter;
private RequestData requestData;
private ArrayList<EventModel> eventList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_event_list, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
setView();
setControl();
}
private void setView() {
recyclerView = (RecyclerView) view.findViewById(R.id.frg_recycler_view);
}
private void setControl() {
if (eventAdapter == null && mLayoutManager == null) {
eventList = new ArrayList<>();
eventAdapter = new EventAdapter(getActivity().getApplicationContext(), eventList);
mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(eventAdapter);
}
recyclerView.addOnItemTouchListener(new RecyclerItemListener(getActivity().getApplicationContext(), recyclerView, new RecyclerItemListener.RecyclerTouchListener() {
#Override
public void onClickItem(View v, int position) {
EventModel model = eventList.get(position);
SQLiteHandler db = SQLiteHandler.getInstance(getActivity().getApplicationContext());
//some instances
}
#Override
public void onLongClickItem(View v, int position) {
}
}));
}
//make service call
public void eventToList() {
if (requestData == null) {
requestData = new RequestData(getActivity());
}
final ArrayList<EventModel> newList = new ArrayList<>(); //are you leaking?
requestData.getEventToday(new RequestData.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
for (int i = 0; i < result.length(); i++) {
try {
JSONObject item = result.getJSONObject(Integer.toString(i));
EventModel eventModel = new EventModel();
String title = item.getString("title");
String start = item.getString("start");
String end = item.getString("end");
String date = item.getString("date");
eventModel.setDate(date);
eventModel.setStartTime(start);
eventModel.setEndTime(end);
eventModel.setTitle(title);
newList.add(eventModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
eventAdapter.update(newList);
}
});
}
}
Many thanks!
First of all, a design consideration: is it necessary to call web service every 10 seconds? Do you know when/how often server data changes?
Every time you read data from web server, application have to do a lot of work: you create many object, update the adapter etc. Moreover, think about network traffic, you use network every 10 seconds.
There are somethings you can do:
Increment wait time: in this way, you reduce the number of created object/per seconds.
Reduce local reference for temporary objects (see following code)
Check if recycler view's adapter, before add new values, the old ones was correctly deferred.
Evaluate if it is possible to use technology to push data, you to avoid data polling. You can see GCM.
For consideration #2, i try rewrite eventToList method:
public void eventToList() {
if (requestData == null) {
requestData = new RequestData(getActivity());
}
requestData.getEventToday(new RequestData.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
ArrayList<EventModel> newList = new ArrayList<>();
JSONObject item;
EventModel eventModel;
String title;
String start;
String end;
String date;
for (int i = 0; i < result.length(); i++) {
try {
item = result.getJSONObject(Integer.toString(i));
eventModel = new EventModel();
title = item.getString("title");
start = item.getString("start");
end = item.getString("end");
date = item.getString("date");
eventModel.setDate(date);
eventModel.setStartTime(start);
eventModel.setEndTime(end);
eventModel.setTitle(title);
newList.add(eventModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
eventAdapter.update(newList);
}
});
}
I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
[Activity_allday]
Public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}
This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 9 years ago.
I am badly stuck to pass object from one activity to another activity using Parcelable but I am getting null pointer exception at line Log.i("Name",""+rcp.getName());, you can check this line in below code. Plz do check code CookingDataModel class at the end.
Here is the code of object Receiving Activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// No title to display
setContentView(R.layout.recipe_ingredient_detail);
CookingDataModel cook = new CookingDataModel();
RecipeDataModel rcp;
ArrayList<IngredientDataModel> ing;
Bundle bundle = this.getIntent().getExtras();
if(bundle!=null)
cook = bundle.getParcelable("Cooking");
rcp = cook.getRecipe();
ing = cook.getIngredientList();
Log.i("Name",""+rcp.getName());
Log.i("Decrp",""+rcp.getDescription());
Log.i("Duration",""+rcp.getPrepTime());
Log.i("Instructions",""+rcp.getInstructions());
for(int k = 0; k < ing.size(); k++)
{
Log.i("Item Name",""+ing.get(k).getItemName());
Log.i("Item Amount",""+ing.get(k).getItemAmount());
}
}
Here is the code where I am sending object of CookingDataModel .
ListView recepeListView = getListView();
recepeListView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
CookingDataModel cook = recpeList.get(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("Cooking",cook);
intent.putExtras(bundle);
intent.setClass(RecipeList.this,RecipeIngredientDetail.class);
startActivity(intent);
}
});
Here is code of the CookingDataModel class.
public class CookingDataModel implements Parcelable{
private RecipeDataModel recipe = null;
private ArrayList<IngredientDataModel> ingredientList = null;
public RecipeDataModel getRecipe() {
return recipe;
}
public void setRecipe(RecipeDataModel recipe) {
this.recipe = recipe;
}
public ArrayList<IngredientDataModel> getIngredientList() {
return ingredientList;
}
public void setIngredientList(ArrayList<IngredientDataModel> ingredientList) {
this.ingredientList = ingredientList;
}
public static final Parcelable.Creator<CookingDataModel> CREATOR = new Parcelable.Creator<CookingDataModel>()
{
public CookingDataModel createFromParcel(Parcel in)
{
return new CookingDataModel(in);
}
public CookingDataModel[] newArray(int size)
{
return new CookingDataModel[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
}
public CookingDataModel(Parcel in) {
// TODO Auto-generated constructor stub
}
public CookingDataModel()
{
}
}
Please help me in this respect that I could proceed my project. Thanks in adavance.
On the main activity:
intent.putExtra("Cooking",cook);
Then on second activity:
getIntent().getExtras().getParcelable("Cooking");
Try this. Do not use bundle if you've just to send a single object.
You may need to cast the getIntent().... part, I'm not sure.
Few things that need change.
No need of creating a new object, it will be overwritten.
CookingDataModel cook = new CookingDataModel();
Typecast when you get the Parcelable object from intent extras,
cook = bundle.getParcelable("Cooking");
Make Sure when you sending the object, it has valid receipe member. If you notice, you are able to get the CookingDataModel from the intent, and also the Receipe from this object but not able to get data from ReceipeModel.
From the code in the sending activity, I cant really say if the CookingDataModel.Receipe is a valid object.
I have an activity where I am adding objects into an ArrayList which implements the Parcelable interface. I then pass this list to another activity via a bundle however I get the following error when I try to print the size of the list in the new activity:
java.lang.RuntimeException: Unable to resume activity {com.example.test/com.example.test.SectionsActivity}: java.lang.NullPointerException
Here is the first activity where I add to list:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), l.getItemAtPosition(position).toString() + " added to order", Toast.LENGTH_SHORT).show();
// add clicked item to orderData....
MenuItem m = (MenuItem) l.getItemAtPosition(position);
// create new item
orderData.add(m);
subTotal += m.getPrice();
calc();
}
This is first activity where I send the data via intent:
confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b.putParcelable("order", orderData);
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data",b);
startActivity(i);
}
});
and this is second activity where I try to retrieve the bundle and display size:
#Override
protected void onResume() {
super.onResume();
getIntentData();
}
public void getIntentData(){
Intent i = getIntent();
if(i != null & i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
b = i.getExtras();
orderData = b.getParcelable("order");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Any ideas why I am getting the null pointer?? It's driving me mad!
orderData is a MenuItemList object:
public class MenuItemList extends ArrayList <MenuItem> implements Parcelable{
/**
*
*/
private static final long serialVersionUID = 2998684930374219271L;
public MenuItemList(){
}
public static final Parcelable.Creator<MenuItemList> CREATOR = new Parcelable.Creator<MenuItemList>() {
#Override
public MenuItemList createFromParcel(Parcel source) {
return new MenuItemList(source);
}
#Override
public MenuItemList[] newArray(int size) {
return new MenuItemList[size];
}
};
public MenuItemList(Parcel source) {
readFromParcel(source);
}
private void readFromParcel(Parcel source) {
this.clear();
//read the size of the list
int size = source.readInt();
//Remember order of items written into the Parcel. Important here.
for(int i = 0; i < size; i ++){
MenuItem item = new MenuItem();
item.setName(source.readString());
item.setPrice(source.readDouble());
this.add(item);
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
int size = this.size();
dest.writeInt(size);
for(int i = 0; i < size; i ++){
MenuItem item = this.get(i);
dest.writeString(item.getName());
dest.writeDouble(item.getPrice());
}
}
#Override
public int describeContents() {
return 0;
}
}
CHANGES TO CODE THAT SOLVED PROBLEM:
CHANGED onClick(View v):
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", (ArrayList<MenuItem>)orderData);
startActivity(i);
}
CHANGED getIntent():
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
orderData = i.getParcelableExtra("data");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Rewrite
The problem is that you have an extra Bundle. Currently in getIntentData() you have to call:
getIntent() // Fetch the Intent,
.getExtras() // Fetch the Bundle of extras,
.getBundle("data") // Fetch the Bundle "data",
.getParcelable("order"); // Then get your parcelable...
Let's cut out the unnecessary Bundle.
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", orderData);
startActivity(i);
}
Now update getIntentData():
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
orderData = i.getParcelableExtra("data");
...
}
Unless I missed something, you are using the bitwise & instead of the logical && in your getIntentData() function