Custom ArrayList, Passing data between Classes - android

I have a fragment activity with a custom arraylist format
public class giftsListFormat {
String id;
String name;
String url;
String points;
}
ArrayList<giftsListFormat> giftList = new ArrayList<giftsListFormat>();
I am trying to access this list format from an asynctask class
private static class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private MyAsyncTask () {
[How can i create an object of giftsListFormat here?]
[How can i access giftList from here]
}
}

Try this - This may be the custom class that you need.
Declare this as global :
ArrayList<giftsListFormat> details = new ArrayList<giftsListFormat>();
public class giftsListFormat {
String id;
String name;
String url;
String points;
public String getid() {
return id;
}
public void setid(String id)
{
this.id = id;
}
public String getname() {
return name;
}
public void setname(String name)
{
this.name = name;
}
public String geturl() {
return url;
}
public void seturl(String url)
{
this.url = url;
}
public String getpoints() {
return points;
}
public void setpoints(String points)
{
this.points = points;
}
}
To put the value into the array list - Do this
giftsListFormat Detail;
Detail = new giftsListFormat();
Detail.setid("test1");
Detail.setname("test2");
details.add(Detail);
Now to retrieve the values
put the following code inside the async task
details.get(i).id.toString();
details.get(i).name.toString();
details.get(i).url.toString();
You can iterate over the size of the array list.
details.size();

Make "giftList" global variable in your activity.
Send the context to your AsyncTask through Constructor.
Now you can access that variable as follows:
private static class MyAsyncTask extends AsyncTask<Void, Void, Void> {
ArrayList<giftsListFormat> giftList;
private MyAsyncTask (Activity activity) {
giftList = activity. giftList;
giftsListFormat ref = giftList.get(pos);
}
}

create a giftsListFormat class like:
public class giftsListFormat{
String id;
String name;
String url;
String points;
//create constructure and assign parameters which you want to set
public giftsListFormat(String id, String name,String url, String points){
this.id = id;
this.name = name;
this.url = url;
this.points = points;
}
public getId(){
return id;
}
public getName(){
return name;
}
public getUrl(){
return url;
}
public getPoints(){
return points;
}
}
And use this class like: ArrayList<giftsListFormat>...
Inside AsyncTask set all your data at the time of initialization..like:
giftsListFormat mData = new giftsListFormat(id, name, url, points);
And when you want to get just use get methods...

Related

