Parcelable object is Null on receiving activity and good in other - java

Thanks to those who will try to help me!
First time I sent a message. I'm stuck with my parcel.
I try to send an object Neighbour in a recyclerView for a class DetailedNeighbour. After I send my variable to DetailedActivity.putExtra("DNeighbour", neighbour); is well equal to what I want and after in DetailedNeighbourActivity is equal to null.
Neighbour:
package com.openclassrooms.entrevoisins.model;
/**
* Model object representing a Neighbour
*/
public class Neighbour implements Parcelable {
/** Identifier */
private long id;
/** Full name */
private String name;
/** Avatar */
private String avatarUrl;
/** Adress */
private String address;
/** Phone number */
private String phoneNumber;
/** About me */
private String aboutMe;
/**
* Constructor
* #param id
* #param name
* #param avatarUrl
*/
public Neighbour(long id, String name, String avatarUrl, String address,
String phoneNumber, String aboutMe) {
this.id = id;
this.name = name;
this.avatarUrl = avatarUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.aboutMe = aboutMe;
}
public Neighbour (Parcel in){ //constructor //Protected ?
id =in.readLong(); //read and set saved values from parcel
name=in.readString();
avatarUrl=in.readString();
address=in.readString();
phoneNumber=in.readString();
aboutMe=in.readString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAboutMe() {
return aboutMe;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Neighbour neighbour = (Neighbour) o;
return Objects.equals(id, neighbour.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public void writeToParcel(Parcel parcel, int flags) { // In this method you add all your class properties to the parcel which are needed to transfer.
parcel.writeString(name);
parcel.writeString(phoneNumber);
parcel.writeString(avatarUrl);
parcel.writeString(aboutMe);
parcel.writeString(address);
parcel.writeLong(id); /// for favoris ?
}
public static final Parcelable.Creator<Neighbour> CREATOR = new Parcelable.Creator<Neighbour>() { ///This is the method which is used to bind everything together. Nothing much is done here.
#Override
public Neighbour createFromParcel(Parcel in) {
return new Neighbour(in);
}
#Override
public Neighbour[] newArray(int size) {
return new Neighbour[size];
}
};
public static Creator<Neighbour> getCREATOR() {
return CREATOR;
}
#Override
public int describeContents() {
return 0;
}
}
RecyclerViewAdapter:
package com.openclassrooms.entrevoisins.ui.neighbour_list;
public class MyNeighbourRecyclerViewAdapter extends RecyclerView.Adapter<MyNeighbourRecyclerViewAdapter.ViewHolder> {
private final List<Neighbour> mNeighbours;
public MyNeighbourRecyclerViewAdapter(List<Neighbour> items) {
mNeighbours = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_neighbour, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Neighbour neighbour = mNeighbours.get(position);
holder.mNeighbourName.setText(neighbour.getName());
Glide.with(holder.mNeighbourAvatar.getContext())
.load(neighbour.getAvatarUrl())
.apply(RequestOptions.circleCropTransform())
.into(holder.mNeighbourAvatar);
holder.mNeighbourName.setOnClickListener(new View.OnClickListener() { /// Observe le clic sur bouton name
#Override
public void onClick(View view) {
Intent DetailedActivity = new Intent(view.getContext(), DetailedNeighbourActivity.class); //
DetailedActivity.putExtra("DNeighbour", neighbour);
view.getContext().startActivity(DetailedActivity);//
EventBus.getDefault();//
Log.i("DEBUG","l'utilisateur essaye d'ouvrir le détaille");
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post(new DeleteNeighbourEvent(neighbour));
}
});
}
#Override
public int getItemCount() {
return mNeighbours.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_list_avatar)
public ImageView mNeighbourAvatar;
#BindView(R.id.item_list_name)
public TextView mNeighbourName;
#BindView(R.id.item_list_delete_button)
public ImageButton mDeleteButton;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
DetailedNeighboursActivity:
public class DetailedNeighbourActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_neighbour);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Neighbour neighbour = (Neighbour) getIntent().getParcelableExtra("DNeighbour");
String name = neighbour.getName();
EventBus.getDefault();
Log.i("DEBUG", "Le détaille "+ name);
}
}

I'm not really smart ! Sorry for you time .
parcel and writeparcel constructor need the same order for variables. it's ok my code work.

Related

How to filter a custom listView with text, image and checkbox?

Watching a tutorial I have a listView.
I have an EditText and want to filter the listView content by what is in the EditText.
Here is my adapter class:
class ListViewAdapter extends BaseAdapter {
private List<listAudienceFriendsExcept> FriendsExceptList;
private Context context;
ListViewAdapter(Context context, List<listAudienceFriendsExcept> FriendsExceptList) {
this.context = context;
this.FriendsExceptList = FriendsExceptList;
}
#Override
public int getCount() {
return FriendsExceptList.size();
}
#Override
public Object getItem(int pos) {
return FriendsExceptList.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
TextView name = view.findViewById(R.id.name);
ImageView avatar = view.findViewById(R.id.avatar);
final CheckBox checkbox = view.findViewById(R.id.checkbox);
final listAudienceFriendsExcept thisListAudienceFriendsExcept = FriendsExceptList.get(position);
// Setting data to listView items
checkbox.setTag(thisListAudienceFriendsExcept.getId());
name.setText(thisListAudienceFriendsExcept.getGetFirstName());
if (!thisListAudienceFriendsExcept.getGetAvatar().equals("default_avatar.png")) {
Glide.with(avatar)
.load(API_BASE_URL+"files/avatar_back_files/"+thisListAudienceFriendsExcept.getGetAvatar())
.circleCrop()
.fitCenter()
.into(avatar);
} else if (thisListAudienceFriendsExcept.getGetSex().equals("male")) {
Glide.with(avatar)
.load(API_BASE_URL+"tools/img/default_avatar.png")
.circleCrop()
.fitCenter()
.into(avatar);
} else {
Glide.with(avatar)
.load(API_BASE_URL+"tools/img/female_default_avatar.png")
.circleCrop()
.fitCenter()
.into(avatar);
}
return view;
}
}
Here my list:
static class listAudienceFriendsExcept {
#SerializedName("id")
private int id;
#SerializedName("first_name")
private String first_name;
#SerializedName("last_name")
private String last_name;
#SerializedName("avatar")
private String avatar;
#SerializedName("sex")
private String sex;
public listAudienceFriendsExcept(int id, String first_name, String last_name, String avatar, String sex) {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
this.sex = sex;
}
int getId() {
return id;
}
String getGetFirstName() {
return first_name;
}
String getGetLastName() {
return last_name;
}
String getGetAvatar() {
return avatar;
}
String getGetSex() {
return sex;
}
}
Here my populateListView:
private void populateListView(List<listAudienceFriendsExcept> thisList) {
ListView listViewAudienceFriendsExcept = findViewById(R.id.listViewAudienceFriendsExcept);
ListViewAdapter adapter = new ListViewAdapter(this, thisList);
listViewAudienceFriendsExcept.setAdapter(adapter);
}
I tried that:
final TextInputEditText first_name_edit_text = findViewById(R.id.first_name_edit_text);
first_name_edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence cs, int s, int b, int c) {
friendListAdapter.getFilter().filter(newText); // What is **friendListAdapter** in my case ?
}
I'm using Retrofit tho get data from server when activity start:
private void callServer() {
/*Create handle for the RetrofitInstance interface*/
df myAPIService = RetrofitClientInstance.getRetrofitInstance().create(df.class);
Call<List<listAudienceFriendsExcept>> call = myAPIService.getListAudienceFriendsExcept();
call.enqueue(new Callback<List<listAudienceFriendsExcept>>() {
#SuppressWarnings("NullableProblems")
#Override
public void onResponse(Call<List<listAudienceFriendsExcept>> call, Response<List<listAudienceFriendsExcept>> response) {
populateListView(response.body());
}
#SuppressWarnings("NullableProblems")
#Override
public void onFailure(Call<List<listAudienceFriendsExcept>> call, Throwable throwable) {
Toast.makeText(MainActivity.this, throwable.getMessage()+"èèè", Toast.LENGTH_LONG).show();
}
});
}
I have googled and found that: friendListAdapter.getFilter().filter(newText); But I don't know to use in my case.
Any Solution?
My other question:
How could I pass the user ID to php server ?
Thanks.`
You can use streams to filter.
//add this imports on your class or activity
//import com.annimon.stream.Collectors;
//import com.annimon.stream.Stream;
//import com.annimon.stream.function.Predicate;
List<listAudienceFriendsExcept> original_list=new ArrayList<>();
List<listAudienceFriendsExcept> search_list=new ArrayList<>();
EditText serch_field;
void setup()
{
//original_list=whatever the source of the list is
//be sure to populate the original list before proceeding here
populateListView(original_list);
serch_field.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
search_list = Stream.of(original_list).filter(new Predicate<listAudienceFriendsExcept>() {
#Override
public boolean test(listAudienceFriendsExcept item) {
// return item.getGetFirstName().toUpperCase().contains(serch_field.getText().toString().toUpperCase())||item.getGetLastName().toUpperCase().contains(serch_field.getText().toString().toUpperCase());//if you want to filter multiple fields
return item.first_name.toUpperCase().contains(serch_field.getText().toString().toUpperCase());//to filter first name only
}
}).collect(com.annimon.stream.Collectors.<listAudienceFriendsExcept>toList());
populateListView(search_list);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
For the model
public class listAudienceFriendsExcept {
#SerializedName("id")
private int id;
#SerializedName("first_name")
public String first_name;
#SerializedName("last_name")
private String last_name;
#SerializedName("avatar")
private String avatar;
#SerializedName("sex")
private String sex;
public listAudienceFriendsExcept(int id, String first_name, String last_name, String avatar, String sex) {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
this.sex = sex;
}
int getId() {
return id;
}
public String getGetFirstName() {
return first_name;
}
public String getGetLastName() {
return last_name;
}
public String getGetAvatar() {
return avatar;
}
public String getGetSex() {
return sex;
}
}
And on Gradle-dependencies add
implementation 'com.annimon:stream:1.1.2'

Firebase model POJO getter returns null in FirebaseRecyclerAdapter

I have a FirebaseRecyclerAdapter fetching data from the firebase database but when I am trying to access firebase data the getter method of the POJO returns null. I am able to get the database reference key.
final Query beveragesQuery = mDatabaseReference.child(FirebaseValues.PRODUCTS)
.child(FirebaseValues.BEVERAGES);
FirebaseRecyclerOptions<GenericProductModel> beveragesOptions =
new FirebaseRecyclerOptions.Builder<GenericProductModel>()
.setQuery(beveragesQuery, GenericProductModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<GenericProductModel, Combos.MovieViewHolder>(
beveragesOptions
) {
#NonNull
#Override
public Combos.MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_cardview_layout, parent, false);
return new Combos.MovieViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Combos.MovieViewHolder viewHolder, int position, #NonNull GenericProductModel model) {
Log.d(TAG, "Item received:"+getRef(position).getKey());
String json = new Gson().toJson(model);
Log.d(TAG, "Item received:"+ json);
Log.d(TAG, "Item received:"+ model.toString());
if (tv_no_item.getVisibility() == View.VISIBLE) {
tv_no_item.setVisibility(View.GONE);
}
Log.d(TAG, "card name:"+model.getCardname());
viewHolder.cardname.setText(model.getCardname());
viewHolder.cardprice.setText("₹ " + Float.toString(model.getCardprice()));
Picasso.get().load(model.getCardimage()).into(viewHolder.cardimage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Beverages.this, IndividualProduct.class);
intent.putExtra("product", getItem(position));
startActivity(intent);
}
});
}
#Override
public void onError(DatabaseError e) {
Log.e(TAG, "RV Adapter, Error occurred: " + e.getMessage());
}
};
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
adapter.startListening();
mRecyclerView.setAdapter(adapter);
}
My POJO or model class is
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
I am implementing Serializable because I am sending this data as an intent to other activity.
Added some more log options for clearity
When I run the app the log output I am getting is:
03-17 15:05:55.200 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received, received:1
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:{"a":0,"e":0.0}
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:com.vdeveloper.chaisutta.b.a#63d3fc
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: card name:null
Database Screenshot:
I have found a solution myself. The problem was with my POJO. As this project was on androidx I need to add the annotation "#Keep" to stop the compiler from removing methods which it thinks are redundant.
import java.io.Serializable;
import androidx.annotation.Keep;
#Keep
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
Thanks, everyone for helping
You are getting null because all your values are null since you are returning in each getter this.fieldName instead of the fieldName. To solve this, please change your getters to:
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
See, there is no this anymore.

Method getParcelableExtra() returns null when creating an intent

I have a problem regarding the creation of an intent and the handover of an object with the getParcelableExtra() method to it.
The aim of the project is the creation of a recycler view. If an item from the recycler is selected a new intent gets started and should display more detailed data.
Because the data is fetched from an external MySQL DB I'm using Volley for most of the networking stuff.
The recycler is implemented inside the Volley onResponse() method which is first called at app start (onCreate). Until this point everything works fine and the recycler is loaded and displayed correctly.
public class UserAreaActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
initializeRecycler();
}
public void initializeRecycler() {
operations.getFoodFromDB(getFoodID(), new IDatabaseOperations() {
#Override
public void onSuccess(final ArrayList<Food> food_list) {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLayoutmanager = new LinearLayoutManager(UserAreaActivity.this);
mAdapter = new FoodAdapter(food_list);
mRecyclerView.setLayoutManager(mLayoutmanager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {
#Override
public void OnItemClick(int position) {
Intent intent = new Intent(UserAreaActivity.this, FoodProfile.class);
GETS CORRECT OBJECT----->intent.putExtra("food", food_list.get(position));
startActivity(intent);
}
});
}
});
}
}
As you see I created an interface for the Volley onResponse method called onSuccess. Inside this method I am creating an onItemClickListener and this is where it gets ugly.
The onItemClickListener opens up the more detailed view of the item, but the method getParcelableExtra() returns NULL. Whatever I do it never returns an object of the class Food.
public class FoodProfile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_food_profile);
Food food = getIntent().getParcelableExtra("food");<----RETURNS NULL
String price = food.getPrice();
String name = food.getName();
String rating = ((Float)food.getRating()).toString();
String imageRes = food.getmimgId();
TextView mPrice = (TextView) findViewById(R.id.Price);
mPrice.setText(price);
TextView mName = (TextView) findViewById(R.id.Name);
mName.setText(name);
TextView mRating = (TextView) findViewById(R.id.Rating);
mRating.setText(rating);
}
}
So the putExtra() works as intended and gets the correct object of the food class. But getParcelableExtra() returns NULL everytime. So no value is displayed in the started intent.
Food class:
public class Food implements Parcelable {
public int id;
public String name;
public String category;
public String date;
public int vegan;
public int vegetarian;
public String price;
public String uuid;
public float rating;
public String mimgId;
public Food(int id, String name, String category, int vegan, int vegetarian, String price, String uuid, float rating, String mimgId){
this.id = id;
this.name = name;
this.category = category;
this.date = date;
this.vegan = vegan;
this.vegetarian = vegetarian;
this.price = price;
this.uuid = uuid;
this.rating = rating;
this.mimgId = mimgId;
}
protected Food(Parcel in) {
id = in.readInt();
name = in.readString();
category = in.readString();
date = in.readString();
vegan = in.readInt();
vegetarian = in.readInt();
price = in.readString();
uuid = in.readString();
rating = in.readFloat();
mimgId = in.readString();
}
public static final Creator<Food> CREATOR = new Creator<Food>() {
#Override
public Food createFromParcel(Parcel in) {
return new Food(in);
}
#Override
public Food[] newArray(int size) {
return new Food[size];
}
};
public int getId() {
return id;
}
public String getName() {
if(name != null) {
name = name.replaceAll(System.getProperty("line.separator"), (""));
}
return name;
}
public String getDate() {
return date;
}
public int isVegan() {
return vegan;
}
public int isVegetarian() {
return vegetarian;
}
public String getPrice() {
return price;
}
public String getUuid() {
return uuid;
}
public float getRating(){return rating;}
public String getmimgId() {
return mimgId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(price);
dest.writeString(name);
dest.writeString(((Float)rating).toString());
dest.writeString(mimgId);
}
}
Has anyone an idea whats causing the getParcelableExtra() to return null?
Thanks for your help in advance!
As I commented above, the writeToParcel() is problematic. The parcel should be written and read in the same order.
Please refer to the following pages as reference:
What is Parcelable in android
Using Parcelable
Understanding Androids Parcelable - Tutorial

How to pass a class with an abstract class type as parameter in parcelable android studio java

I am trying to pass this class as a parcelable in android.
public class Outfit implements Parcelable {
private List<Item> itemList;
private String mName;
private String mImageUrl;
public Outfit() {}
public Outfit(String mName, String mImageUrl) {
this.mName = mName;
this.mImageUrl = mImageUrl;
}
protected Outfit(Parcel in) {
itemList = in.createTypedArrayList(Item.CREATOR);
mName = in.readString();
mImageUrl = in.readString();
}
public static final Creator<Outfit> CREATOR = new Creator<Outfit>() {
#Override
public Outfit createFromParcel(Parcel in) {
return new Outfit(in);
}
#Override
public Outfit[] newArray(int size) {
return new Outfit[size];
}
};
public String getmName() {
return mName;
}
public String getmImageUrl() {
return mImageUrl;
}
#Override
public String toString() {
return mName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeTypedList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
}
the problem is that Item is abstract and itemList = in.creatTypedArrayList(Item.CREATOR) because Item does not have a CREATOR . Only its subclasses have this implementation.
Item.java
public abstract class Item implements Parcelable {
private String mName;
private String mColor;
private String mImageUrl;
private List<TagHolder> tags = new ArrayList<>();
private String mKey;
public Item(){
}
public Item(String mName, String mColor, String mImageUrl) {
this.mName = mName;
this.mColor = mColor;
this.mImageUrl = mImageUrl;
}
protected Item(Parcel in) {
mName = in.readString();
mColor = in.readString();
mImageUrl = in.readString();
tags = in.createTypedArrayList(TagHolder.CREATOR);
mKey = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeString(mColor);
dest.writeString(mImageUrl);
dest.writeTypedList(tags);
dest.writeString(mKey);
}
#Override
public int describeContents() {
return 0;
}
public void setmName(String mName) {
this.mName = mName;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public List<TagHolder> getTags() {
return tags;
}
public String getmColor() {
return mColor;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmColor(String mColor) {
this.mColor = mColor;
}
public String getmName() {
return mName;
}
public void setTags(List<TagHolder> tags) {
this.tags = tags;
}
#Exclude // dont need this in our firebase database
public String getKey() {
return mKey;
}
#Exclude
public void setMkey(String key) {
mKey = key;
}
public abstract String getCategory();
}
I am able to parce a List as a parcelable array when I call put extra. But when I try to do so for outfit it gives error . Is there any way to pass Outfit as a parcelable?
Do you try using another method for the list?
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
protected Outfit(Parcel in) {
in.readList(itemList, Item.class.getClassLoader());
mName = in.readString();
mImageUrl = in.readString();
}

Parcelable error Attempt to invoke virtual method on a null object reference

I am trying to use parcelable to make a simple edit form. The data was received from an array list. But, when I try to run it, there is an error:
Attempt to invoke virtual method 'int com.insiteprojectid.practiceadapter.user.Student.getId()' on a null object reference
These are my codes:
public class StudentActivity extends AppCompatActivity {
private ListView lv;
private CustomUsersAdapter customUsersAdapter;
private TextView emptyTextView;
private StaticStudent staticStudent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
customUsersAdapter = new CustomUsersAdapter(this, new ArrayList<Student>());
lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(customUsersAdapter);
emptyTextView = (TextView)findViewById(R.id.emptyView);
lv.setEmptyView(emptyTextView);
staticStudent = StaticStudent.getInstance();
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fabButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),AddStudentActivity.class);
intent.putExtra("action","add");
startActivity(intent);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), AddStudentActivity.class);
Student student = staticStudent.get(position);
intent.putExtra("StudentList", student);
startActivity(intent);
}
});
}
private void populateStudentDummies() {
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student(1, "3135136188", "TRI FEBRIANA SIAMI", "tri.febriana#unj.ac.id", "021577888"));
studentList.add(new Student(2, "3135136192", "UMMU KULTSUM", "ummu.kultsum#unj.ac.id", "021577888"));
studentList.add(new Student(3, "3135136215", "ANDREAN OKTAVIANUS H.S.", "andrean.ohs#unj.ac.id", "021577888"));
staticStudent.AddStudents(studentList);
customUsersAdapter = new CustomUsersAdapter(this,staticStudent.getList());
lv.setAdapter(customUsersAdapter);
}
#Override
protected void onResume() {
//overriding method
super.onResume();
//check size of student list
if(staticStudent.count()==0) {
customUsersAdapter = new CustomUsersAdapter(this, new ArrayList<Student>());
//set emptyView
emptyTextView.setText("No Student Found");
} else{
customUsersAdapter = new CustomUsersAdapter(this, staticStudent.getList());
}
lv.setAdapter(customUsersAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_student_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.createDummy:
populateStudentDummies();
return true;
case R.id.clearList:
StaticStudent.getInstance().clearList();
customUsersAdapter = new CustomUsersAdapter(this, new ArrayList<Student>());
lv.setAdapter(customUsersAdapter);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
the Parcelable subclass:
public class Student implements Parcelable{
private int id;
private String noreg;
private String name;
private String mail;
private String phone;
public Student(int id, String noreg, String name, String mail, String phone){
this.id = id;
this.name = name;
this.mail = mail;
this.phone = phone;
this.noreg = noreg;
}
protected Student(Parcel in) {
this.id = in.readInt();
this.noreg = in.readString();
this.name = in.readString();
this.mail = in.readString();
this.phone = in.readString();
}
public Student(){
}
public static final Creator<Student> CREATOR = new Creator<Student>() {
#Override
public Student createFromParcel(Parcel in) {
return new Student(in);
}
#Override
public Student[] newArray(int size) {
return new Student[size];
}
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNoreg() {
return noreg;
}
public void setNoreg(String noreg) {
this.noreg = noreg;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getId());
dest.writeString(getNoreg());
dest.writeString(getName());
dest.writeString(getMail());
dest.writeString(getPhone());
}
}
and then the method
public class StaticStudent {
private static ArrayList<Student> studentList = new ArrayList<>();
private static StaticStudent instance = new StaticStudent();
public static ArrayList<Student> getStudentList() {
return studentList;
}
public static void setStudentList(ArrayList<Student> studentList) {
StaticStudent.studentList = studentList;
}
public static StaticStudent getInstance() {
return instance;
}
public static void setInstance(StaticStudent instance) {
StaticStudent.instance = instance;
}
public void addStudent(Student student){
student.setId(nextId());
studentList.add(student);
}
public int nextId(){
return studentList.size()+1;
}
public Student removeLast(){
Student student = studentList.remove(studentList.size()-1);
return student;
}
public Student get(int index){
Student student = studentList.get(index);
return student;
}
public void set(int index, Student student){
studentList.set(index, student);
}
public Student remove(int index){
Student student = studentList.remove(index);
resetCounterId(index);
return student;
}
public Student getLast(){
Student student = studentList.get(studentList.size() - 1);
return student;
}
public void AddStudents(ArrayList<Student> students){
studentList.addAll(students);
resetCounterId(0);
}
public ArrayList<Student> getList(){
return studentList;
}
public int count(){
return studentList.size();
}
private void resetCounterId(int i){
for (int j = i; j < studentList.size(); j++) {
studentList.get(j).setId(j);
}
}
public void clearList(){
studentList.clear();
}
}
this is the logcat
10-20 11:23:34.753 22842-22842/com.insiteprojectid.practiceadapter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.insiteprojectid.practiceadapter, PID: 22842
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.insiteprojectid.practiceadapter/com.insiteprojectid.practiceadapter.AddStudentActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.insiteprojectid.practiceadapter.user.Student.getId()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:967)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.insiteprojectid.practiceadapter.user.Student.getId()' on a null object reference
at com.insiteprojectid.practiceadapter.AddStudentActivity.onCreate(AddStudentActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.access$800(ActivityThread.java:169) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5546) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:967) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 

Categories

Resources