I have a class that has parcelable implemented and I want to pass it to another activity.
This is how I've gone about it
public class Result implements Parcelable {
public static final String TMDB_IMAGE_PATH = "http://image.tmdb.org/t/p/w500";
#SerializedName("vote_count")
#Expose
private Integer voteCount;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("video")
#Expose
private Boolean video;
#SerializedName("vote_average")
#Expose
private Double voteAverage;
#SerializedName("title")
#Expose
private String title;
#SerializedName("popularity")
#Expose
private Double popularity;
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("original_language")
#Expose
private String originalLanguage;
#SerializedName("original_title")
#Expose
private String originalTitle;
#SerializedName("genre_ids")
#Expose
private JsonArray genreIds = null;
#SerializedName("backdrop_path")
#Expose
private String backdropPath;
#SerializedName("adult")
#Expose
private Boolean adult;
#SerializedName("overview")
#Expose
private String overview;
#SerializedName("release_date")
#Expose
private String releaseDate;
public Result(Integer voteCount, Integer id, Boolean video,Double voteAverage ,
String title ,Double popularity,String posterPath, String originalLanguage,
String originalTitle, JsonArray genreIds,String backdropPath,Boolean adult, String overview,String releaseDate){
this.voteCount = voteCount;
this.id = id;
this.video = video;
this.voteAverage = voteAverage;
this.title = title;
this.popularity = popularity;
this.posterPath = posterPath;
this.originalLanguage = originalLanguage;
this.originalTitle = originalTitle;
this.genreIds = genreIds;
this.backdropPath = backdropPath;
this.adult = adult;
this.overview = overview;
this.releaseDate = releaseDate;
}
private Result(Parcel source) {
this.voteCount = source.readInt();
this.id = source.readInt();
this.video = source.readByte() != 0;
this.voteAverage = source.readDouble();
this.title = source.readString();
this.popularity = source.readDouble();
this.posterPath = source.readString();
this.originalLanguage = source.readString();
this.originalTitle = source.readString();
this.backdropPath = source.readString();
this.adult = source.readByte() != 0;
this.overview = source.readString();
this.releaseDate = source.readString();
}
public Integer getVoteCount() {
return voteCount;
}
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Boolean getVideo() {
return video;
}
public void setVideo(Boolean video) {
this.video = video;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public String getPosterPath() {
return TMDB_IMAGE_PATH + posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public JsonArray getGenreIds() {
return genreIds;
}
public void setGenreIds(JsonArray genreIds) {
this.genreIds = genreIds;
}
public String getBackdropPath() {
return TMDB_IMAGE_PATH +backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public Boolean getAdult() {
return adult;
}
public void setAdult(Boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public static final Parcelable.Creator<Result> CREATOR = new Parcelable.Creator<Result>() {
public Result createFromParcel(Parcel source) {
Result movie = new Result(source);
return movie;
}
public Result[] newArray(int size) {
return new Result[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int i) {
dest.writeString(posterPath);
dest.writeByte((byte) (adult ? 1 : 0));
dest.writeString(overview);
dest.writeString(releaseDate);
dest.writeInt(id);
dest.writeString(originalTitle);
dest.writeString(originalLanguage);
dest.writeString(title);
dest.writeString(backdropPath);
dest.writeDouble(popularity);
dest.writeInt(voteCount);
dest.writeByte((byte) (video ? 1 : 0));
dest.writeDouble(voteAverage);
}
}
This is how I send the Parcelable class From my RecycerView Adapter
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private List<Result> movies;
private int rowLayout;
private Context context;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
ImageView pic;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
movieTitle = (TextView) itemView.findViewById(R.id.title);
data = (TextView) itemView.findViewById(R.id.subtitle);
rating = (TextView) itemView.findViewById(R.id.rating);
pic = (ImageView) itemView.findViewById(R.id.image_view_pic);
}
#Override
public void onClick(View view) {
int itemPosition = getAdapterPosition();
Result movie = movies.get(itemPosition);
Intent intent = new Intent(view.getContext(), MovieDetailActivity.class);
intent.putExtra("movieDetails",movie);
view.getContext().startActivity(intent);
}
}
public MovieAdapter(List<Result> movies, Context context){
this.movies = movies;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.movieTitle.setText(movies.get(position).getTitle());
holder.data.setText(movies.get(position).getReleaseDate());
holder.rating.setText(movies.get(position).getVoteAverage().toString());
String PictureString = movies.get(position).getPosterPath();
Picasso.with(context)
.load(PictureString)
.placeholder(R.color.colorAccent)
.into(holder.pic);
}
#Override
public int getItemCount() {
return movies.size();
}
}
This is where I receive it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
Intent intent = getIntent();
Result films = intent.getParcelableExtra("movieDetails");
}
So the problem with this code is that i am getting a null value at receving end but my Recycler view is displaying data.
Please can someone point me to the probelm?
The order in writing data and reading it should be the same. When in writeToParcel() you first write posterPath
#Override
public void writeToParcel(Parcel dest, int i) {
dest.writeString(posterPath);
....
}
Then when reading from Parcel you should read it first. like below:
private Result(Parcel source) {
this.posterPath = source.readString();
...
}
and so on.
//our model class name of Property
public class Property implements Parcelable {
...
}
//Sending our parcelable model class within intent
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("Property", property);
startActivity(intent);
//collect our intent
Intent intent = getIntent();
Property property = intent.getParcelableExtra("Property");
Related
I am working on a nearyPlaces application that helps users get nearby locations around them. I used retrofit library to fetch response from google api. Everything works perfectly as you can see here. So. I want to parse this results inside a recyclerView just like google maps. The problem is that after consuming the api, it displays as an object instead of an arrayList.
I really need directions on this as it has given me headache for a few weeks.
RequestInterface
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
interface RequestInterface {
#GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
Call <NearbyPlaces.Result> getPlacesJson(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
MapActivity.java
private void getPlacesResponse(String type) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInteface = retrofit.create(RequestInterface.class);
Call<NearbyPlaces.Result> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);
call.enqueue(new Callback<NearbyPlaces.Result>() {
#Override
public void onResponse(#NonNull Call<NearbyPlaces.Result> call, #NonNull Response<NearbyPlaces.Result> response) {
Log.d("error", response.toString());
placeResultAdapter=new PlaceResultAdapter(MapActivity.this, placeResultAdapter);
//here I need to set an arrayList to my adapter but I can't because the retrofit's data comes as an object instead of arrayList.
// mRecyclerView.setAdapter(placeResultAdapter);
}
#Override
public void onFailure(Call<NearbyPlaces.Result> call, Throwable t) {
Log.d("error", call.toString() + " " + t.toString());
}
});
}
Nearby Places Class
public class GetNearbyPlaces extends AsyncTask<Object, String,String> {
private String googlePlaceData;
private GoogleMap mMap;
private Context mContext;
private Bitmap bitmap;
public GetNearbyPlaces (Context context){
mContext = context;
}
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap) objects[0];
String url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try {
googlePlaceData = downloadUrl.ReadTheURL(url);
} catch (IOException e) {
e.printStackTrace();
}
return googlePlaceData;
}
#Override
protected void onPostExecute(String s) {
List<HashMap<String, String>> nearbyPlacesList;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
Log.d("nearby", nearbyPlacesList.toString());
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList){
for (int i = 0; i<nearbyPlacesList.size(); i++){
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
String nameOfPlace = googleNearbyPlace.get("place_name");
String iconLink = googleNearbyPlace.get("icon");
String vicinity = googleNearbyPlace.get("vicinity");
double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(nameOfPlace);
//load image icon from url;
Glide.with(mContext)
.asBitmap()
.apply(RequestOptions.centerCropTransform())
.load(iconLink)
.listener(new RequestListener<Bitmap>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap bitmap, Transition<? super Bitmap> transition) {
Bitmap locator = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.locator_red);
Bitmap scaledLocator =Bitmap.createScaledBitmap(locator, 100, 100, true);
Bitmap iconBitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
Bitmap mergedImages = createSingleImageFromMultipleImages(scaledLocator, tintImage(iconBitmap, Color.WHITE));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(mergedImages));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
});
}
}
private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(firstImage, 0f, 0f, null);
canvas.drawBitmap(secondImage, 35, 10, null);
return result;
}
public static Bitmap tintImage(Bitmap bitmap, int color) {
Paint paint = new Paint();
paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
Bitmap bitmapResult = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapResult);
canvas.drawBitmap(bitmap, 0, 0, paint);
return bitmapResult;
}
}
Nearby Places Adapter (Updated)
public class PlaceResultAdapter extends RecyclerView.Adapter {
private ArrayList placeModels;
private Context context;
public PlaceResultAdapter(Context context, ArrayList<NearbyPlaces.Result> placeModels) {
this.placeModels=placeModels;
this.context=context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.place_result_item,viewGroup,false);
return new PlaceResultAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PlaceResultAdapter.ViewHolder viewHolder, int i) {
viewHolder.place_name.setText(placeModels.get(i).getName());
//Picasso.get().load(placeModels.get(i).getUrl()).into(viewHolder.car_image);
}
#Override
public int getItemCount() {
return placeModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView place_image;
private TextView place_name,place_category;
public ViewHolder(#NonNull View itemView) {
super(itemView);
place_image= itemView.findViewById(R.id.image_view);
place_name= itemView.findViewById(R.id.title);
place_category= itemView.findViewById(R.id.category_text);
}
}
}
Model Class (Updated)
public abstract class NearbyPlaces {
public class Result {
#Expose
#SerializedName("photos")
private List<Photos> photos;
#SerializedName("geometry")
private Geometry getGeometry;
#SerializedName("icon")
private String icon;
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("vicinity")
private String vicinity;
public Geometry getGetGeometry() {
return getGeometry;
}
public List<Photos> getPhotos() {
return photos;
}
public void setPhotos(List<Photos> photos) {
this.photos = photos;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVicinity() {
return vicinity;
}
}
public static class Photos {
#Expose
#SerializedName("width")
private int width;
#Expose
#SerializedName("photo_reference")
private String photoReference;
#Expose
#SerializedName("html_attributions")
private List<String> htmlAttributions;
#Expose
#SerializedName("height")
private int height;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String getPhotoReference() {
return photoReference;
}
public void setPhotoReference(String photoReference) {
this.photoReference = photoReference;
}
public List<String> getHtmlAttributions() {
return htmlAttributions;
}
public void setHtmlAttributions(List<String> htmlAttributions) {
this.htmlAttributions = htmlAttributions;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
public static class Reviews {
#Expose
#SerializedName("time")
private int time;
#Expose
#SerializedName("text")
private String text;
#Expose
#SerializedName("relative_time_description")
private String relativeTimeDescription;
#Expose
#SerializedName("rating")
private int rating;
#Expose
#SerializedName("profile_photo_url")
private String profilePhotoUrl;
#Expose
#SerializedName("language")
private String language;
#Expose
#SerializedName("author_url")
private String authorUrl;
#Expose
#SerializedName("author_name")
private String authorName;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRelativeTimeDescription() {
return relativeTimeDescription;
}
public void setRelativeTimeDescription(String relativeTimeDescription) {
this.relativeTimeDescription = relativeTimeDescription;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getProfilePhotoUrl() {
return profilePhotoUrl;
}
public void setProfilePhotoUrl(String profilePhotoUrl) {
this.profilePhotoUrl = profilePhotoUrl;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getAuthorUrl() {
return authorUrl;
}
public void setAuthorUrl(String authorUrl) {
this.authorUrl = authorUrl;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
public static class Geometry {
#Expose
#SerializedName("viewport")
private Viewport viewport;
#Expose
#SerializedName("location")
private Location location;
public Viewport getViewport() {
return viewport;
}
public void setViewport(Viewport viewport) {
this.viewport = viewport;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
public static class Viewport {
#Expose
#SerializedName("southwest")
private Southwest southwest;
#Expose
#SerializedName("northeast")
private Northeast northeast;
public Southwest getSouthwest() {
return southwest;
}
public void setSouthwest(Southwest southwest) {
this.southwest = southwest;
}
public Northeast getNortheast() {
return northeast;
}
public void setNortheast(Northeast northeast) {
this.northeast = northeast;
}
}
public static class Southwest {
#Expose
#SerializedName("lng")
private double lng;
#Expose
#SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class Northeast {
#Expose
#SerializedName("lng")
private double lng;
#Expose
#SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class Location {
#Expose
#SerializedName("lng")
private double lng;
#Expose
#SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class AddressComponents {
#Expose
#SerializedName("types")
private List<String> types;
#Expose
#SerializedName("short_name")
private String shortName;
#Expose
#SerializedName("long_name")
private String longName;
public List<String> getTypes() {
return types;
}
public void setTypes(List<String> types) {
this.types = types;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getLongName() {
return longName;
}
public void setLongName(String longName) {
this.longName = longName;
}
}
}
As you can see, am already retrieving the data inside NearbyPlaces Class which contains the AsyncTask class. So i think what I need to do is find out how to transfer the data from my async task to my adapter so I can show with recyclerView.
create models as per your json response
Main object
public class Response {
#SerializedName("results")
private ArrayList<Result> list;
public ArrayList<Result> getList() {
return list;
}
}
Array inside main object
public class Result {
#SerializedName("geometry")
private Geometry getGeometry;
#SerializedName("icon")
private String icon;
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("vicinity")
private String vicinity;
public Geometry getGetGeometry() {
return getGeometry;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVicinity() {
return vicinity;
}
}
Geometry object
public class Geometry {
#SerializedName("location")
private Location location;
#SerializedName("viewport")
private ViewPort viewPort;
public Location getLocation() {
return location;
}
public ViewPort getViewPort() {
return viewPort;
}
}
Location object
public class Location {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
ViewPort model
public class ViewPort {
#SerializedName("northeast")
private NorthEast northEast;
#SerializedName("southwest")
private SouthWest southWest;
public NorthEast getNorthEast() {
return northEast;
}
public SouthWest getSouthWest() {
return southWest;
}
}
NorthEast model
public class NorthEast {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
SouthWest model
public class SouthWest {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
1 Create class for all these models and copy them
2 Modify your interface
interface RequestInterface {
#GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
Call <Response> getPlacesJson(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
3 Modify your apicall function
private void getPlacesResponse(String type) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInteface = retrofit.create(RequestInterface.class);
Call<Response> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(#NonNull Call<Response> call, #NonNull Response<Resonse> response) {
ArrayList<Result> dataList = response.body().getList();
placeResultAdapter=new PlaceResultAdapter(MapActivity.this, dataList);
mRecyclerView.setAdapter(placeResultAdapter);
}
#Override
public void onFailure(Response> call, Throwable t) {
Log.d("error", call.toString() + " " + t.toString());
}
});
}
4 : Now you can fetch api data.
Adapter class
public class PlaceResultAdapter extends RecyclerView.Adapter<PlaceResultAdapter.ViewHolder> {
private ArrayList<NearbyPlaces.Result> placeModels;
private Context context;
public PlaceResultAdapter(Context context, ArrayList<NearbyPlaces.Result> placeModels) {
this.placeModels=placeModels;
this.context=context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.place_result_item,viewGroup,false);
return new PlaceResultAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PlaceResultAdapter.ViewHolder viewHolder, int i) {
viewHolder.place_name.setText(placeModels.get(i).getName());
viewHolder.place_category.setText(placeModels.get(i).getTypes().get(0));
String image_url = placeModels.get(i).getIcon();
//Picasso.get().load(image_url).into(viewHolder.car_image);
}
#Override
public int getItemCount() {
return placeModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView place_image;
private TextView place_name,place_category;
public ViewHolder(#NonNull View itemView) {
super(itemView);
place_image= itemView.findViewById(R.id.image_view);
place_name= itemView.findViewById(R.id.title);
place_category= itemView.findViewById(R.id.category_text);
}
}
}
my problem is when I scan Qr code, I want to get the class file variables
and send via btnSearch button to an another activity. plz help me how to do it? sorry for poor English
This is My class file
public class UploadDataGetter {
#SerializedName("record_id")
private int id;
#SerializedName("full_name")
private static String name;
#SerializedName("full_address")
private String address;
#SerializedName("contact")
private String contact;
#SerializedName("dilivery_place")
private String dplace;
#SerializedName("dilivery_place")
private String fdetails;
#SerializedName("no_of_normal")
private int noOfNormal;
#SerializedName("no_of_classified")
private int noOfClassified;
#SerializedName("no_of_cds")
private int noOfCds;
public UploadDataGetter(
//constuctor's para
int record_id,
String full_name,
String full_address,
String contact_number,
String dilivery_place ,
String further_details,
int no_of_normal,
int no_of_classified,
int no_of_cds
)
{
id = record_id;
name = full_name;
address = full_address;
contact = contact_number;
dplace = dilivery_place;
fdetails = further_details;
noOfNormal = no_of_normal;
noOfClassified= no_of_classified;
noOfCds = no_of_cds;
String img_collector ;
String dilivery_status ;
double geo_long;
double geo_lat;
}
public
int getId() {
return id;
}
public
void setId(int id) {
this.id = id;
}
public static
String getName() {
return name;
}
public
void setName(String name) {
this.name = name;
}
public
String getAddress() {
return address;
}
public
void setAddress(String address) {
this.address = address;
}
public
String getContact() {
return contact;
}
public
void setContact(String contact) {
this.contact = contact;
}
public
String getDplace() {
return dplace;
}
public
void setDplace(String dplace) {
this.dplace = dplace;
}
public
String getFdetails() {
return fdetails;
}
public
void setFdetails(String fdetails) {
this.fdetails = fdetails;
}
public
int getNoOfNormal() {
return noOfNormal;
}
public
void setNoOfNormal(int noOfNormal) {
this.noOfNormal = noOfNormal;
}
public
int getNoOfClassified() {
return noOfClassified;
}
public
void setNoOfClassified(int noOfClassified) {
this.noOfClassified = noOfClassified;
}
public
int getNoOfCds() {
return noOfCds;
}
public
void setNoOfCds(int noOfCds) {
this.noOfCds = noOfCds;
}
this is my Qr Activity,
public class QrActivity extends AppCompatActivity {
public static UploadDataGetter id;
public static UploadDataGetter name;
public static UploadDataGetter address;
public static UploadDataGetter dplace;
public static UploadDataGetter fdetails;
public static UploadDataGetter noOfNormal;
public static UploadDataGetter noOfClassified;
public static UploadDataGetter noOfCds;
public static UploadDataGetter img_collector;
public static UploadDataGetter dilivery_status;
/**
* QR code declaration
*/
Button btnscan, btnSearch;
TextView lblSearch;
TextView ID;
TextView DPlace;
TextView Address;
TextView name;
TextView contact;
private Object uploadDataGetter;
private String result;
#Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr);
btnscan = (Button) findViewById(R.id.btnscan);
btnscan.setClickable(false);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setClickable(false);
lblSearch = (TextView) findViewById(R.id.lblSearch);
final Activity activity = this;
btnscan.setOnClickListener(new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnscan.setClickable(true);
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
//call the class var
if (this.getIntent().getAction().equals("moveData"))
moveData();
}
private void moveData() {
String id = uploadDataGetter.toString();
String name = uploadDataGetter.toString();
String address = uploadDataGetter.toString();
String dplace = uploadDataGetter.toString();
String noOfNormal= uploadDataGetter.toString();
String noOfClassified = uploadDataGetter.toString();
String noOfCds = uploadDataGetter.toString();
//this is for Calling class file
}
#Override
protected
void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_SHORT).show();
} else {
/**
* Qr code result
* */
lblSearch.setText(result.getContents());
// Toast.makeText(this, result.getContents(), Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
// "Go to Second Activity" button click
View.OnClickListener listener = new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnSearch.setClickable(true);
Intent myIntent= new Intent(QrActivity.this, DistributionDetails.class);
myIntent.setAction("moveData");
startActivity(myIntent);
}
};
btnscan.setOnClickListener(listener);
btnSearch.setOnClickListener(listener);
}
public
void getResults(View view) {
}
}
Replace your class with this
public class UploadDataGetter implements Serializable {
#SerializedName("record_id")
private int id;
#SerializedName("full_name")
private String name;
#SerializedName("full_address")
private String address;
#SerializedName("contact")
private String contact;
#SerializedName("dilivery_place")
private String dplace;
#SerializedName("dilivery_place")
private String fdetails;
#SerializedName("no_of_normal")
private int noOfNormal;
#SerializedName("no_of_classified")
private int noOfClassified;
#SerializedName("no_of_cds")
private int noOfCds;
public UploadDataGetter(
//constuctor's para
int record_id,
String full_name,
String full_address,
String contact_number,
String dilivery_place,
String further_details,
int no_of_normal,
int no_of_classified,
int no_of_cds
) {
id = record_id;
name = full_name;
address = full_address;
contact = contact_number;
dplace = dilivery_place;
fdetails = further_details;
noOfNormal = no_of_normal;
noOfClassified = no_of_classified;
noOfCds = no_of_cds;
String img_collector;
String dilivery_status;
double geo_long;
double geo_lat;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getDplace() {
return dplace;
}
public void setDplace(String dplace) {
this.dplace = dplace;
}
public String getFdetails() {
return fdetails;
}
public void setFdetails(String fdetails) {
this.fdetails = fdetails;
}
public int getNoOfNormal() {
return noOfNormal;
}
public void setNoOfNormal(int noOfNormal) {
this.noOfNormal = noOfNormal;
}
public int getNoOfClassified() {
return noOfClassified;
}
public void setNoOfClassified(int noOfClassified) {
this.noOfClassified = noOfClassified;
}
public int getNoOfCds() {
return noOfCds;
}
public void setNoOfCds(int noOfCds) {
this.noOfCds = noOfCds;
}
}
now send this to new activity in intent like this
Intent intent=new Intent(this, NewActivity.class);
int.putExtra("data", YOUR_UPDATE_DATA_GETTER_OBJECT);
Now get the object in the new activity like this
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class NewActivity extends Activity {
private UploadDataGetter dataGetter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
if(intent.hasExtra("data")){
dataGetter= (UploadDataGetter) intent.getSerializableExtra("data");
Log.d("NewActivity","ID: "+dataGetter.getId());
}
}
}
Good day. I need to implement parcelable in Model class.Currently it is Serializable. for now only setdate and set title if thare If any one can help. please edit code.
MainActivity.java
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setDate(item.child(4).text());
newsItem.setTitle(item.child(0).text());
newsItemsList.add(newsItem);
}
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new NewsAdaptor(Main2Activity.this,
newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
NewsItem.java //model class
public class NewsItem implements Serializable {
String imagePath;
String title;
String link;
String date;
public NewsItem () {
}
public String getImagePath () {
return imagePath;
}
public void setImagePath ( String imagePath ) {
this.imagePath = imagePath;
}
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
public String getLink () {
return link;
}
public void setLink ( String link ) {
this.link = link;
}
public String getDate () {
return date;
}
public void setDate ( String date ) {
this.date = date;
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
private int textSize;
TextView tvtitle;
private int color;
Context context;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList<NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null){
convertView=View.inflate(context, R.layout.newsitemlist_layout,null);
}
NewsItem currentNews = newsList.get(position);
ImageView iv1 = (ImageView) convertView.findViewById(R.id.mainimg);
TextView tvdate = (TextView) convertView.findViewById(R.id.pubDateid);
Picasso.with(context).load(currentNews.getImagePath()).placeholder(R.drawable.expressimg).into(iv1);
tvdate.setText(currentNews.getDate());
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
Check this Parcelable NewsItem:
public class NewsItem implements Parcelable {
String imagePath;
String title;
String link;
String date;
public NewsItem() {
}
protected NewsItem(Parcel in) {
imagePath = in.readString();
title = in.readString();
link = in.readString();
date = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(imagePath);
dest.writeString(title);
dest.writeString(link);
dest.writeString(date);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<NewsItem> CREATOR = new Creator<NewsItem>() {
#Override
public NewsItem createFromParcel(Parcel in) {
return new NewsItem(in);
}
#Override
public NewsItem[] newArray(int size) {
return new NewsItem[size];
}
};
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
I am trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}
I'm using GSON to parse a JSON feed like this here:
http://dvz.hj.cx/api/get_recent_posts/?dev=1
My model class looks like this one here:
public class Recent {
#Expose
private String status;
#Expose
private int count;
#Expose
private int count_total;
#Expose
private int pages;
#Expose
private List<Post> posts = new ArrayList<Post>();
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Recent withStatus(String status) {
this.status = status;
return this;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Recent withCount(int count) {
this.count = count;
return this;
}
public int getCount_total() {
return count_total;
}
public void setCount_total(int count_total) {
this.count_total = count_total;
}
public Recent withCount_total(int count_total) {
this.count_total = count_total;
return this;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Recent withPages(int pages) {
this.pages = pages;
return this;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public Recent withPosts(List<Post> posts) {
this.posts = posts;
return this;
}
}
As you can see I'm referring to another model class called Post.
The Post model class looks like this one:
public class Post {
#Expose
private int id;
#Expose
private String url;
#Expose
private String title;
#Expose
private String date;
#Expose
private List<Category> categories = new ArrayList<Category>();
#Expose
private List<Object> tags = new ArrayList<Object>();
#Expose
private Author author;
#Expose
private List<Attachment> attachments = new ArrayList<Attachment>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Post withId(int id) {
this.id = id;
return this;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Post withUrl(String url) {
this.url = url;
return this;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post withTitle(String title) {
this.title = title;
return this;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Post withDate(String date) {
this.date = date;
return this;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public Post withCategories(List<Category> categories) {
this.categories = categories;
return this;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Post withAuthor(Author author) {
this.author = author;
return this;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public Post withAttachments(List<Attachment> attachments) {
this.attachments = attachments;
return this;
}
}
And again I'm reffering to some other models. Until now erverything works perfect, but now I need to access some of this getters and setters in my BaseAdapter.
My Adapter classe looks like this:
public class NewsList extends BaseAdapter {
private List<Recent> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public ImageLoader imageLoader;
public NewsList(Context context, List<Recent> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.news_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.commentView = (TextView) convertView.findViewById(R.id.comment);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Recent rec = (Recent) listData.get(position);
Post post = (Post) rec.getPosts();
Attachment att = (Attachment) post.getAttachments();
List<Images> img = att.getImages();
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
if(post != null){
/* date and time */
String date = post.getDate().replace("-",".");
String zeit = date.substring(11,16);
String datum = date.substring(0, 11);
String djahr = datum.substring(0,4);
String dmonat = datum.substring(5,8);
String dtag = datum.substring(8,10);
holder.headlineView.setText(Html.fromHtml(post.getTitle()));
holder.reportedDateView.setText(Html.fromHtml("Am <b>" + dtag+"."+dmonat+djahr+" </b>um <b>"+zeit+"</b>"));
holder.commentView.setText(Html.fromHtml("Von: <b>" + author.getName()));
ImageView image = holder.imageView;
if(post.attachments.getMime_type().contains("image")){
imageLoader.DisplayImage(thumb.getUrl(), image);
}
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView commentView;
TextView reportedDateView;
ImageView imageView;
}
}
As you see I try to get the List<Post> which is located inside the ArrayList<Recent>.
This line works perfect:
Recent rec = (Recent) listData.get(position);
But as soon as it comes to this line it doesn't work:
Post post = (Post) rec.getPosts();
I have no idea how to resolve this. Please help its very important for me. If you have a better solution, its welcome.
When it comes to this line Post post = (Post) rec.getPosts();, LogCat says
Cannot convert ArrayList to List
You are misinterpreting List<T> with T and this same problem is present at different parts of your code:
getPosts() returns List<Post> not Post like getImages() returns List<Images> not Images, you might need a loop to iterate over your List<Post>, getting single Post and then getting its data like List<Attachment>.
Change it to the following:
Recent rec = (Recent) listData.get(position);
List<Post> posts = rec.getPosts();
for(int i = 0; i < posts.size(); i++){
Post post = (Post) posts.get(i);
if(post != null){
List<Attachment> atts = post.getAttachments();
Attachment att = (Attachment) atts.get(0) // You can use loop instead of get(0)
List<Images> imgs = att.getImages();
Images img = (Images) imgs.get(0); // You can use loop instead of get(0)
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
...
}
}