Pass List with custom object to another activity android - java

I have a List<News> new ArrayList<News>(); I need to pass this list to another activity and retrieve object from it to assign it to String values.
News.java
public class News
{
String title;
String description;
String thumbnail;
String newsUrl;
String body;
String newsBigImage ;
String newsComments ;
String newsViews;
String publishedDate;
String articleGuid;
String newsSourceId;
String newsId ;
String publisherName;
String newsSourceTitle;
String color;
News(String title, String description, String thumbnail, String newsUrl, String body, String newsBigImage, String newsComments, String newsViews,
String publishedDate,
String articleGuid,
String newsSourceId,
String newsId ,
String publisherName,
String newsSourceTitle )
{
this.title = title;
this.description = description;
this.articleGuid =articleGuid;
this.thumbnail = thumbnail;
this.newsUrl = newsUrl;
this.body = body;
this.newsBigImage = newsBigImage;
this.newsComments = newsComments;
this.newsViews = newsViews;
this.publishedDate = publishedDate;
this.newsId = newsId;
this.newsSourceId = newsSourceId;
this.publisherName = publisherName;
//this.color = color;
this.newsSourceTitle =newsSourceTitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getNewsUrl() {
return newsUrl;
}
public void setNewsUrl(String newsUrl) {
this.newsUrl = newsUrl;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getNewsBigImage() {
return newsBigImage;
}
public void setNewsBigImage(String newsBigImage) {
this.newsBigImage = newsBigImage;
}
public String getNewsComments() {
return newsComments;
}
public void setNewsComments(String newsComments) {
this.newsComments = newsComments;
}
public String getNewsViews() {
return newsViews;
}
public void setNewsViews(String newsViews) {
this.newsViews = newsViews;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
public String getArticleGuid() {
return articleGuid;
}
public void setArticleGuid(String articleGuid) {
this.articleGuid = articleGuid;
}
public String getNewsSourceId() {
return newsSourceId;
}
public void setNewsSourceId(String newsSourceId) {
this.newsSourceId = newsSourceId;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getPublisherName() {
return publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public String getNewsSourceTitle() {
return newsSourceTitle;
}
public void setNewsSourceTitle(String newsSourceTitle) {
this.newsSourceTitle = newsSourceTitle;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
I pass values like:-
myNewsList.add(new News(title, description, thumbnail, newsUrl, body, newsBigImage, newsComments, newsViews, publishedDate, articleGuid, newsSourceId, newsId, publisherName, newsSourceTitle));
Then I pass this list to an ListAdapter to show it in a ListView.
itemsAdapter = new LazyAdapter(myContext, myNewsList);
newsList.setAdapter(itemsAdapter);
Now, When the user clicks a listview item, I want to pass the myNewsList to the new activity and retrieve items from it and assign it to another Strings in that class.
ewsList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(myContext).show(getActivity(), "Fetching news..", "Just a moment");
//News myMap = myNewsList.get(position);
Intent newsIntent = new Intent(getActivity(),NewsDetails.class);
startActivity(newsIntent);
How can I do this??

implements a parcelable interface so your class will look like
public class News implements Parcelable {
String title;
String description;
String thumbnail;
String newsUrl;
String body;
String newsBigImage ;
String newsComments ;
String newsViews;
String publishedDate;
String articleGuid;
String newsSourceId;
String newsId ;
String publisherName;
String newsSourceTitle;
String color;
protected News(Parcel in) {
title = in.readString();
description = in.readString();
thumbnail = in.readString();
newsUrl = in.readString();
body = in.readString();
newsBigImage = in.readString();
newsComments = in.readString();
newsViews = in.readString();
publishedDate = in.readString();
articleGuid = in.readString();
newsSourceId = in.readString();
newsId = in.readString();
publisherName = in.readString();
newsSourceTitle = in.readString();
color = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeString(thumbnail);
dest.writeString(newsUrl);
dest.writeString(body);
dest.writeString(newsBigImage);
dest.writeString(newsComments);
dest.writeString(newsViews);
dest.writeString(publishedDate);
dest.writeString(articleGuid);
dest.writeString(newsSourceId);
dest.writeString(newsId);
dest.writeString(publisherName);
dest.writeString(newsSourceTitle);
dest.writeString(color);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
#Override
public News createFromParcel(Parcel in) {
return new News(in);
}
#Override
public News[] newArray(int size) {
return new News[size];
}
};
}
and you can pass now this in intent extra like
intent.putExtra("newsObject", obj);
and for passing arraylist do Intent.putParcelableArrayListExtra("newsList", arr);
and in next activity get like
News news = (News)intent.getParcelableExtra("newsObject");
and for getting arraylist do
ArrayList<News> news = (ArrayList<News>)intent.getParcelableArrayListExtra("newsList");

Use Seriazable or Parceable interface implementation for this.

In NewsDetails class just you want to show the description so call getters method of model class and show there, or else follow above solution

first, create a getter method to retreive your object in adapter.. returning your List then you call your getter in your activity, then you create your intent.

Related

How to pass raw data in API request using Retrofit2 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
#FormUrlEncoded
#POST("/api/login/{mobile}")
Call<ResObj> userLogin( #Field("phoneNumber") String mobile );
And the API implementation
private void doLogin(final String mobile){
Call<ResObj> call = userService.login(mobile);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body(); // here i am getting null response.body()
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ResObj class:
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to know what causes the error and what are possible solutions.
UPDATE
POSTMAN
You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body();
if(resObj != null){ // checking object is not null
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}else{
// handle null response here.
}
}
Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getContactPerson ()
{
return contactPerson;
}
public void setContactPerson (String contactPerson)
{
this.contactPerson = contactPerson;
}
public String getTimeOut ()
{
return timeOut;
}
public void setTimeOut (String timeOut)
{
this.timeOut = timeOut;
}
public String getProblem ()
{
return problem;
}
public void setProblem (String problem)
{
this.problem = problem;
}
public String getSrNo ()
{
return srNo;
}
public void setSrNo (String srNo)
{
this.srNo = srNo;
}
public String getFieldEngineer ()
{
return fieldEngineer;
}
public void setFieldEngineer (String fieldEngineer)
{
this.fieldEngineer = fieldEngineer;
}
public String getJoNo ()
{
return joNo;
}
public void setJoNo (String joNo)
{
this.joNo = joNo;
}
public String getIrNo ()
{
return irNo;
}
public void setIrNo (String irNo)
{
this.irNo = irNo;
}
public String getDesignation ()
{
return designation;
}
public void setDesignation (String designation)
{
this.designation = designation;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getTimeIn ()
{
return timeIn;
}
public void setTimeIn (String timeIn)
{
this.timeIn = timeIn;
}
public String getProductType ()
{
return productType;
}
public void setProductType (String productType)
{
this.productType = productType;
}
public boolean getStatus ()
{
return status;
}
public void setStatus (boolean status)
{
this.status = status;
}
public String getContactNo ()
{
return contactNo;
}
public void setContactNo (String contactNo)
{
this.contactNo = contactNo;
}
}
You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
#Headers("Content-Type: application/json")
#POST("/api/login")
Call<ResObj> userLogin(#Body JsonObject jsonObject);
And call your API like this
private void doLogin(final String mobile){
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResObj> call = userService.login(paramObject);
call.enqueue(new Callback<ResObj>() {
//your rest of code
});
}
UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable
public class ResObj implements Parcelable {
// ...........your previous code here
// just simply add the following methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(date);
dest.writeString(address);
dest.writeString(accountName);
dest.writeString(contactPerson);
dest.writeString(timeOut);
dest.writeString(problem);
dest.writeString(srNo);
dest.writeString(fieldEngineer);
dest.writeString(joNo);
dest.writeString(irNo);
dest.writeString(designation);
dest.writeString(email);
dest.writeString(timeIn);
dest.writeString(productType);
dest.writeByte((byte) (status ? 1 : 0));
dest.writeString(contactNo);
}
public static final Parcelable.Creator<ResObj> CREATOR
= new Parcelable.Creator<ResObj>() {
public ResObj createFromParcel(Parcel in) {
return new ResObj(in);
}
public ResObj[] newArray(int size) {
return new ResObj[size];
}
};
protected ResObj(Parcel in) {
date = in.readString();
address = in.readString();
accountName = in.readString();
contactPerson = in.readString();
timeOut = in.readString();
problem = in.readString();
srNo = in.readString();
fieldEngineer = in.readString();
joNo = in.readString();
irNo = in.readString();
designation = in.readString();
email = in.readString();
timeIn = in.readString();
productType = in.readString();
status = in.readByte() != 0;
contactNo = in.readString();
}
}
Now pass your object via intent like the following.
if(resObj != null){
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
Get data from your ListActivity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.
// Now you can use your data like that
yourEditText.setText(yourObject.getEmail());
}

update query not working?

I have the following Dao class:
#Dao
public interface AchievementDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertIntoDatabase(AchievementModel... achievementModel);
#Query("SELECT * FROM achievements WHERE game = :game")
AchievementModel[] getAchievementDataForGame(String game);
#Query("UPDATE achievements SET pointsAchieved = pointsAchieved + :points WHERE achievementKey = :achievementKey")
void updatePointsForKey(double points, String achievementKey);
#Query("SELECT * FROM achievements WHERE achievementKey LIKE :achievementKey")
AchievementModel getAchievementForKey(String achievementKey);
}
and the following model class:
#Entity(tableName = "achievements", indices = {#Index(value = {"achievementKey"}, unique = true)})
public class AchievementModel {
#PrimaryKey #NonNull
private String achievementKey;
private String title;
private String description;
private double pointsAchieved;
private int imageId;
private int viewType;
private String game;
public AchievementModel(#NonNull String achievementKey, String title, String description,
double pointsAchieved, int imageId, int viewType, String game) {
this.achievementKey = achievementKey;
this.title = title;
this.description = description;
this.pointsAchieved = pointsAchieved;
this.imageId = imageId;
this.viewType = viewType;
this.game = game;
}
#NonNull
public String getAchievementKey() {
return achievementKey;
}
public void setAchievementKey(#NonNull String achievementKey) {
this.achievementKey = achievementKey;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPointsAchieved() {
return pointsAchieved;
}
public void setPointsAchieved(double pointsAchieved) {
this.pointsAchieved = pointsAchieved;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getGame() {
return game;
}
public void setGame(String game) {
this.game = game;
}
}
The first 2 queries in the DAO class are working absolutely fine whereas the last 2 queries updatePointsForKey and getAchievementForKey are not working. They are being called correctly from a background thread. Please help. Do tell me if more information is required about the question.
The update query maybe returns an int instead of void ... What do you think ?

Storing an arraylist of custom objects (which have Strings, Dates, Lists, and more as fields) in shared preferences

I am trying to save an arraylist of clients in shared preferences, however I am getting out of memory error. I am new to this and can't figure out how to do this? I looked at a lot of pages on stackoverflow, but couldn't find one that would work for me or that also had an ArrayList of custom objects, where every object contains more ArrayLists with custom objects.
client object:
public class Client implements Serializable, Comparable<Client> {
private int clientID;
private String name;
private String phone;
private String email;
private String url;
private Double turnover;
private String visitAddress;
private String visitCity;
private String visitZipcode;
private String visitCountry;
private String postalAddress;
private String postalCity;
private String postalZipcode;
private String postalCountry;
private Drawable clientImage;
private List<Contact> contactList = new ArrayList<Contact>();
private List<Project> projectList = new ArrayList<Project>();
private List<Task> taskList = new ArrayList<Task>();
private List<Order> orderList = new ArrayList<Order>();
public Client(int clientID, String Name, String Phone, String Email, String URL, Double Turnover,
String VisitAddress, String VisitCity, String VisitZipcode, String VisitCountry,
String PostalAddress, String PostalCity, String PostalZipcode, String PostalCountry,
List contactList, List projectList, List taskList, List orderList){
super();
this.clientID = clientID;
this.name = Name;
this.phone = Phone;
this.email = Email;
this.url = URL;
this.turnover = Turnover;
this.visitAddress = VisitAddress;
this.visitCity = VisitCity;
this.visitZipcode = VisitZipcode;
this.visitCountry = VisitCountry;
this.postalAddress = PostalAddress;
this.postalCity = PostalCity;
this.postalZipcode = PostalZipcode;
this.postalCountry = PostalCountry;
this.contactList = contactList;
this.projectList = projectList;
this.taskList = taskList;
this.orderList = orderList;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
public String getUrl() {
return url;
}
public Double getTurnover() {
return turnover;
}
public String getVisitAddress() {
return visitAddress;
}
public String getVisitCity() {
return visitCity;
}
public String getVisitZipcode() {
return visitZipcode;
}
public String getVisitCountry() {
return visitCountry;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalCity() {
return postalCity;
}
public String getPostalZipcode() {
return postalZipcode;
}
public String getPostalCountry() {
return postalCountry;
}
public List<Contact> getContactList(){
return contactList;
}
public List<Project> getProjectList(){
return projectList;
}
public List<Task> getTaskList(){
return taskList;
}
public List<Order> getOrderList() {
return orderList;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEmail(String email) {
this.email = email;
}
public void setUrl(String url) {
this.url = url;
}
public void setTurnover(Double turnover) {
this.turnover = turnover;
}
public void setVisitAddress(String visitAddress) {
this.visitAddress = visitAddress;
}
public void setVisitCity(String visitCity) {
this.visitCity = visitCity;
}
public void setVisitZipcode(String visitZipcode) {
this.visitZipcode = visitZipcode;
}
public void setVisitCountry(String visitCountry) {
this.visitCountry = visitCountry;
}
public void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}
public void setPostalCity(String postalCity) {
this.postalCity = postalCity;
}
public void setPostalZipcode(String postalZipcode) {
this.postalZipcode = postalZipcode;
}
public void setPostalCountry(String postalCountry) {
this.postalCountry = postalCountry;
}
public Drawable getClientImage() {
return clientImage;
}
public void setClientImage(Drawable clientImage) {
this.clientImage = clientImage;
}
public int getClientID() {
return clientID;
}
public void setClientID(int clientID) {
this.clientID = clientID;
}
underlying project object: (also with list of custom objects)
public class Project implements Serializable, Comparable<Project>{
private String clientName;
private String projectName;
private String projectDiscription;
private String projectStatus;
private GregorianCalendar projectDate;
private List<TimeSheet> projectTimeRegestrationList = new ArrayList<>();
private List<WorkOrder> workOrderList = new ArrayList<WorkOrder>();
public Project(String clientName, String projectName, String projectDiscription, String projectStatus, GregorianCalendar projectDate, List projectTimeRegestrationList, List workOrderList) {
this.projectName = projectName;
this.projectDiscription = projectDiscription;
this.projectStatus = projectStatus;
this.projectDate = projectDate;
this.clientName = clientName;
this.projectTimeRegestrationList = projectTimeRegestrationList;
this.workOrderList = workOrderList;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDiscription() {
return projectDiscription;
}
public void setProjectDiscription(String projectDiscription) {
this.projectDiscription = projectDiscription;
}
public String getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public GregorianCalendar getProjectDate() {
return projectDate;
}
public void setProjectDate(GregorianCalendar projectDate) {
this.projectDate = projectDate;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public List<TimeSheet> getProjectTimeRegestrationList() {
return projectTimeRegestrationList;
}
public List<WorkOrder> getWorkOrderList() {
return workOrderList;
}
now my specific question: is it possible to save this inside shared preferences, if yes, how do i do this, if no, how should i then locally safe this data.
you can use json to store them as a string in sharedpreference
for example if you want to store an object of your client class contaning a url ,country and phone
just write the following
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
jsonArray.put(object1);
//adding another object
JSONObject object2=new JSONObject();
object2.put("url","anotherurl");
object2.put("phone","anotherphonenumber");
object2.put("country","anothercountry");
jsonArray.put(object2);
} catch (JSONException e) {
e.printStackTrace();
}
and than simply save it as a string by calling jsonArray.toString() in sharedpreference
and if your object that you want to store contains a list of another object you can easily save like for example if you have a url, country, and phone number which you want to save plus a list of another object containing the first and lastname you can save list as json object itself just like you did for the url,phone number and country as shown below
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
//saving a list of another object contaning firstname and lastname
JSONArray listArray=new JSONArray();
//supposing your list contains 10 objects
for(int f=0;f<10;f++){
JSONObject listobject=new JSONObject();
listobject.put("firstname","myfirstname");
listobject.put("lastname","mylastname");
listArray.put(listobject);
}
//now the list array we added as an object of the jsonArray variable
JSONObject object2=new JSONObject(); //object2 containing the list of firstname and lastname
object2.put("list",listArray.toString());
jsonArray.put(object1);//object1 contains the url, phone, and country
jsonArray.put(object2);//object2 contains the list of firstname and lastname
} catch (JSONException e) {
e.printStackTrace();
}

Constructor ClipData.Item is undefined Android

im trying to create a item for a list, to display on a listview some pictures.
The codes is the following:
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (int i = 0; i < pictures.size(); i++) {
Item item = new Item(pictures.get(i).getID(),pictures.get(i).getAddress(),pictures.get(i).getDescription(),pictures.get(i).getPath());
items.add(item);
}
return items;
}
What i'm trying to do in this is to create an item for each picture on database. (getDescription would be to get the picture description from a database handler, same for address and path)
However im getting the following error in the line where i use the "gets"
The constructor ClipData.Item(int, String, String, String) is undefined.
What could this be? Thank you!
Picture Class
public class Picture {
int _id;
String _name;
String _address;
String _description;
String _path;
// Empty constructor
public Picture(){
}
// constructor
public Picture(int id, String name, String _address, String _description, String _path){
this._id = id;
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// constructor
public Picture(String name, String _address, String _description){
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
// getting phone number
public String getAddress(){
return this._address;
}
// setting phone number
public void setAddress(String phone_number){
this._address = phone_number;
}
public String getPath(){
return this._path;
}
public void setPath(String path){
this._path = path;
}
}
try to use for each loop
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (Picture pic:pictures) {
int id = pic.getID();
String address = pic.getAddress();
String desc= pic.getDescription();
String path= pic.getPath();
Item item = new Item(id ,address ,desc,path);
items.add(item);
}
return items;
}

Android: getParcelable returning null?

As a follow on from my last question: Passing Arraylist between activities? Using Parcelable
I'm now attempting to pass my ArrayList via Parcelable. However, when it's gotten from the other activity it returns null. I can't seem to figure out why. I've got the following...
ResultsList.java
public class ResultsList extends ArrayList<SearchList> implements Parcelable {
/**
*
*/
private static final long serialVersionUID = -78190146280643L;
public ResultsList(){
}
public ResultsList(Parcel in){
readFromParcel(in);
}
#SuppressWarnings({ "rawtypes" })
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public ResultsList createFromParcel(Parcel in) {
return new ResultsList(in);
}
public Object[] newArray(int arg0) {
return null;
}
};
private void readFromParcel(Parcel in) {
this.clear();
//First we have to read the list size
int size = in.readInt();
//Reading remember that we wrote first the Name and later the Phone Number.
//Order is fundamental
for (int i = 0; i < size; i++) {
String title = in.readString();
String Des = in.readString();
String message = in.readString();
SearchList c = new SearchList(title,Des,link);
this.add(c);
}
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
int size = this.size();
//We have to write the list size, we need him recreating the list
dest.writeInt(size);
//We decided arbitrarily to write first the Name and later the Phone Number.
for (int i = 0; i < size; i++) {
SearchList c = this.get(i);
dest.writeString(c.gettitle());
dest.writeString(c.getDescription());
dest.writeString(c.getmessage());
}
}
}
SearchList.java
public class SearchList {
private String title;
private String description;
private String message;
public SearchList(String name, String phone, String mail) {
super();
this.title = name;
this.description = phone;
this.message = mail;
}
public String gettitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getmessage() {
return message;
}
public void setmessage(String link) {
this.message = message;
}
}
listOfResults is declared as ResultsList listOfResults = new ResultsList(); and filled earlier in the code It's then sent with...
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
startActivityForResult(intent,0);
Receiving...
Bundle extras = getIntent().getExtras();
ResultsList results = extras.getParcelable("results");
I'd like to point out I'm testing this null thing by checking the size() of the Arraylist going into the Bundle and then it coming out. It goes in fine and comes out null.
Didn't attach bundle to intent! (doh!) was pointed out by a kind gent on IRC! #android-dev

Categories

Resources