Retrofit returns null - android

I want to retrieve user details from an API, but when i place the text in a textview, it becomes blank.
My Object class
public class Obj {
/**
* settings : {"success":"1","message":"You have successfully logged in.","fields":["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]}
* data : [{"user_id":"108","email":"jk#grr.la","status":"Active","profile_image":"http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png","access_token":"144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635","phone":"","user_name":"Jack Kalsan","plate_number":"ABC1234","state_id":"2722","state":"Abakan","is_social":"","is_notification_enabled":"Yes","search_report_count":"69","remove_add":"0"}]
*/
private SettingsBean settings;
private List<DataBean> data;
public SettingsBean getSettings() {
return settings;
}
public void setSettings(SettingsBean settings) {
this.settings = settings;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class SettingsBean {
/**
* success : 1
* message : You have successfully logged in.
* fields : ["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]
*/
private String success;
private String message;
private List<String> fields;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
}
public static class DataBean {
/**
* user_id : 108
* email : jk#grr.la
* status : Active
* profile_image : http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png
* access_token : 144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635
* phone :
* user_name : Jack Kalsan
* plate_number : ABC1234
* state_id : 2722
* state : Abakan
* is_social :
* is_notification_enabled : Yes
* search_report_count : 69
* remove_add : 0
*/
private String user_id;
private String email;
private String status;
private String profile_image;
private String access_token;
private String phone;
private String user_name;
private String plate_number;
private String state_id;
private String state;
private String is_social;
private String is_notification_enabled;
private String search_report_count;
private String remove_add;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfile_image() {
return profile_image;
}
public void setProfile_image(String profile_image) {
this.profile_image = profile_image;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPlate_number() {
return plate_number;
}
public void setPlate_number(String plate_number) {
this.plate_number = plate_number;
}
public String getState_id() {
return state_id;
}
public void setState_id(String state_id) {
this.state_id = state_id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getIs_social() {
return is_social;
}
public void setIs_social(String is_social) {
this.is_social = is_social;
}
public String getIs_notification_enabled() {
return is_notification_enabled;
}
public void setIs_notification_enabled(String is_notification_enabled) {
this.is_notification_enabled = is_notification_enabled;
}
public String getSearch_report_count() {
return search_report_count;
}
public void setSearch_report_count(String search_report_count) {
this.search_report_count = search_report_count;
}
public String getRemove_add() {
return remove_add;
}
public void setRemove_add(String remove_add) {
this.remove_add = remove_add;
}
}}
My MainActivity.java
public class MainActivity extends AppCompatActivity {
List emList=new ArrayList();
List dataList=new ArrayList();
List userDets=new ArrayList();
ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;
String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;
String email;
Login login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emList.add(email);
proImg=(ImageView)findViewById(R.id.userProfilePic);
userName=findViewById(R.id.userName);
email=getIntent().getStringExtra("email");
login=ApiUtils.getLoginClass();
getUserData();
}
private void getUserData(){
Call<Obj.DataBean> call=login.getUserDetails();
call.enqueue(new Callback<Obj.DataBean>() {
#Override
public void onResponse(Call<Obj.DataBean> call, Response<Obj.DataBean> response) {
if(response.isSuccessful()) {
Obj.DataBean obj=response.body();
name=obj.getUser_name();
userName.setText(name);
}
}
#Override
public void onFailure(Call<Obj.DataBean> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}}
My interface
interface Login {
#GET("user_login_v1")
Call<Obj.DataBean> getUserDetails();}
My layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#e9edf6"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/userProfilePic"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyNameText"
android:layout_marginTop="50dp"
/>
<TextView
android:id="#+id/userID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyUserIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/emailID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyEmailText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStatusText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userPlateNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyPlateNumText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStateName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateNameText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStateID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userSearchReportCount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummySearchReportCountText"
android:layout_marginTop="20dp"
/>
</LinearLayout>
</ScrollView>
I want to display the details(like name,id,plate number etc) in different textviews. But it returns a blank string,ie null.
Here's my API in JSON format
Can someone help me?

Try this interface method.
#GET("user_login_v1")
Call<Obj> getUserDetails(#Query("email") String email,
#Query("password") String password);
and Call method in your MainActivity like this.
Call<Obj> call=login.getUserDetails(email,password);//email and password which user enter when he login in your device.
Feel free to ask more questions.

Related

hello, I want to list the cities and their temperatures with the recyclerview

I want to list the cities and their temperatures with the recyclerview via the api, but I can't see the data. I'm new to this, can you help me?
My Code:
public class MainActivity extends AppCompatActivity {
public static String apikey = "blablabla";
public static String lan = "55.5";
public static String lon="37.5";
public static String cnt="10";
private List<CountryData> list;
SearchView searchView;
RecyclerView countries;
TextView countryName, temperature;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchView = (SearchView) findViewById(R.id.searchView);
countries = (RecyclerView) findViewById(R.id.countries);
countryName = (TextView) findViewById(R.id.countryName);
temperature = (TextView) findViewById(R.id.temperature);
image = (ImageView) findViewById(R.id.image);
list = new ArrayList<>();
countries = findViewById(R.id.countries);
countries.setLayoutManager(new LinearLayoutManager(this));
countries.setHasFixedSize(true);
Adapter adapter = new Adapter(this, list);
countries.setAdapter(adapter);
ApiUtilities.getApiInterface().getCountryData(lan,lon,cnt,apikey).enqueue(new Callback<List<CountryData>>(){
#Override
public void onResponse(Call<List<CountryData>> call, Response<List<CountryData>> response) {
if (response.code() == 200) {
RetrofitModel retrofitModel = (RetrofitModel) response.body();
assert retrofitModel != null;
double temp = retrofitModel.main.temp - 273.15;
int tempToInt = (int) temp;
String country = retrofitModel.sys.country;
for(int i=0; i<list.size(); i++){
countryName.setText(country);
}
String temperatures = tempToInt + "°C";
temperature.setText(temperatures);
}
}
#Override
public void onFailure(Call<List<CountryData>> call, Throwable t) {
}
});
}
}
API CONTROLLER
public interface APIController {
String BASE_URL = "https://api.openweathermap.org/data/2.5/";
#GET("find?lat=55.5&lon=37.5&cnt=10&appid=3f8c9db425f5691cb59026f85546237e")
//Call<List<CountryData>> getCountryData();
Call<List<CountryData>> getCountryData(#Query("lat") String lat, #Query("lon") String lon, #Query("cnt") String cnt , #Query("APIKey") String apiKey);
}
RETROFİT MODEL
class RetrofitModel {
#SerializedName("list")
private String list;
private String country;
private String name;
private String temp;
#SerializedName("coord")
public Coord coord;
#SerializedName("sys")
public Sys sys;
#SerializedName("weather")
public ArrayList<Weather> weather = new ArrayList<Weather>();
#SerializedName("main")
public Main main;
public String getList() {
return list;
}
public void setList(String list) {
this.list = list;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public ArrayList<Weather> getWeather() {
return weather;
}
public void setWeather(ArrayList<Weather> weather) {
this.weather = weather;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public RetrofitModel(String list, String country, String name, String temp, Coord coord, Sys sys, ArrayList<Weather> weather, Main main) {
this.list = list;
this.country = country;
this.name = name;
this.temp = temp;
this.coord = coord;
this.sys = sys;
this.weather = weather;
this.main = main;
}
}
class Weather {
#SerializedName("id")
public int id;
#SerializedName("main")
public String main;
}
class Main {
#SerializedName("temp")
public float temp;
}
class Sys {
#SerializedName("country")
public String country;
public Sys(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
class Coord {
#SerializedName("lon")
public float lon;
#SerializedName("lat")
public float lat;
}
COUNTRY DATA
public class CountryData {
#SerializedName("list")
private String list;
private String country;
private String name;
private String temp;
public CountryData(String list, String country, String name, String temp) {
this.list = list;
this.country = country;
this.name = name;
this.temp = temp;
}
public String getList() {
return list;
}
public void setList(String list) {
this.list = list;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
}
XML CODES
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="#drawable/weather"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="12dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="30dp"
android:textColor="#color/black"
android:text="Country Name"
android:textSize="15dp" ></TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="30dp"
android:text="Temperature"
androi
d:textColor="#color/black"
android:textSize="15dp" >
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/countries"
tools:listitem="#layout/country_item_layout"
app:layoutManager="LinearLayoutManager"
/>
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="3dp"
android:layout_marginHorizontal="8dp"
android:layout_marginTop="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="7dp"
android:layout_marginHorizontal="15dp">
<TextView
android:id="#+id/countryName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentStart="true"
android:layout_marginEnd="30dp"
android:textColor="#color/black"
android:text="Türkiye"
android:layout_centerVertical="true"
android:gravity="center"
android:textSize="15dp" ></TextView>
<TextView
android:id="#+id/temperature"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="30dp"
android:textColor="#color/black"
android:text="Temperature"
android:layout_centerVertical="true"
android:gravity="center"
android:textSize="15dp" ></TextView>
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
hello, I want to list the cities and their temperatures with the recyclerview via the api, but I can't see the data. I'm new to this, can you help me?
You can easy to implement in Volley
implementation 'com.android.volley:volley:1.2.0'
In Java Code:
queue = Volley.newRequestQueue(this); // RequestQueue
String url = "https://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=3f8c9db425f5691cb59026f85546237e";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("list");
for (int i = 0 ; i<jsonArray.length() ; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
resultText.append("ID : " + id + "\nName : " + name + "\n\n"); // TextView
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}}
) ;
queue.add(request);
Output:

Get Data from API using retrofit

I need to get the details from the API and display them in textviews.
Here's my API in JSON format : https://imgur.com/a/WI98ymx
I need to get the data like username, user image, user phone number etc in Strings and display them in textviews.
How do i request all the fields and show the list in different textviews?
Here's my Login interface
package com.example.hb.loginapi;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
interface Login {
#POST("user_login_v1")
Call<ResObj> loginInfo(#Query("password") String password,
#Query("email") String email);
#GET("user_login_v1")
Call<List> getUserDetails();
}
Here's my ResObj class
package com.example.hb.loginapi;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class ResObj {
#SerializedName("settings")
private Settings settings;
#SerializedName("data")
private List<DataItem> data;
public void setSettings(Settings settings){
this.settings = settings;
}
public Settings getSettings(){
return settings;
}
public void setData(List<DataItem> data){
this.data = data;
}
public List<DataItem> getData(){
return data;
}
public class Settings {
#SerializedName("success")
private String success;
#SerializedName("message")
private String message;
#SerializedName("fields")
private List<String> fields;
public void setSuccess(String success) {
this.success = success;
}
public String getSuccess() {
return success;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
public List<String> getFields() {
return fields;
}
}
public class DataItem{
#SerializedName("user_name")
private String userName;
#SerializedName("search_report_count")
private String searchReportCount;
#SerializedName("access_token")
private String accessToken;
#SerializedName("profile_image")
private String profileImage;
#SerializedName("is_social")
private String isSocial;
#SerializedName("is_notification_enabled")
private String isNotificationEnabled;
#SerializedName("user_id")
private String userId;
#SerializedName("phone")
private String phone;
#SerializedName("plate_number")
private String plateNumber;
#SerializedName("state_id")
private String stateId;
#SerializedName("state")
private String state;
#SerializedName("email")
private String email;
#SerializedName("status")
private String status;
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
public void setSearchReportCount(String searchReportCount){
this.searchReportCount = searchReportCount;
}
public String getSearchReportCount(){
return searchReportCount;
}
public void setAccessToken(String accessToken){
this.accessToken = accessToken;
}
public String getAccessToken(){
return accessToken;
}
public void setProfileImage(String profileImage){
this.profileImage = profileImage;
}
public String getProfileImage(){
return profileImage;
}
public void setIsSocial(String isSocial){
this.isSocial = isSocial;
}
public String getIsSocial(){
return isSocial;
}
public void setIsNotificationEnabled(String isNotificationEnabled){
this.isNotificationEnabled = isNotificationEnabled;
}
public String getIsNotificationEnabled(){
return isNotificationEnabled;
}
public void setUserId(String userId){
this.userId = userId;
}
public String getUserId(){
return userId;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public void setPlateNumber(String plateNumber){
this.plateNumber = plateNumber;
}
public String getPlateNumber(){
return plateNumber;
}
public void setStateId(String stateId){
this.stateId = stateId;
}
public String getStateId(){
return stateId;
}
public void setState(String state){
this.state = state;
}
public String getState(){
return state;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return status;
}
}
}
My Layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#e9edf6"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/userProfilePic"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyNameText"
android:layout_marginTop="50dp"
/>
<TextView
android:id="#+id/userID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyUserIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/emailID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyEmailText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStatusText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userPlateNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyPlateNumText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStateName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateNameText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userStateID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummyStateIDText"
android:layout_marginTop="20dp"
/>
<TextView
android:id="#+id/userSearchReportCount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/fnavyblue"
android:textSize="20sp"
android:text="DummySearchReportCountText"
android:layout_marginTop="20dp"
/>
</LinearLayout>
</ScrollView>
My MainActivity.java
public class MainActivity extends AppCompatActivity {
List emList=new ArrayList();
List dataList=new ArrayList();
List userDets=new ArrayList();
ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;
String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;
String email;
Login login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emList.add(email);
userName=findViewById(R.id.userName);
email=getIntent().getStringExtra("email");
login=ApiUtils.getLoginClass();
getUserData();
}
private void getUserData(){
Call<List> call=login.getUserDetails();
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
List resObj=(List)response.body();
for(int i=0;i<resObj.size();i++){
Log.e("data",resObj.get(i).toString());
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
I don't know what to write in the onResponse() method.
change the for loop.
List<DataItem> items = resObj.getData();
for(int i=0;i<items.size();i++){
Log.e("data",items.get(i).getUserName()); // like this you can access other values in the items list
}
Update api interface method
#GET("user_login_v1")
Call<ResObj> getUserDetails();
Update your getUserData() method
private void getUserData(){
Call<ResObj> call=login.getUserDetails();
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
ResObj resObj=(ResObj)response.body();
DataItem user=reObj.getData().get(0);
//set value on yout text views
userName.setText(user.getUserName())
userID.setText(user.getUserId())
//....
}
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
Create ResObj.class using Android studio plugin "GsonFormat"
It will create a perfect POJO class for your APICall, just past the API GET response from Postman.
It will create a suitable POJO class, from which you can simply call
private void callApi() {
Log.e(TAG, "callApi: inside apiCall");
Call<List> call =
login.getUserDetails();
call.enqueue(new Callback<List>() {
#Override
public void onResponse(Call<List> call, #NonNull Response<List>response) {
List items = response.body();
items = list.data;
String user_id = items.getUserID();
}
#Override
public void onFailure(Call<LiveMatches> call, Throwable t) {
}
call callApi() method where you want to get data;
This method and method will not work if you copy and paste it you need to alter it according to your POJO class but this will provide help
Also add your layout and activity code to give us context

Loop with dataBinding - android

I have two models for get values from service :
First model FieldStudyList.class:
public class FieldStudyList {
#SerializedName("result")
#Expose
private List<ResultFieldStudyList> result = null;
#SerializedName("status")
#Expose
private Integer status;
public List<ResultFieldStudyList> getResult() {
return result;
}
public void setResult(List<ResultFieldStudyList> result) {
this.result = result;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
Second model ResultFieldStudyList.class:
public class ResultFieldStudyList {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("introtext")
#Expose
private String introtext;
#SerializedName("title")
#Expose
private String title;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIntrotext() {
return introtext;
}
public void setIntrotext(String introtext) {
this.introtext = introtext;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I am using from dataBinding in my xml for show values but I can't show them :
<data>
<variable
name="listItems"
type="xxx.xx.models.FieldStudyList" />
</data>
<android.support.v7.widget.CardView
android:id="#+id/card_lstItemStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="7dp"
card_view:cardElevation="7dp"
card_view:cardMaxElevation="7dp"
card_view:contentPadding="0dp">
<TextView
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{listItems.result.iterator() ???}"<=== I can't show title here ?
android:textSize="20sp" />
</android.support.v7.widget.CardView>

Setting text of multiple TextViews through custom adapter

I'm having trouble setting the text of multiple textviews in a custom list layout with a custom adapter. Here is my list item layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dp"
android:contentDescription="TODO"
android:src="#drawable/blue_circle" />
<TextView
android:id="#+id/short_content"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:text="content"
android:singleLine="true"
android:textSize="12sp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/short_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Title"
android:textSize="16sp" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/short_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/icon"
android:gravity="right"
android:text="date"
android:textSize="13sp" />
Here is my adapter:
public class MessageAdapter extends ArrayAdapter<TextContent> {
public MessageAdapter(Context context, int textViewResourceId){
super(context, textViewResourceId);
}
public MessageAdapter(Context context, int textViewResourceId, List<TextContent> items){
super(context, textViewResourceId, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater;
inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.messages_layout, null);
}
TextContent p = getItem(position);
if(p != null) {
TextView textViewShortContent = (TextView) view.findViewById(R.id.short_content);
TextView textViewTitle = (TextView) view.findViewById(R.id.title);
TextView textViewDate = (TextView) view.findViewById(R.id.date);
if (textViewShortContent != null) {
textViewShortContent.setText("Short Content");
}
if (textViewTitle != null) {
textViewTitle.setText("TITLE");
}
if (textViewDate != null) {
textViewDate.setText("DATE");
}
}
return view;
}
}
here is my textContent class:
public class TextContent implements Serializable{
private String GUID, created, modified, deleted, name, message, title, shortContent, fullContent, author, language, person;
public TextContent(){
}
public TextContent(String GUID, String created, String modified, String deleted, String name, String message, String title,
String shortContent, String fullContent, String author, String language, String person) {
this.GUID = GUID;
this.created = created;
this.modified = modified;
this.deleted = deleted;
this.name = name;
this.message = message;
this.title = title;
this.shortContent = shortContent;
this.fullContent = fullContent;
this.author = author;
this.language = language;
this.person = person;
}
public String getGUID() {
return GUID;
}
public String getCreated() {
return created;
}
public String getModified() {
return modified;
}
public String getDeleted() {
return deleted;
}
public String getName() {
return name;
}
public String getMessage() {
return message;
}
public String getTitle() {
return title;
}
public String getShortContent() {
return shortContent;
}
public String getFullContent() {
return fullContent;
}
public String getAuthor() {
return author;
}
public String getLanguage() {
return language;
}
public String getPerson() {
return person;
}
public void setGUID(String GUID) {
this.GUID = GUID;
}
public void setCreated(String created) {
this.created = created;
}
public void setModified(String modified) {
this.modified = modified;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public void setName(String name) {
this.name = name;
}
public void setMessage(String message) {
this.message = message;
}
public void setTitle(String title) {
this.title = title;
}
public void setShortContent(String shortContent) {
this.shortContent = shortContent;
}
public void setFullContent(String fullContent) {
this.fullContent = fullContent;
}
public void setAuthor(String author) {
this.author = author;
}
public void setLanguage(String language) {
this.language = language;
}
public void setPerson(String person) {
this.person = person;
}
}
and here is where I instantiate my adapter
listView = (ListView) getView().findViewById(R.id.list_view_messages);
MessageAdapter adapter = new MessageAdapter(context, R.layout.messages_layout, textContentList);
listView.setAdapter(adapter);
The only thing that gets displayed is the getShortContent but not getTitle or getCreated for some reason. I am 100% certain that text has been set for all fields of the textContent.
I figured it out. The textViews in my layout was overlapping so the content from the other textviews got hidden behind.

Android Data binding Error: HOw Can we bind ImageView If we get List of Images from model

I am Facing Problem to attach ImageView with model....I'm getting List of images...and after attaching with layout getting Image Setter Error... Thanks
My PostImageMOdel
public class PostImageModel {
#SerializedName("postimages_id")
long imageId;
#SerializedName("post_id")
long postId;
#SerializedName("post_image")
String image;
public long getImageId() {
return imageId;
}
public long getPostId() {
return postId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
and Here is my PostModel
public class PostModel {
#SerializedName("post_id")
#Expose
private String postId;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("date")
#Expose
private String date;
#SerializedName("images")
#Expose
private List<PostImageModel> images = new ArrayList<>();
#SerializedName("user")
#Expose
private UserModel user;
/**
* #return The postId
*/
public String getPostId() {
return postId;
}
/**
* #param postId The post_id
*/
public void setPostId(String postId) {
this.postId = postId;
}
/**
* #return The userId
*/
public String getUserId() {
return userId;
}
/**
* #param userId The user_id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* #return The date
*/
public String getDate() {
return date;
}
/**
* #param date The date
*/
public void setDate(String date) {
this.date = date;
}
public List<PostImageModel> getImages() {
return images;
}
public void setImages(List<PostImageModel> images) {
this.images = images;
}
public UserModel getUser() {
return user;
}
}
My Layout where I am going to bind
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="house"
type="com.gulam.dreamhome.model.PostModel" />
</data>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="170dp"
android:layout_weight="2"
android:background="#drawable/home8"
tools:showIn="#layout/item_home_picture">
<ImageView
android:id="#+id/img1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:onClick="ClickONImage"
android:src="#{house.images[0]}" />
<TextView
android:id="#+id/price"
style="#style/item_image_text_price"
android:layout_above="#+id/city"
android:text="#{house.price, default=price}"
android:textSize="20sp"/>
<TextView
android:id="#+id/city"
android:layout_alignParentBottom="true"
style="#style/item_image_text_city"
android:text="#{house.city, default=City}"
android:textSize="15sp" />
</RelativeLayout>
</layout>
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'android:src' with parameter type com.gulam.dreamhome.model.PostImageModel on android.widget.ImageView.

Categories

Resources