Model structure to parse JSON with Retrofit [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?
(11 answers)
Closed 4 years ago.
I have the following JSON structure:
[
{
"id":1,
"name":"car",
"elements":[
{
"id":1,
"name":"price",
"type":"textField",
"constraints":"blablabla"
},
{
"id":2,
"name":"color",
"type":"textField",
"constraints":"blablabla"
},
{
"id":3,
"name":"images",
"type":"image",
"constraints":"blablabla"
}
]
}
]
And I have the following models:
public class Product {
private Long id;
private String name;
#Expose
private Element elements;
public Product(Long id, String name, Element elements) {
this.id = id;
this.name = name;
this.elements = elements;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Element getElements() {
return elements;
}
}
public class Element {
private Long id;
private String name;
private String type;
private String constraints;
public Element(Long id, String name, String constraints, String type) {
this.id = id;
this.type=type;
this.name = name;
this.constraints = constraints;
}
public String getType() {
return type;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getConstraints() {
return constraints;
}
}
The Elements model is which I have problems, I am getting the following error:
ERROR: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 35 path $[0].elements
How can I change the model to make it work? I tried to change the elements in Product class to JSONObject array but when I wanted to parse, it was empty.
You need to modify your POJOs like this:
Element.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Element {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("type")
#Expose
private String type;
#SerializedName("constraints")
#Expose
private String constraints;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConstraints() {
return constraints;
}
public void setConstraints(String constraints) {
this.constraints = constraints;
}
}
Product.java
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
P.S: You should use 'http://www.jsonschema2pojo.org/' website for generating POJO automatically from the JSON string you provide to it.
I hope this helps.
I think you try to put an array of Elements into "private Element elements" which is a single object
Change your pojo with this. Also you can add your respective constructor which you require.
public class Element {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("type")
#Expose
private String type;
#SerializedName("constraints")
#Expose
private String constraints;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConstraints() {
return constraints;
}
public void setConstraints(String constraints) {
this.constraints = constraints;
}
}
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
in json you have list of Element and in the model you declared Element as an Object
change this private Element elements; to List of Element
Try this pojo or you can make from this link
private String id;
private String name;
private ArrayList<Elements> elements;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public ArrayList<Elements> getElements ()
{
return elements;
}
public void setElements (ArrayList<Elements> elements)
{
this.elements = elements;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", name = "+name+", elements = "+elements+"]";
}
public class Elements
{
private String id;
private String name;
private String constraints;
private String type;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getConstraints ()
{
return constraints;
}
public void setConstraints (String constraints)
{
this.constraints = constraints;
}
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", name = "+name+", constraints = "+constraints+",
type = "+type+"]";
}
}

Converting the string resources to strings

I've already tried to use
String mystring = getResources().getString(R.string.mystring);
And I found the same theme in this article How can I convert the android resources int to a string. eg.: android.R.string.cancel?. But it doesn't work in my situation.
This is my code:
public class Film{
private int image;
private String name;
private String schedule;
private String description;
public Film() {
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class FilmList {
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(getResources().getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(getResources().getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(getResources().getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(getResources().getString(R.string.desc2));
films.add(film);
return films
}
}
If you don't have access to a Context (e.g. via an Activity, Service, ContentProvider, or BroadcastReceiver), you cannot get a string resource.
If you have a class that is not one of the above and it needs to get a string resource, you must either have pass a Context to that class so it can retrieve the resource, or pass that class an already-resolved resource.
Make an application class and add a hold its reference in a static varialble. then you can access context anywhere in the app
public class MyApp extends Application {
private static AppLWP instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Then you can access this instance for context anywhere in the app
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc2));
films.add(film);
return films
}
}
First, provide context to the class Film via the activity you are calling the object of Film.
If you call from Main Activity you will have to do something like this:
public class MainActivty extends AppCompatActivity {
private static MainActivty obj;
onCreate() {
//usual functions
obj = MainActivity.this;
}
}
Once you have the context, simply try this:
String mystring = context.getString(R.string.mystring);
Or, if you floowed my MainActivty method:
String mystring = MainActivty.obj.getResources().getString(R.string.mystring);

How to retrieve a value from list android

I have a list specialties having 75 items that has two values id and name.
private List specialties;
I would like to get the name without using a loop something like below
specialties.get(0).name;
I get an error saying can't resolve name. Is there any way to retrieve name from the values list.
Thanks.
Create a class (Model) to get and set the ID and Name property:-
public class ClassName {
private String id;
private String name;
public ClassName(String mId, String mName){
this.id=mId;
this.name=mName;
}
public String getName() {
return name;
}
public void setName(String sName) {
this.name = sName;
}
public String getId() {
return id;
}
public void setId(String sId) {
this.id = sId;
}
}
In your Activity:-
Define a List having the ClassName type of objects.
List<ClassName> mList = new ArrayList<>();
Now access the property name like this:-
mList.get(0).getName();
mList.get(0).getId();
try the following:
public class Clone {
private int Id;
private String name;
public int getId() {
return Id;
}
public String getName() {
return name;
}
public void setId(int id) {
Id = id;
}
public void setName(String name) {
this.name = name;
}
}
and use
private List<Clone> arrayList = new ArrayList();
for (int i = 0; i < 10; i++) {
Clone helloItem = new Clone();
helloItem.setId(i);
helloItem.setName("I'm Clone no - " + i);
arrayList.add(helloItem);
}
Log.d("check", "get item - " + arrayList.get(0).getName());
hope it help.
I want to suggest you. You should declare name with public access. If it is not public, use public getter and setter method.Call getName() method.
public class YourClass{
private int id;
private String name;
public YourClass(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private List<YourClass> specialties = new ArrayList<YourClass>;
...//add data into list...
specialties.add(new YourClass( 1 , "John"));
...// retrieve data
specialties.get(position).getName();
You have declared your list as private List specialties; you can not access it like this specialties.get(0).name;
You need declare your list like this private List<YourModelClass> specialties;
SAMPLE DEMO
If you want add model class in your list than than check this example
create model class like this
public class User {
String name, email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Now use like this in your list
List<User> userArrayList= new ArrayList<>();
To add data inside list like this
userArrayList.add(new User("Nilesh","abc#gmail.com"));
To get data from your list use like this
userArrayList.get(0).getEmail();
userArrayList.get(0).getEmail();
or
for (int i=0;i<userArrayList.size();i++){
userArrayList.get(i).getName();
userArrayList.get(i).getEmail();
}

Missing object when using #SerializedName with Retrofit call

I'm developing an Android app which connects to a Springboot server.
The app (using okhttp3 and retrofit) calls the server which returns an array list in an object (Photo Response) below.
The list is populating but the object MediaContentGroup does not populate in any photo object even though the fields of id and title do.
I've debugged through my server to ensure that I am using the correct object names when using #SerializedName.
I'm pretty new to Android development and using springboot, so if anyone could help me to understand why the MediaContentGroup object is always null, I would really appreciate it.
Is there any possible way I've set it to only accept Strings??
Thanks
public class PhotoResponse {
#SerializedName("photoFeed")
#Expose
private PhotoFeed photoFeed;
public PhotoFeed getPhotoFeed() {
return photoFeed;
}
}
public class PhotoFeed {
#SerializedName("photoList")
#Expose
private List<Photo> photoList = new ArrayList<>();
public List<Photo> getPhotoList() {
return photoList;
}
}
public class Photo {
public final static int HD_720_WIDTH = 1280;
public final static int HD_720_HEIGHT = 720;
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("mediaContentGroup")
#Expose
private MediaContentGroup mediaContentGroup;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setMediaContentGroup(MediaContentGroup mediaContentGroup){
this.mediaContentGroup = mediaContentGroup;
}
public MediaContentGroup getMediaContentGroup(){
return this.mediaContentGroup;
}
public String getImageUrl() {
return mediaContentGroup.getImages().get(0).getUrl();
}
public String getThumbUrl() {
return mediaContentGroup.getThumbnails().get(0).getUrl();
}
}
public class MediaContentGroup {
#SerializedName("images")
#Expose
public List<MediaContent> images = new ArrayList<>();
public void setImages(List<MediaContent> images){ this.images = images;}
public List<MediaContent> getImages() {
return images;
}
#SerializedName("thumbnails")
#Expose
public List<Thumbnail> thumbnails = new ArrayList<>();
public void setThumbnails(List<Thumbnail> thumbnails){ this.thumbnails = thumbnails;}
public List<Thumbnail> getThumbnails() {
return thumbnails;
}
}
public class Thumbnail {
#SerializedName("url")
#Expose
private String url;
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}

Professional way to handle model classes when using GSON and SQLight Android app

In My application I get data from a web service and display those data in recycler view. After that I'm planing to add those data in to local sqlite database and display those data when user open application without internet connection.
Here's a simple model class I'm using to pars JSON result using GSON
public class Repo implements Parcelable {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I can create a almost identical model class to represent SQLite data. In here I'm using ORMlite. But this is very similar situation for other ORMs.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
private long repoId;
#DatabaseField(columnName = "name")
private String name;
public long getRepoId() {
return repoId;
}
public String getName() {
return name;
}
public void setRepoId(long repoId) {
this.repoId = repoId;
}
public void setName(String name) {
this.name = name;
}
}
But by the time I'm trying to save these data in to SQLite database I already have data objects set in GSON model classes. It's kind a redundant thing copy object from GSON model and setting that values in to SQLite model. So I came up with below solution by trying to use single model class to represent both.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo implements Parcelable {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
#SerializedName("id")
#Expose
private Integer id;
#DatabaseField(columnName = "name")
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I have try this with different type of model class where it only had String type fields. Since GSON uses types like Integer,Boolean That stopping me from using same model for SQLite because database does not identify Integer as a type, in order to work it need to be int.
So what is the professional way to handle this ? Don't I have any other option other than going back to the method of creating two separate model class to represent SQLite and GSON.
Yout approach is absolutely correct, but i think you are putting too much effort reinventing the wheel
You can easily achieve the described task using Room

Categories

Resources