application close without error messages - android

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/

Related

How do I change the image in other activities when I click the button?

When I click the image button (can_button) in "Giftshop Activity", how to change the "main_cat" image in "Main Activity" to the "can_cat" image for 9 seconds and return to the "main_cat" image?
I tried this code, but don't change the image.
public class GiftshopActivity extends AppCompatActivity {
private static final String TAG = "Giftshop_Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_giftshop);
// change MainActivity
ImageButton home = (ImageButton) findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GiftshopActivity.this, MainActivity.class);
startActivity(intent);
}
});
// change can_cat image
ImageButton can_button = (ImageButton) findViewById(R.id.can_button);
can_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GiftshopActivity.this, MainActivity.class);
intent.putExtra((String) ImageNavInfo.BUNDLE_KEY, ImageNavInfo.longDelay(R.raw.can)); //second param is Serializable
startActivity(intent);
}
});
public class MainActivity extends AppCompatActivity {
// main_cat
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// main_cat image
ImageView main_cat = (ImageView) findViewById(R.id.maincat);
Glide.with(this).load(R.raw.main_cat).into(main_cat);
public class CanActivity extends AppCompatActivity {
// can_cat
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_can);
ImageNavInfo imageNavInfo = (ImageNavInfo) getIntent().getSerializableExtra("ImageNavInfo");
if (imageNavInfo == null)
imageNavInfo = ImageNavInfo.noDelay(R.raw.main_cat);
ImageView can = (ImageView) findViewById(R.id.can_cat);
Glide.with(this).load(ImageNavInfo.drawableId).into(can);
Handler hand = new Handler();
hand.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(CanActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, imageNavInfo.delayMillis);
public class ImageNavInfo implements Serializable {
public static final Object BUNDLE_KEY = "ImageNavInfo";
#DrawableRes
static int drawableId;
final long delayMillis;
private ImageNavInfo(int drawableId, long delayMillis) {
this.drawableId = drawableId;
this.delayMillis = delayMillis;
}
// Getters skip
public static ImageNavInfo noDelay(int drawableId) {
return new ImageNavInfo(drawableId, 0L);
}
public static ImageNavInfo longDelay(int drawableId) {
return new ImageNavInfo(drawableId, 9000L);
}
}
English is not natural because I am Korean. Thank you for your understanding.

Android RecyclerView does not refresh after insert

I have a problem with my RecyclerView.
I have a ProductDetailActivity which shows the detail of a product and i have a RecyclerView with its adapter in it.
The user can click on the give rating button which navigates to the RatingActivity where you can give a rating to the product.
The problem is that when i submit my rating and automatically go back to my RatingActivity, the RecyclerView does not get the recently added rating. i have to go back to my productlist and reclick on the product to see the recently added rating.
Here is my code:
ProductDetailActivity:
public class ProductDetailActivity extends AppCompatActivity {
public AppDatabase appDatabase;
private static final String DATABASE_NAME = "Database_Shop";
private RecyclerView mRecycleviewRating;
private RatingAdapter mAdapterRating;
private Button btnGoToRatingActivity;
List<Rating> ratings;
Product p;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
btnGoToRatingActivity = findViewById(R.id.btn_goToRatingActivity);
Intent intent = getIntent();
id = intent.getIntExtra("productid", -1);
// pour montrer tous les ratings d'un produit, tu fais un getall
p = appDatabase.productDAO().getProductById(id);
ImageView imageView = findViewById(R.id.imageDetail);
TextView textViewName = findViewById(R.id.txt_nameDetail);
TextView textViewAuthor = findViewById(R.id.txt_authorDetail);
TextView textViewCategory = findViewById(R.id.txt_categoryDetail);
TextView textViewDetail = findViewById(R.id.txt_descriptionDetail);
Picasso.get().load(p.getProductImage()).fit().centerInside().into(imageView);
textViewName.setText(p.getProductName());
textViewAuthor.setText(p.getProductAuthor());
textViewCategory.setText(p.getProductCategory());
textViewDetail.setText(p.getProductDescription());
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
mRecycleviewRating = findViewById(R.id.recyclerRating_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecycleviewRating.setLayoutManager(linearLayoutManager);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapterRating = new RatingAdapter(ratings);
mRecycleviewRating.setAdapter(mAdapterRating);
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
startActivity(i);
}
});
mAdapterRating.notifyDataSetChanged();
}
#Override
public void onResume() {
super.onResume();
ratings = appDatabase.ratingDAO().getRatingByProductId(id); // reload the items from database
mAdapterRating.notifyDataSetChanged();
System.out.println(mAdapterRating.ratings.size());
}
}
RatingActivity:
public class RatingActivity extends AppCompatActivity implements RatingGiveFragment.RatingListener {
RelativeLayout mRelativeLayout;
private Button btnConfirmRating;
private EditText mComment;
private RatingBar mRatingBar;
public AppDatabase appDatabase;
private RatingAdapter mAdapter;
List<Rating> ratings;
private static final String DATABASE_NAME = "Database_Shop";
Product p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
int idProduct = RatingActivity.this.getIntent().getIntExtra("productid",-1);
p = appDatabase.productDAO().getProductById(idProduct);
mRatingBar = findViewById(R.id.rating_bar);
mComment = findViewById(R.id.txt_insertOpinionText);
mRelativeLayout = findViewById(R.id.activity_rating);
btnConfirmRating = findViewById(R.id.buttonConfirmRating);
mAdapter = new RatingAdapter(ratings);
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
mAdapter.notifyDataSetChanged();
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
}
/*private class insertRating extends AsyncTask<String,Integer, Integer>
{
#Override
protected Integer doInBackground(String... strings) {
Rating rating = new Rating(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]), strings[3], strings[4]);
appDatabase.ratingDAO().insertRating(rating);
return 1;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer == 1)
{
Toast.makeText(getApplicationContext(), getString(R.string.createRating), Toast.LENGTH_SHORT).show();
}
}
}*/
#Override
public void ratingChanged(int newRating) {
RatingTextFragment textFragment = (RatingTextFragment) getSupportFragmentManager().findFragmentById(R.id.fmt_text);
textFragment.setRating(newRating);
}
private boolean checkEmptyFields(){
if(TextUtils.isEmpty(mComment.getText().toString())){
return true;
}else{
return false;
}
}
}
RatingAdapter:
public class RatingAdapter extends RecyclerView.Adapter<RatingAdapter.RatingViewHolder> {
List<Rating> ratings;
public RatingAdapter(List<Rating> ratings){
this.ratings = ratings;
}
#NonNull
#Override
public RatingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rating_row,viewGroup, false);
return new RatingViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RatingViewHolder ratingViewHolder, int position) {
ratingViewHolder.ratingUsername.setText(ratings.get(position).getRatingUsername());
ratingViewHolder.ratingNumber.setText(String.valueOf(ratings.get(position).getRatingNumber()) + "/5");
ratingViewHolder.ratingComment.setText(ratings.get(position).getRatingText());
}
#Override
public int getItemCount() {
return ratings.size();
}
public static class RatingViewHolder extends RecyclerView.ViewHolder{
public TextView ratingUsername;
public TextView ratingNumber;
public TextView ratingComment;
public RatingViewHolder(#NonNull View itemView) {
super(itemView);
ratingUsername = itemView.findViewById(R.id.txt_usernamerating);
ratingNumber = itemView.findViewById(R.id.num_rating);
ratingComment = itemView.findViewById(R.id.txt_ratingComment);
}
}
}
Pictures:
You get no update in the ProductDetailActivity because you are not updating the data object ratings in the ProductDetailActivity that is the basis for the RatingAdapter.
It would be better to use startActivityForResult in the onClick()method of the ProductDetailActivity. Then you need to override the onActivityResult() method in the ProductDetailActivity. Evaluate the return values and update your data source if necessary, then call notifyDataSetChanged.
This is just pseudo code!
Changes to ProductDetailActivity:
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
// with this you are telling the activity to expect results and..
//..to deal with them in onActivityResult
startActivityForResult(i, 1);
}
});
// You do not need this next line because setting the adaper triggers the first
//mAdapterRating.notifyDataSetChanged();
}
Add the onActivityResult() method to the ProductDetailActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
// trigger a method to update the data object that is linked to the adapter
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
// and now that the data has actually been updated you can call notifyDataSetChanged!!
mAdapterRating.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Probably do nothing or make a Toast "Canceled"??
}
}
}
Changes to RatingActivity:
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
// I will just assume this works!
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
Intent intent = new Intent();
//If you need to return some value.. do it here other you do not need it
//intent.putExtra("result", result);
setResult(Activity.RESULT_OK, intent);
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
Please be aware in RatingActivity that in btnConfirmRating.setOnClickListener notifying the adapter with mAdapter.notifyDataSetChanged(); does nothing: firstly, because the adapter in the RatingActivity has nothing to do with the adapter in the ProductDetailActivity; secondly: you call finish(); in the next line of code.

