Gson, parse object of arrays using retrofit - android

I have this server response:
{ "result" : true , "content" : {
"files" : [],
"filesNames" : [],
"folders" : []
}
}
How can i create a gson object to make retrofit adapt that response? Because this doesn't seem to work(i only need files and folders):
public class GetUserFilesAnswer {
public boolean result;
public List<Integer> files;
public List<String> folders;
}
client.getUserFiles(email, token, path, new Callback<GetUserFilesAnswer>() {
#Override
public void success(GetUserFilesAnswer getUserFilesAnswer, Response response) {
}
#Override
public void failure(RetrofitError error) {
}
});

Try this model:
public class GetUserFilesAnswer {
public static class Content {
public List<Integer> files;
public List<String> folders;
}
public boolean result;
public Content content;
}

Related

Return Observable<Song> from an object of SongResponse that contains a List<Song>

I have a class SongResponse:
public class SongResponse implements Parcelable {
#SerializedName("token")
public String token;
#SerializedName("items")
public List<Song> songList;
}
#GET("songs")
Observable<SongResponse> getSongs(#Query("token") String token)
In the manager class, I want to return an Observable by used the request above
public Observable<Song> syncSongs(token) {
return mSongService.getSongs(token);
....
#Override
public Observable<Song> call(List<Song> songs) {
return mDatabaseHelper.setSongs(songs);
}
}
syncSongs will call another Observer to insert songs in the database.
I used RxAndroid 2. I try to find about .map and .flatMapIterable, but don't result my problem. Could you help me complete this function?
You can try something like that :
public Observable syncSongs(token) {
return mSongService.getSongs(token).flatMap(new Function<SongResponse, ObservableSource<List<Song>>() {
#Override
public ObservableSource<List<Song>> apply(#io.reactivex.annotations.NonNull SongResponse songResponse) throws Exception {
return Observable.just(songResponse.getSongList()); //some changes here
}
}).flatMapIterable(new Function<List<Song>, Iterable<? extends Song>>() {
#Override
public Iterable<? extends Song> apply(List<Song> songs) throws Exception {
return songs;
}
}).flatMap(new Function<Song, Observable<Song>>() {
#Override
public Observable<Song> apply(final Song song) throws Exception {
return Observable.just(song);
}
});
}
Hope this helps.

How to get List<String> from JSON list using Retrofit 2?

I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like
[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}].
tried with Retrofit Scalars.
Response as
[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]
but error detecting as:
Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]*
Any better way to retrieve the list of strings from the JSON?
This is sample code :
GroupService groupService = createService(GroupService.class);
Call<List<Groups>> groupCall = groupService.getGroups();
groupCall.enqueue(new Callback<List<Groups>>() {
#Override
public void onResponse(retrofit.Response<List<Groups>> response, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
Interfaces :
public interface GroupService {
#GET("<URL>")
Call<List<Groups>> getGroups();
}
Also create model name Groups.
I hope this helps you.
Make the following model class (parcelable)
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example implements Parcelable {
#SerializedName("bgroup")
#Expose
private String bgroup;
public String getBgroup() {
return bgroup;
}
public void setBgroup(String bgroup) {
this.bgroup = bgroup;
}
protected Example(Parcel in) {
bgroup = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(bgroup);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Example> CREATOR = new Parcelable.Creator<Example>() {
#Override
public Example createFromParcel(Parcel in) {
return new Example(in);
}
#Override
public Example[] newArray(int size) {
return new Example[size];
}
};
}
Than create interface class like this
public interface ApiService {
#GET("<URL>")
Call<List<Example>> getBloodGroups();
}
And finally call retrofit like following :
Call<List<Example>> call = new RestClient(this).getApiService()
.getBloodGroups();
call.enqueue(new Callback<List<Example>>() {
#Override
public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {
}
#Override
public void onFailure(Call<List<Example>> call, Throwable throwable) {
}
});

How to store parametrized listeners in list?

I have a listener:
public interface OnCompleteListener<T> {
void onComplete(T data);
}
I store it in list:
private List<OnCompleteListener<?>> mListeners = new ArrayList<>();
// ...
public void addType1Listener() {
addListener(new OnCompleteListener<Type1>() {
//...
});
}
public void addType2Listener() {
addListener(new OnCompleteListener() {
//...
});
}
private <T> void addListener(OnCompleteListener<T> listener) {
mListeners.add(listener);
}
I am trying to get it by this way:
public <T> OnRequestsCompleteListener<T> get(int i) {
return (OnRequestsCompleteListener<T>) mListeners.get(i);
}
Type1 and Type2 have no parent class and cannot have.
But I get 'unchecked cast' warning. How to get it correctly?
Instead of specifying genetic T in a method, you need a class with generic T
public class ListenerCollection <T> {
private List<OnCompleteListener<T>> mListeners = new ArrayList<OnCompleteListener<T>>();
public void addListener(OnCompleteListener<T> listener) {
mListeners.add(listener);
}
public OnCompleteListener<T> get(int i) {
return mListeners.get(i);
}
}
Suppose you have a class OnRequestCompleteListener, implemening OnCompleteListener<String>. Then you do:
ListenerCollection<String> lcollection;
...........
OnRequestCompleteListener newListener = (OnRequestCompleteListener) lcollection.get(i);
That doesn't give any warning.

How to get JSON array from web api with retrofit and active android

I have an web api which gives me array of partners and it looks like this:
[
"partner1",
"partner2",
"partner3",
"....",
"parner222"
]
I have Table partners (ActiveAndroid) in which I would like to save all partners from api.
#Table(name = "Partners")
public class Partners extends Model {
#Column(name = "Name")
String name;
public Partners() {}
public Partners(String name) {
this.name = name;
}
}
Here is my Pojo model class:
public class Partners {
#SerializedName("name")
#Expose
private List<String> name = new ArrayList<String>();
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
}
This is my interface
public interface APIService {
#GET("Partners")
Call<Partners> getPartners();
}
And this is my APIHelper with api url
public class APIHelper {
public static APIService apiService;
public static APIService getApiService() {
if (apiService == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://part-oflink.domain.com/partners.json/")
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}
}
And this is Fragment where I have an Button on which I would like to implement onClick method to get data from API and save it into Partners table.
public class DownloadMain extends Fragment implements Callback<Partners> {
private Button dloadPartners;
private Call<Partners> callPartners;
public static APIService apiService;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
callPartners.enqueue(this);
return view;
}
Button.OnClickListener btnListener = (new View.OnClickListener() {
#Override
public void onClick(View v) {
//here I need to implement that on click downloads me data
// and save it into my Partners table
}
});
#Override
public void onResponse(Call<Partners> call, Response<Partners> response) {
//here I'm trying to put api response into array list
if (response.body() != null) {
ArrayList<String> partnersList = new ArrayList<>();
partnersList = response.body();
}
}
#Override
public void onFailure(Call<Partners> call, Throwable t) {
}
}
And now I have stuck. I would like to implement onClick Button method to get data from API. In onResponse() method I'm trying to put data into ArrayList to check if data is recieved. And also I would like to save this data into my table partners.
I would be grateful if someone could help me or guide me to fix this. This is first time I'm doing with retrofit and api.
Can somebody help me or guide me to successfully get data from API and save it into table Partners?
The way you are trying to parse the JSON string(array of partners) is not the appropriate. Your JSON should like this:
{
"partners":
["partner1", "partner2", "partner3", ...]
}
And the POJO model class should be:
class Partners{
private List<String> partners;
public Partners(){}
public void setList(List<String> partners) {
this.partners = partners;
}
public List<String> getList() {
return this.partners;
}
//setter and getter methods
}
If the response is not empty then for printing the values:
for(Partner partner: response){
Log.d("Partner Name",partner.name);
}
And if you are using any ORM for the database, then call its DAO and pass the values to save in the DB.

Android Retrofit: adding the list from callback into class

im using Retrofit for the first time here.
I want to put my List from the Callback to UsersData class. Its not possible. But if i erase everything from UsersData and put the content from Profile in UsersData then it works. But it doesn´t fulfill my needs. I need to be able to put List from Callback to UsersData class.
Thank you in advantage
In my fragment
App.getRestClient().getAttendanceService().getUsers(48, new Callback<List<UsersData>>() {
#Override
public void success(List<UsersData> usersDao, Response response) {
String ble = usersDao.get(0).getResults().get(0).getFirstName();
Toast.makeText(getActivity(),ble, Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError error) {
}
});
App
public class App extends Application {
private static RestClient restClient;
public static App instance = null;
public static Context getInstance() {
if (null == instance) {
instance = new App();
}
return instance;
}
#Override
public void onCreate(){
super.onCreate();
restClient = new RestClient();
}
public static RestClient getRestClient(){
return restClient;
}
}
And my client
public class RestClient {
private static final String BASE_URL = "www.Link_to_json.com" ;
private AttendanceService attendanceService;
public RestClient()
{
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
//.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(BASE_URL)
//.setClient(new OkClient(new OkHttpClient()))
//.setConverter(new GsonConverter(gson))
.build();
attendanceService = restAdapter.create(AttendanceService.class);
}
public AttendanceService getAttendanceService()
{
return attendanceService;
}
}
My interface
public interface AttendanceService {
#GET("/GetUsers")
void getUsers(#Query("companyId") int i, Callback<List<UsersData>> u );
}
and UsersData
public class UsersData {
private List<Profile> results;
public List<Profile> getResults() {
return results;
}
}
Profile data class:
public String firstName;
public String lastname;
public int userId;
public String userNameId;
...
Example of json:
[
{
"AttendanceDate":null,
"AttendanceStatus":1,
"AttendanceStatusDescription":null,
"CompanyId":48,
"Email":"",
"FirstName":"Sindri",
"Gender":1,
"Gsm":"",
"Id":259,
"LastName":"yeh",
"MiddleName":"",
"Role":0,"UserId":"corp\\marg"
},{
"AttendanceDate":null,
"AttendanceStatus":1,
"AttendanceStatusDescription":null,
"CompanyId":48,
"Email":"",
"FirstName":"David",
"Gender":1,
"Gsm":"",
"Id":165,
"LastName":"Guðmundsson",
"MiddleName":"",
"Role":0,"UserId":"corp\\marg"
}
]
Try wrapping the list/array inside the UsersData class itself:
public interface AttendanceService {
#GET("/GetUsers")
void getUsers(#Query("companyId") int i, Callback<UsersData> u );
}
UsersData.java:
public class UsersData {
public Profile[] results;
public class Profile {
public String firstName;
public String lastname;
public int userId;
public String userNameId;
}
}
In the callback you can then iterate over the results array.
As UMESH0492 comments you should also name your list in the JSON:
{
"profile": [
{
"AttendanceDate":null,
"AttendanceStatus":1,
"AttendanceStatusDescription":null,
"CompanyId":48,
"Email":"",
"FirstName":"Sindri",
"Gender":1,
"Gsm":"",
"Id":259,
"LastName":"yeh",
"MiddleName":"",
"Role":0,"UserId":"corp\\marg"
},{
"AttendanceDate":null,
"AttendanceStatus":1,
"AttendanceStatusDescription":null,
"CompanyId":48,
"Email":"",
"FirstName":"David",
"Gender":1,
"Gsm":"",
"Id":165,
"LastName":"Guðmundsson",
"MiddleName":"",
"Role":0,"UserId":"corp\\marg"
}
]
}

Categories

Resources