When I put an object into a bundle so I can transfer it to another Activity, changing the value of the attribute IdEscritorio occurs.
In my LoginActivity IdEscritorio the value of = 1, when I get in my Main Activity is it with the value of 7.
LogCat
LoginActivity Method
private void IniciarMainActivity(Usuario usuarioAutenticado)
{
//Iniciar Activity Main
Intent i = new Intent(LoginActivity.this, MainActivity.class);
Bundle b = new Bundle();
b.putParcelable("usuarioAutenticado", usuarioAutenticado);
Log.d(TAG, "IdEscritorio: " + String.valueOf(usuarioAutenticado.getIdEscritorio()));
i.putExtras(b);
startActivity(i);
}
MainActivity onCreate()
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Widgets
InicializeComponents();
//Listeners Events
Listeners();
//Recuperar os valores de usuario autenticado enviado da activity Login
_usuarioAutenticado = new Usuario();
Bundle bundle = getIntent().getExtras();
if(bundle != null)
_usuarioAutenticado = bundle.getParcelable("usuarioAutenticado");
Log.d(TAG, "IdEscritorio: " + String.valueOf(_usuarioAutenticado.getIdEscritorio()));
}
Class Usuario
public class Usuario implements Parcelable {
private int Id;
private int IdEscritorio;
private String Nome;
private String Login;
private String Senha;
/**
* Construtores
*/
public Usuario()
{
super();
}
public Usuario(Parcel parcel)
{
this();
this.Id = parcel.readInt();
this.IdEscritorio = parcel.readInt();
this.Nome = parcel.readString();
this.Login = parcel.readString();
this.Senha = parcel.readString();
}
/**
* Propriedades
*/
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
public int getIdEscritorio() {
return IdEscritorio;
}
public void setIdEscritorio(int idEscritorio) {
IdEscritorio = idEscritorio;
}
public String getNome() {
return Nome;
}
public void setNome(String nome) {
Nome = nome;
}
public String getLogin() {
return Login;
}
public void setLogin(String login) {
Login = login;
}
public String getSenha() {
return Senha;
}
public void setSenha(String senha) {
Senha = senha;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(getId());
out.writeString(getNome());
}
public static final Parcelable.Creator<Usuario> CREATOR = new Parcelable.Creator<Usuario>(){
#Override
public Usuario createFromParcel(Parcel in){
return new Usuario(in);
}
#Override
public Usuario[] newArray(int size) {
return new Usuario[size];
}
};
}
The problem is with your Parcelable class. In your writeToParcel class, you are writing only Id and Nome to the Parcel.
#Override
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(getId());
out.writeString(getNome());
}
However, you are reading all 5 fields when creating the object in Usuario(Parcel parcel).
For this to work correctly, change your writeToParcel method to:
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(getId());
out.writeInt(getIdEscritorio());
out.writeString(getNome());
out.writeString(getLogin());
out.writeString(getSenha());
}
Related
I will try to be brief and precise:
I have a user object that contains a chat, and this is updated every time I receive a message:
public class Usuarios implements Serializable {
private static final long serialVersionUID = 1113799434508676095L;
private int id;
private String nombre;
private String ip;
private boolean isSInicial;
//HERE WILL GO THE VARIABLE THAT STORMS THE CHAT, BUT I DO NOT KNOW HOW TO IMPLEMENT IT
public Usuarios(int id, String nombre, String ip, boolean isSInicial){
this.id = id;
this.nombre = nombre;
this.ip = ip;
this.isSInicial = isSInicial;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public boolean isSInicial() {
return isSInicial;
}
public void setSInicial(boolean SInicial) {
isSInicial = SInicial;
}}
I have an activity, that by clicking on a list, loads a new activity for the specific user:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
Usuarios e = (Usuarios) listview.getItemAtPosition(pos);
Intent visorDetalles = new Intent(view.getContext(),Chat.class);
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("indice", Contactos.listaDeContactos.indexOf(e));
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
}
});
I need the EditText that contains the Intent to be updated automatically every time I click on a user of a ListView.
I do not know what kind of variable I should use in the user object and how to implement it.
In your Usuarios class add the variable:
public ArrayList<String> currentChat;
Instead of passing the index, pass the Object himself maybe.
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("usuario",e);
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
And in your onCreate Chat Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
Usuario usuario = (Usuario) intent.getSerializableExtra("usuario");
EditText myEditText = (EditText)findViewById(R.id.myEditText1));
String allChat;
for(String chatLine : usuario.currentChat) {
allChat += chatLine + '\n';
}
myEditText.setText(allChat);
Did I got your problem right ?
I'm trying to send an object of this class to another activity. I used parcelabler.com to generate the code. The problem is when i declare the intent, Eclispse says that the method putExtra(String, GrupoMuscular) is undefined for the type Intent. Do i have a wrong parcelable implementation?
public class GrupoMuscular implements Parcelable {
private int id;
private static int id_aux = 0;
private String nome;
private int imagem;
private ArrayList<Exercicio> exercicios;
public GrupoMuscular(String nome, int img) {
//super();
id = id_aux;
id_aux++;
this.nome = nome;
this.imagem = img;
this.exercicios = new ArrayList<Exercicio>();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getImagem() {
return imagem;
}
public void setImagem(int imagem) {
this.imagem = imagem;
}
public ArrayList<Exercicio> getGruposMuscular() {
return exercicios;
}
public void addExercicio(int id, String nome, String descricao, int imagem){
Exercicio ex = new Exercicio(id, nome, descricao, imagem);
exercicios.add(ex);
}
public void setGruposMuscular(ArrayList<Exercicio> gruposMuscular) {
this.exercicios = gruposMuscular;
}
public ArrayList<Exercicio> getExercicios() {
return exercicios;
}
public void setExercicios(ArrayList<Exercicio> exercicios) {
this.exercicios = exercicios;
}
public int getId() {
return id;
protected GrupoMuscular(Parcel in) {
id = in.readInt();
nome = in.readString();
imagem = in.readInt();
if (in.readByte() == 0x01) {
exercicios = new ArrayList<Exercicio>();
in.readList(exercicios, Exercicio.class.getClassLoader());
} else {
exercicios = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(nome);
dest.writeInt(imagem);
if (exercicios == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(exercicios);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<GrupoMuscular> CREATOR = new Parcelable.Creator<GrupoMuscular>() {
#Override
public GrupoMuscular createFromParcel(Parcel in) {
return new GrupoMuscular(in);
}
#Override
public GrupoMuscular[] newArray(int size) {
return new GrupoMuscular[size];
}
};
}
Activity Intent:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent;
intent = new Intent(ExerciciosActivity.this, ListaExerciciosActivity.class);
intent.putExtra("musculos", gruposMusculares.get(position));
startActivity(intent);
}});
}
Try Passing the Object as a Parcelable Extra on the Intent.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,android.os.Parcelable)
Since you are only passing a single instance of this Object.
// Create a new Intent
Intent myNewIntent = new Intent(this, NextActivity.class);
myNewIntent.putExtra("musculos", groupMusculares.get(position));
startActivity(myNewIntent);
Then in your NextActivity.class:
use
http://developer.android.com/reference/android/content/Intent.html#getParcelableExtra(java.lang.String)
// Class Member variable
GrupoMuscular mMuscleGroup;
// inside onCreate
Bundle extras = getIntent().getExtras();
// If the extras are not null
if(extras != null){
mMuscleGroup = extras.getParcelableExtra("musculos");
// if its not null do something with it
if(mMuscleGroup != null){
// Perform some logic
// ...
}
}
I have a Activity A which has a ArrayList of object which i parceable..
Object is :
public class DashBoardPOJO implements Parcelable {
private String dashBoardName;
private String dashBoardId;
private String dashBoardStatus;
private ArrayList<DashBoardDataPOJO> dashBoardDataList;
private boolean loaded;
public ArrayList<DashBoardDataPOJO> getDashBoardDataList() {
return dashBoardDataList;
}
public void setDashBoardDataList(
ArrayList<DashBoardDataPOJO> dashBoardDataList) {
this.dashBoardDataList = dashBoardDataList;
}
public boolean isLoaded() {
return loaded;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public String getDashBoardStatus() {
return dashBoardStatus;
}
public void setDashBoardStatus(String dashBoardStatus) {
this.dashBoardStatus = dashBoardStatus;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dashBoardName);
dest.writeString(dashBoardId);
dest.writeList(dashBoardDataList);
}
public static final Parcelable.Creator<DashBoardPOJO> CREATOR = new Parcelable.Creator<DashBoardPOJO>() {
public DashBoardPOJO createFromParcel(Parcel in) {
return new DashBoardPOJO(in);
}
public DashBoardPOJO[] newArray(int size) {
return new DashBoardPOJO[size];
}
};
public DashBoardPOJO() {
dashBoardName = null;
dashBoardId = null;
dashBoardDataList = null;
/*
* userName=null; userId=null;
*/
}
private DashBoardPOJO(Parcel in) {
dashBoardName = in.readString();
dashBoardId = in.readString();
in.readList(dashBoardDataList, null);
}
// GETTERS AND SETTERS............
public String getDashBoardName() {
return dashBoardName;
}
public void setDashBoardName(String dashBoardName) {
this.dashBoardName = dashBoardName;
}
public String getDashBoardId() {
return dashBoardId;
}
public void setDashBoardId(String dashBoardId) {
this.dashBoardId = dashBoardId;
}
}
I want to pass the ArrayList to a activity which extends Fragment Activity.
I am sending the object like this
Intent intent = new Intent(
DashboardActivity.this,
BaseFragmentActivity.class);
intent.putParcelableArrayListExtra("dashBoardList", dashBoardList);
startActivity(intent);
And receiving it at the fragment activity like this
dashboardList = getIntent().getExtras().getParcelableArrayList("dashBoardList");
But still the intent is returninig me a null value... Pls help...
Try this:
private DashBoardPOJO(Parcel in) {
dashBoardName = in.readString();
dashBoardId = in.readString();
dashBoardDataList = (ArrayList<DashBoardDataPOJO>) in.readArrayList(DashBoardDataPOJO.class.getClassLoader());
}
I am currently trying to pass a parceablearraylist from mylogin activity to my main activity but getting a
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.muuves.introround/com.muuves.introround.activities.MainActivity}: java.lang.RuntimeException: Parcel android.os.Parcel#41ef90a8: Unmarshalling unknown type code 7536741 at offset 684
Here are my parceable objects
public class Challenge implements Parcelable {
private Integer id;
private Integer challenger_id;
private Integer friend_id;
private String artist_name;
private String song_name;
private String image_url;
private String song_url;
private String answer_url;
private int challenge_attempts_left;
private int answer;
private Person person;
private Person friend;
public Challenge() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getChallenger_id() {
return challenger_id;
}
public void setChallenger_id(Integer challenger_id) {
this.challenger_id = challenger_id;
}
public Integer getFriend_id() {
return friend_id;
}
public void setFriend_id(Integer friend_id) {
this.friend_id = friend_id;
}
public String getArtist_name() {
return artist_name;
}
public void setArtist_name(String artist_name) {
this.artist_name = artist_name;
}
public String getSong_name() {
return song_name;
}
public void setSong_name(String song_name) {
this.song_name = song_name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getSong_url() {
return song_url;
}
public void setSong_url(String song_url) {
this.song_url = song_url;
}
public String getAnswer_url() {
return answer_url;
}
public void setAnswer_url(String answer_url) {
this.answer_url = answer_url;
}
public int getChallenge_attempts_left() {
return challenge_attempts_left;
}
public void setChallenge_attempts_left(int challenge_attempts_left) {
this.challenge_attempts_left = challenge_attempts_left;
}
public int getAnswer() {
return answer;
}
public void setAnswer(int answer) {
this.answer = answer;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Person getFriend() {
return friend;
}
public void setFriend(Person friend) {
this.friend = friend;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(challenger_id);
dest.writeInt(friend_id);
dest.writeString(artist_name);
dest.writeString(image_url);
dest.writeString(song_url);
dest.writeString(answer_url);
dest.writeInt(challenge_attempts_left);
dest.writeInt(answer);
dest.writeParcelable(person, flags);
dest.writeParcelable(friend, flags);
}
public static final Parcelable.Creator<Challenge> CREATOR = new Parcelable.Creator<Challenge>() {
#Override
public Challenge createFromParcel(Parcel in) {
Challenge challenge = new Challenge();
challenge.setId(in.readInt());
challenge.setChallenger_id(in.readInt());
challenge.setFriend_id(in.readInt());
challenge.setArtist_name(in.readString());
challenge.setSong_name(in.readString());
challenge.setImage_url(in.readString());
challenge.setSong_url(in.readString());
challenge.setAnswer_url(in.readString());
challenge.setChallenge_attempts_left(in.readInt());
challenge.setAnswer(in.readInt());
challenge.setPerson((Person) in.readParcelable(Person.class.getClassLoader()));
challenge.setFriend((Person) in.readParcelable(Person.class.getClassLoader()));
return challenge;
}
#Override
public Challenge[] newArray(int size) {
return new Challenge[size];
}
};
}
public class Person implements Parcelable {
private int id;
private String first_name;
private String last_name;
private String image_url;
public Person(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirst_Name() {
return first_name;
}
public void setFirst_Name(String first_name) {
this.first_name = first_name;
}
public String getLast_Name() {
return last_name;
}
public void setLast_Name(String last_name) {
this.last_name = last_name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(first_name);
dest.writeString(last_name);
dest.writeString(image_url);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
Person person = new Person();
person.setId(in.readInt());
person.setFirst_Name(in.readString());
person.setLast_Name(in.readString());
person.setImage_url(in.readString());
return person;
}
#Override
public Person[] newArray(int size) {
return null;
}
};
}
Login activity
#Override
public void preLoadDetails(Details details) {
Intent intent = new Intent(this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("receive", details.getReceive());
intent.putExtras(bundle);
startActivity(intent);
}
MainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
ArrayList<Challenge> friends = bundle.getParcelableArrayList("receive");
mContent = new MainFragment(0);
mContent.setArguments(getIntent().getExtras());
// set the Above View
setContentView(R.layout.home_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new MenuFragment()).commit();
// Disable
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
}
Been trying to fix it for the pass day and getting no where all I know is that person parceable object in the challenge object are always null but they are not when I put them in the bundle.
Appreciate any input.
Those Integer type could be null or an int, you need to handle that situation properly.
For example I have utility functions like this :
static public Integer readInteger(Parcel in){
if(in.readInt() == 1){
return in.readInt();
}else{
return null;
}
}
static public void writeInteger(Integer value, Parcel out){
if(value != null){
out.writeInt(1);
out.writeInt(value);
}else{
out.writeInt(0);
}
}
First thing in the class Challenge you use Integer attributes and you parce "int" those are 2 diferents things.
Exemple of how i do things myself :
public Podcast(Parcel parcel) {
id = parcel.readLong();
title = parcel.readString();
subtitle = parcel.readString();
summary = parcel.readString();
duration = parcel.readString();
author = parcel.readString();
date = parcel.readString();
mp3 = parcel.readString();
podcastCategoryId = parcel.readLong();
}
#Override
public int describeContents() {
// not used
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(title);
dest.writeString(subtitle);
dest.writeString(summary);
dest.writeString(duration);
dest.writeString(author);
dest.writeString(date);
dest.writeString(mp3);
dest.writeLong(podcastCategoryId);
}
public static Creator<Podcast> CREATOR = new Creator<Podcast>() {
public Podcast createFromParcel(Parcel parcel) {
return new Podcast(parcel);
}
public Podcast[] newArray(int size) {
return new Podcast[size];
}
};
#Override
public Person[] newArray(int size) {
return null;
}
You should create there an array of that size and return it.
#Override
public Person[] newArray(int size) {
return new Person[size];
}
Solved it was actually very simple, forgot song url when i was writing to the parcel. Any when i missed that write that was why i was getting the weird exception for person object. it was expecting a person object but was getting something else. 1 day wasted oh well :(
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(challenger_id);
dest.writeInt(friend_id);
dest.writeString(artist_name);
**dest.writeString(song_name);**
dest.writeString(image_url);
dest.writeString(song_url);
dest.writeString(answer_url);
dest.writeInt(challenge_attempts_left);
dest.writeInt(answer);
dest.writeParcelable(person, flags);
dest.writeParcelable(friend, flags);
}
I am transferring an object from one activity to another using parcelable, but it showing null
as retrieving that object in another activity.
any suggestions?
Here's the code :
public class TPackage implements Parcelable {
// private static final long serialVersionUID = 1L;
private int cost;
private String name;
private int totalChannels;
private HashMap<String, Channel> channelList;
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public int getTotal_channels() {
return totalChannels;
}
public void setTotal_channels(int total_channels) {
this.totalChannels = total_channels;
}
public HashMap<String, Channel> getList() {
return channelList;
}
public void setList(HashMap<String, Channel> list) {
this.channelList = list;
}
public void put(String name, Channel c) {
channelList.put(name, c);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
}
public static final Parcelable.Creator<TPackage> CREATOR = new Parcelable.Creator<TPackage>() {
public TPackage createFromParcel(Parcel in) {
return new TPackage();
}
public TPackage[] newArray(int size) {
return new TPackage[size];
}
};
}
This is the right way to transfer your object using parcel andorid
public class TPackage implements Parcelable {
// private static final long serialVersionUID = 1L;
private int cost;
private String name;
private int totalChannels;
private HashMap<String, Channel> channelList;
public TPackage(int cost, String name, int totalChannels,
HashMap<String, Channel> channelList){
this.cost = cost;
this.name = name;
this.totalChannels = totalChannels;
this.channelList = channelList;
}
public TPackage(Parcel in){
//same order as that in writeToParcel()
cost = in.readInt();
name = in.readString();
totalChannels = in.readInt();
Bundle bundle = in.readBundle();
channelList = (HashMap<String, Channel>) bundle.getSerializable("channelList");
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public int getTotal_channels() {
return totalChannels;
}
public void setTotal_channels(int total_channels) {
this.totalChannels = total_channels;
}
public HashMap<String, Channel> getList() {
return channelList;
}
public void setList(HashMap<String, Channel> list) {
this.channelList = list;
}
public void put(String name, Channel c) {
channelList.put(name, c);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(cost);
dest.writeString(name);
dest.writeInt(totalChannels);
//easiest way to transfer HashMap via parcel
Bundle bundle = new Bundle();
bundle.putSerializable("channelList", channelList);
dest.writeBundle(bundle);
}
public static final Parcelable.Creator<TPackage> CREATOR = new Parcelable.Creator<TPackage>() {
public TPackage createFromParcel(Parcel in) {
return new TPackage(in);
}
public TPackage[] newArray(int size) {
return new TPackage[size];
}
};
}
[EDITED]
This is the sender activity
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TPackage tPackage = new TPackage(10, "hello", 123, new HashMap<String, Channel>());
Intent intent = new Intent(this, NActivity.class);
intent.putExtra("parcel", tPackage);
startActivity(intent);
}
}
This is the receiver activity
public class NActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
TPackage tPackage = intent.getParcelableExtra("parcel");
HashMap<String, Channel> hashMap = tPackage.getList();
Log.d("MyTag", "cost : " + tPackage.getCost() + " name: " + tPackage.getName()
+ " total channels: " + tPackage.getTotal_channels() + " list count: " + hashMap.size());
}
}
Logcat output
09-13 21:57:20.578: DEBUG/MyTag(1478): cost : 10 name: hello total channels: 123 list count: 0
You may need to actually put something in the createFromParcel and in writeToParcel (like the content of the object)