Adding datas into an array to list in another activity

Below are the 3 java classes that I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array but I am quite confused on how the logic must be for the code to send the datas keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. Do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java - https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java - https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java - https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
you can store them as public static variable or create AddActivity constructor and get functions.
String student name; /*add value to this variable #onCreate or wherever in your AddActivity*/
public class AddActivity(/*here to pass data to addactivity*/){
//
}
public String getName(){
return this.name;
}
in another activity
AddActivity ac = new AddActivity();
String someName = ac.getName();
you can use this logic to pass data.
Edit
but if you want to pass data with Intent then just check intenr content onCreate()
Intent i = getIntent();
if(i.hasExtra("intentKey")){//check if it s not null
String name = i.getExtraString("intentKay");
}
The best solution I could find is, declare that array list as static and you could access those wherever you want provided if the classes are in the same package. But if you want to store those values, used shared preferences. Hope this may helps out.

I have error when use context in adapter, i would like use startActivityForResult(...) in adapter, how should I do?

and thank you in advance for your suggestions.
MainActivity.java
RecyclerView.Adapter mAdapter;
#Override
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mAdapter = new MyAdapter(getBaseContext(),TITLES,ICONS,NAME,EMAIL,PROFILE);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
...}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
String path = "";
mImageCaptureUri = data.getData();
path = getPath(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath();
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
mImageView.setImageBitmap(bitmap);
}
Myadapter.java
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
...
Context mContext;
Activity mActivity;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public static class ViewHolder extends RecyclerView.ViewHolder {...}
MyAdapter(Context context, String Titles[],int Icons[],String Name,String Email, int Profile){
this.mContext = context;
mNavTitles = Titles
mIcons = Icons;
name = Name;
email = Email;
profile = Profile;
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
if(holder.Holderid ==1) {
holder.textView.setText(mNavTitles[position - 1]);
holder.imageView.setImageResource(mIcons[position -1]);
}
else{
holder.profile.setImageResource(profile);
holder.Name.setText(name);
holder.email.setText(email);
holder.profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity = (Activity)mContext;
Intent imageIntent = new Intent();
imageIntent.setType("image/*");
imageIntent.setAction(imageIntent.ACTION_GET_CONTENT);
mActivity.startActivityForResult(Intent.createChooser(imageIntent, "Select photo"), 2);
}
});
}
}
It's possible call startActivityForResult in Adapter?
Why error is on mActivity = (Activity)mContext;?
p.s.: I tried to create method
public void startxx(Intent i){
startActivityForResult(i, 2);
}
and call this in Adapter...but Adapter wants statxx static and Activity non-static.
Context is Base class for Activity. You can not downcast object in Java. Thats why you can not perform mActivity = (Activity)mContext;.
You can not call startActivityForResult() from as Adapter class as it is method of Activity.java class. Here is one solution you can try -
- Declare one interface. say IObserver.java
public interface IObserver {
// change signature of method as per your need
public abstract void onItemClicked();
}
}
Write one method in Adapter class say
public void setListener(IObserver obs) {
mObserver = obs;
}
Implement IObserver interface in Activity class. You need to implement onItemClicked() method as well.
From onCreate() method of activity, call adapter.setListener(this);
In adapter class, from onClick() method, write code as below
holder.profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// It will call method from activity class where you can do startActivityForResult()
mObserver.onItemClicked();
}
});
Hope it will help.

RuntimeException when trying to getParcelableArray in target activity

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?

Categories

Resources