NullPointerException on Android Parcelable Object on Intent - java

I have this problem with this piece of code and I have been a few days trying to solve it and I can't find the solution.
I have this parcelable class:
public class Sistema implements Parcelable{
private ArrayList<Lista> listas;
private ArrayList<Articulo> articulos;
public Sistema() {
listas = new ArrayList<Lista>();
articulos = new ArrayList<Articulo>();
}
public ArrayList<Lista> getListas() {
return listas;
}
public void agregarLista(Lista lista) {
this.getListas().add(lista);
}
public ArrayList<Articulo> getArticulos(){
return this.articulos;
}
public void agregarArticulo(Articulo articulo){
this.getArticulos().add(articulo);
}
public static final Parcelable.Creator<Sistema> CREATOR =
new Parcelable.Creator<Sistema>() {
#Override
public Sistema createFromParcel(Parcel parcel) {
return new Sistema(parcel);
}
#Override
public Sistema[] newArray(int size) {
return new Sistema[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeTypedList(listas);
parcel.writeTypedList(articulos);
}
public Sistema(Parcel parcel)
{
parcel.readTypedList(listas, Lista.CREATOR);
parcel.readTypedList(articulos, Articulo.CREATOR);
}
}
And then in the main i use an intent to send a Sistema object to an other activity:
public void addArticle(View view) {
Intent intent = new Intent(this, AgregarArticulo.class);
intent.putExtra("objectSystem", s);
this.startActivityForResult(intent, 1);
}
Here is where the problem is, i recieve the intent in the second activity with this code:
Intent intento = getIntent();
s = intento.getParcelableExtra("objectSystem");
When I run the code, i get a NullPointerException in the getParcelableExtra
Do you guys have an idea of what the problem should be?
Thanks

Could you please try this . You need to prefix your package name(com.example.whatever) with the name your passing in putExtra:
public void addArticle(View view) {
Intent intent = new Intent(this, AgregarArticulo.class);
intent.putExtra("YOURPACKAGENAME.objectSystem", s);
this.startActivityForResult(intent, 1);
}
and same in getParcelableExtra also:
Intent intento = getIntent();
s = intento.getParcelableExtra("YOURPACKAGENAME.objectSystem");

Related

Get object from intent throws null

I am trying to pass an object to another class using intent. The object implements Parcelable.
The thing is, when I try to get the attributes it doesn't get the object, it says it's null.
But when I do a System.out.println of the intent.getExtras():
Bundle[{usuariocreado =com.example.frpi.repasando.Usuario#4ed1d39}]
It's actually there!
if (this.getIntent().getExtras() != null) {
Usuario usuariocreado = intent.getParcelableExtra("usuariocreado");
usuariocreado.getNombreUsuario();
} else {
System.out.println("Mierda");
}
This is the code on MainActivty which receives the intent.
NombreUsuario = (EditText) findViewById(R.id.UsuarioRegister);
PasswordPrimero = (EditText) findViewById(R.id.PasswordPrimero);
Usuario obj = new Usuario(String.valueOf(NombreUsuario.getText()), String.valueOf(PasswordPrimero.getText()));
Intent intent = new Intent(getBaseContext(), MainActivity.class);
Usuario usuariocreado = new Usuario(String.valueOf(NombreUsuario.getText()), String.valueOf(PasswordPrimero.getText()));
intent.putExtra("usuariocreado ", usuariocreado);
startActivity(intent);
This is the code on the SecondActivity which sends the intent.
What am i doing wrong??
Thanks!
public class Usuario implements Parcelable {
public Usuario(String nombreUsuario, String passwordPrimero) {
NombreUsuario = nombreUsuario;
PasswordPrimero = passwordPrimero;
}
/**
* NombreUsuario : Paco
* PasswordPrimero : Example
*/
private String NombreUsuario;
private String PasswordPrimero;
protected Usuario(Parcel in) {
NombreUsuario = in.readString();
PasswordPrimero = in.readString();
}
public static final Creator<Usuario> CREATOR = new Creator<Usuario>() {
#Override
public Usuario createFromParcel(Parcel in) {
return new Usuario(in);
}
#Override
public Usuario[] newArray(int size) {
return new Usuario[size];
}
};
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String NombreUsuario) {
this.NombreUsuario = NombreUsuario;
}
public String getPasswordPrimero() {
return PasswordPrimero;
}
public void setPasswordPrimero(String PasswordPrimero) {
this.PasswordPrimero = PasswordPrimero;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(NombreUsuario);
dest.writeString(PasswordPrimero);
}
}
You have to cast the intent.getParcelableExtra("usuariocreado") with Usuario
Replace
Usuario usuariocreado = intent.getParcelableExtra("usuariocreado");
with
Usuario usuariocreado = ((Usuario) intent.getParcelableExtra("usuariocreado"));

How do I iterate through an ArrayList of custom objects from Intent and add them into LinearLayout?

I have an ArrayList of custom FlightData objects within the intent. I load the intent and get the arraylist as null, and the foreach loop also forces me to use Object as type.
Saving arraylist into intent:
intent.putParcelableArrayListExtra("FlightDataList", (ArrayList<? extends Parcelable>) flightDataList);
Loading of intent:
Intent intent = getIntent();
LinearLayout layout_datasheet = findViewById(R.id.layout_datasheet);
List flightDataList = intent.getParcelableArrayListExtra("FlightDataList");
if (flightDataList == null){
Log.d("flightDataList_size", "FlightDataList is null"); // this fires
}
assert flightDataList != null;
for (Object data : flightDataList){
data = (FlightData) data; // items in list are of type FlightData
TextView tv = new TextView(this);
tv.setText(data.toString());
layout_datasheet.addView(tv);
}
My custom class' parcelable functions (x,y,time, has getters-setters):
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(x);
dest.writeDouble(y);
dest.writeDouble(time);
}
public static final Creator<FlightData> CREATOR = new Creator<FlightData>() {
#Override
public FlightData createFromParcel(Parcel in) {
return new FlightData(in);
}
#Override
public FlightData[] newArray(int size) {
return new FlightData[size];
}
};
1.First Implement Parceable in your FlightData object model / pojo / class
2.val flightDataList= ArrayList<FlightData>()
3.val args = Bundle()
4.args.putParcelableArrayList("FlightDataList", flightDataList)
5.intent.putExtra(args)
Then to get list
val flightDataList = context.getIntent().getExtras().getParcelableArrayList("FlightDataList")
I doubt that you have implemented Parcable in FlightData
https://medium.com/techmacademy/how-to-implement-and-use-a-parcelable-class-in-android-part-1-28cca73fc2d1
It should work. The only thing that I am missing in your example is the constructor. It could explain the null your are getting.
Try adding this constructor for FlightData
public FlightData(Parcel in) {
x = in.readDouble();
y = in.readDouble();
time = in.readDouble();
}
did you try creating a datastructure that implements parcelable?
public class flightDataList implements Parcelable{
String dataThingyString;
int dataThingyInt;
public flightDataList(String dataThingyString, int dataThingyInt){
this.dataThingyString = dataThingyString;
this.dataThingyInt = dataThingyInt;
}
public flightDataList(Parcle in){
this.dataThingyString = in.readString();
this.dataThingyInt = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags){
dest.writeString(dataThingyString);
dest.writeInt(dataThingyInt);
}
public static final Creator<flightDataList> CREATOR = new Creator<flightDataList>(){
#Override
public flightDataList createFromParcel(Parcel source){
return new flightDataList(source);
}
#Override
public flightDataList[] newArray(int size){
return new flightDataList[size];
}
}
public void setdataThingyString(String stringData){
this.dataThingyString = stringData;
}
public void setdataThingyInt(int intData){
this.dataThingyInt = intData;
}
public String getdataThingyString(){
return dataThingyString;
}
public int getdataThingyInt(){
return dataThingyInt;
}
#Override
public int describeContents(){
return 0;
}
}

Parcelable list inside Parcelable class not reading back with Parcel.readTypedList

I have two Activities, A and B. I am trying to send object from Activity A, to Activity B. When in Activity A, I can see that my List contains two items, but when I retrieve it in Activity B, the List contains 7000000+ records.
Here is my Assessment class, that implements Parcelable, and contains an ArrayList<Photo> which should be parcelable as well.
Assessment POJO:
public class Assessment extends BaseObservable implements Parcelable {
public Assessment(){
}
#SerializedName("Vehicle")
private String vehicle;
#SerializedName("Photos")
private List<Photo> photos;
#Bindable
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
notifyPropertyChanged(BR.vehicle);
}
public List<Photo> getPhotos() {
return photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
protected Assessment(Parcel in) {
vehicle = in.readString();
photos = new ArrayList<Photo>();
in.readTypedList(photos, Photo.CREATOR);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(vehicle);
dest.writeTypedList(photos);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Assessment> CREATOR = new Parcelable.Creator<Assessment>() {
#Override
public Assessment createFromParcel(Parcel in) {
return new Assessment(in);
}
#Override
public Assessment[] newArray(int size) {
return new Assessment[size];
}
};
}
Photo POJO:
public class Photo implements Parcelable {
public Photo(){
}
#SerializedName("PhotoPath")
private String photoPath;
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
#SerializedName("Base64PhotoString")
private String photoBase64String;
public String getPhotoBase64String() {
return photoBase64String;
}
public void setPhotoBase64String(String photoBase64String) {
this.photoBase64String = photoBase64String;
}
protected Photo(Parcel in) {
photoPath = in.readString();
photoBase64String = in.readString();
}
//region parelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(photoPath);
dest.writeString(photoBase64String);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() {
#Override
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
#Override
public Photo[] newArray(int size) {
return new Photo[size];
}
};
//endregion
}
Here is how I send the object via Intent from Activity A, to Activity B:
public void OnAdapterItemClicked(View view){
Intent activityIntent = new Intent(this, com.example.andrewkp.gaassessing.DisplayAssessment.class);
Assessment extraAssessment = getAssessmentFromCollection(view); //extraAssessment.getPhotos().size() == 2
activityIntent.putExtra("assessment", extraAssessment);
startActivity(activityIntent);
}
And here is how I read the Parcelable object in Activity B:
assessment = getIntent().getExtras().getParcelable("assessment");
I have looked at the following article, and I follow exactly what they do, but my photos list does not persist through to Activity B:
When I debug the readTypedList method in Parcel class, I can see that it adds 7000000+ records to my ArrayList, but never removes them. Why is this behavior happening?
You are able to put up to 1MB of data in a Bundle encapsulated inside Intent.
You will get bunch of errors when sending PhotoBase64String in Bundle.
However, in order to overcome this issue, I would suggest path/URI of your photo to your second activity. Then in your second activity, read photo from that path, and perform your desired operation.

Java android ava.lang.RuntimeException: Parcelable encountered IOException writing serializable object

I want to in finish Activity with result put a List of objets I created a class which look like this :
public class Vals implements Serializable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
}
Next in activity (fragment) I did this when I finish my activity with result :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
intent.putExtras(conData);
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
intent.putExtra(ROW_BEAN_DATA, new Vals(rows));
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
And in console I have :
FATAL EXCEPTION: main
Process: com.maps, PID: 10222 java.lang.RuntimeException:
Parcelable encountered IOException writing serializable object (name = com.maps.Utils.Vals) at
android.os.Parcel.writeSerializable(Parcel.java:1316) at android.os.Parcel.writeValue(Parcel.java:1264) at android.os.Parcel.writeArrayMapInternal(Parcel.java:618) at android.os.Bundle.writeToParcel(Bundle.java:1692) at android.os.Parcel.writeBundle(Parcel.java:636) at android.content.Intent.writeToParcel(Intent.java:7582) at android.app.ActivityManagerProxy.finishActivity(ActivityManagerNative.java:2517)at android.app.Activity.finish(Activity.java:4324) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.finishWithResult(FragmentListOfAllObjetsToReportActivity.java:156) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.confirmChoose(FragmentListOfAllObjetsToReportActivity.java:160) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.access$200(FragmentListOfAllObjetsToReportActivity.java:34) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity$3.onClick(FragmentListOfAllObjetsToReportActivity.java:102) at android.view.View.performClick(View.java:4640)
This is onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 90:
if (resultCode == RESULT_OK) {
Bundle res = data.getExtras();
String result = res.getString("param_result");
int count = Integer.parseInt(result);
if (count != 1)
tvChooseObjects.setText("Wybrano " + count + " obiekty");
else
tvChooseObjects.setText("Wybrano " + count + " obiekt");
rowBeen = ((Vals) getIntent().getSerializableExtra(FragmentListOfAllObjetsToReportActivity.ROW_BEAN_DATA)).data;
Toast.makeText(getApplicationContext(), rowBeen.size() + " " , Toast.LENGTH_LONG).show();
}
break;
}
Try replacing Serializable implementation with Parcelable in Vals & RawBean classes
Replace getSerializableExtra with getParcelableExtra in *onActivityResult**
Vals.java
public class Vals implements Serializable, Parcelable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
protected Vals(Parcel in) {
if (in.readByte() == 0x01) {
data = new ArrayList<RowBean>();
in.readList(data, RowBean.class.getClassLoader());
} else {
data = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (data == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(data);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Vals> CREATOR = new Parcelable.Creator<Vals>() {
#Override
public Vals createFromParcel(Parcel in) {
return new Vals(in);
}
#Override
public Vals[] newArray(int size) {
return new Vals[size];
}
};
}
RawBean.java
public class RowBean implements Serializable, Parcelable {
public String title;
public boolean selected;
public RowBean(){
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public RowBean(boolean selected, String title) {
this.selected = selected;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
protected RowBean(Parcel in) {
title = in.readString();
selected = in.readByte() != 0x00;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeByte((byte) (selected ? 0x01 : 0x00));
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<RowBean> CREATOR = new Parcelable.Creator<RowBean>() {
#Override
public RowBean createFromParcel(Parcel in) {
return new RowBean(in);
}
#Override
public RowBean[] newArray(int size) {
return new RowBean[size];
}
};
}
Check out This example
public class Vals implements Serializable {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Vals(int id, String name) {
this.id = id;
this.name = name;
}
}
Add DataWraperClass
public class DataWrapper implements Serializable {
private ArrayList<Vals > mServicesList;
public DataWrapper(ArrayList<Vals > data) {
this.mServicesList = data;
}
public ArrayList<Vals > getServicesList() {
return this.mServicesList;
}
}
Create Intent Like This
DataWrapper mServiceListData = new DataWrapper(yourarraylist);
mIntent = new Intent(KitVerfiyActivity.this, BeneficiaryDetailsActivity.class);
mIntent.putExtra("arr_list", mServiceListData);
startActivity(mIntent);
get arraylist from Intent like this
DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("arr_list");
mArrayCaseFullList = dw.getServicesList();
Hope this will help you
Use Below method :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
conData.putSerializable(ROW_BEAN_DATA, new Vals(rows));
intent.putExtras(conData);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
Retrieve your data like below code :
Bundle bundle = getIntent().getExtras();
rowBeen = ((Vals) bundle.getSerializable(ROW_BEAN_DATA);

Passing an ArrayList of other Arrays to an Activity

I have an arraylist of custom objects that extend the Parecelable class and can thus be sent to an Activity through a bundle or through a localbroadcast manager.
Now, my problem arises when i try to send an arraylist of other arrays i.e ArrayList<ArrayList<my_custom_object>>. How can i achieve this?
1.Custom parcelable class (replacing with your custom parcelable class):
import android.os.Parcel;
import android.os.Parcelable;
/**
* Custom parcelable class
*/
public class MyParcelable implements Parcelable {
public int data;
public MyParcelable(int data) {
this.data = data;
}
private MyParcelable(Parcel source) {
// Reading custom data
data = source.readInt();
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
#Override
public MyParcelable createFromParcel(Parcel source) {
return new MyParcelable(source);
}
#Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// Saving custom data
dest.writeInt(data);
}
}
2.Implement a Parcelable class which extends ArrayList.
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* ArrayList of the custom parcelable object
*/
public class MyParcelableList extends ArrayList<MyParcelable> implements Parcelable {
public MyParcelableList() {
}
private MyParcelableList(Parcel source) {
for (Parcelable p : source.readParcelableArray(MyParcelable.class.getClassLoader()))
add((MyParcelable) p);
}
public static final Parcelable.Creator<MyParcelableList> CREATOR
= new Parcelable.Creator<MyParcelableList>() {
#Override
public MyParcelableList createFromParcel(Parcel source) {
return new MyParcelableList(source);
}
#Override
public MyParcelableList[] newArray(int size) {
return new MyParcelableList[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelableArray(toArray(new MyParcelable[size()]), flags);
}
}
3.Passing Intent to TargetActivity.
// Preparing data ...
MyParcelableList list1 = new MyParcelableList();
list1.add(new MyParcelable(1));
MyParcelableList list2 = new MyParcelableList();
list2.add(new MyParcelable(2));
list2.add(new MyParcelable(3));
ArrayList<MyParcelableList> listOfList = new ArrayList<>();
listOfList.add(list1);
listOfList.add(list2);
// Send intent to your target activity
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("KEY_OF_EXTRA", listOfList);
context.startActivity(new Intent(context, TargetActivity.class).putExtras(bundle));
4.Retrieve data at TargetActivity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// processing intent data
if (getIntent()!=null) {
Bundle bundle = getIntent().getExtras();
if (bundle.containsKey("KEY_OF_EXTRA")) {
ArrayList<MyParcelableList> listOfList = bundle.getParcelableArrayList("KEY_OF_EXTRA");
if (listOfList != null)
// Do something here ...
for (MyParcelableList list : listOfList) {
for (MyParcelable p : list) {
Log.v("TargetActivity", "p.data=" + p.data);
}
}
}
}
}
You can try the following code
ActivityA send:
ArrayList<ArrayList<CustomClass>>data = new ArrayList<ArrayList<CustomClass>>();
ArrayList<CustomClass>d1 = new ArrayList<CustomClass>();
CustomClass temp = new CustomClass("this is my object");
d1.add(temp);
data.add(d1);
Intent intent = new Intent(JumpToMainActivity.ACTION);
intent.putExtra("data",data);
startActivity(intent);
ActivityB get:
Intent intent = getIntent();
ArrayList<ArrayList<CustomClass>>data = (ArrayList<ArrayList<CustomClass>>) intent.getSerializableExtra("data");
ArrayList<CustomClass>d1 = data.get(0);
System.out.println("received:" + d1.get(0).result);
CusstonClass.java:
/**
* Created by obo on 15/10/23.
*/
public class CustomClass implements Parcelable {
public String result = "this is my object";
public CustomClass(String result){this.result = result;};
protected CustomClass(Parcel in) {
result = in.readString();
}
public static final Creator<CustomClass> CREATOR = new Creator<CustomClass>() {
#Override
public CustomClass createFromParcel(Parcel in) {
return new CustomClass(in);
}
#Override
public CustomClass[] newArray(int size) {
return new CustomClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(result);
}
}
Hope to help you

Categories