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
Related
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:
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.
I'm trying to put my firestore data within a recyclerview in Android. The app comes up with no errors, however no data shows up.
public class Diseaselist extends AppCompatActivity {
private TextView textView;
private FirebaseFirestore mDatabaseRef;
private Query mChartsQuery;
private RecyclerView mRecycler;
private FirebaseAuth mAuth;
private FirestoreRecyclerAdapter<Upload, ProductViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diseaselist);
RecyclerView recyclerView = findViewById(R.id.goodmeme);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
String useruid = currentUser.getUid();
Query query = rootRef.collection("users").document(useruid).collection("diagnoses")
.orderBy("disease", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Upload> options = new FirestoreRecyclerOptions.Builder<Upload>()
.setQuery(query, Upload.class)
.build();
adapter = new FirestoreRecyclerAdapter<Upload, ProductViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, int position, #NonNull Upload productModel) {
holder.setProductName(productModel.getDisease());
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View views = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_diseaselist, parent, false);
return new ProductViewHolder(views);
}
};
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
private class ProductViewHolder extends RecyclerView.ViewHolder {
private android.view.View view;
ProductViewHolder(android.view.View itemView) {
super(itemView);
view = itemView;
}
void setProductName(final String productName) {
CardView cview =view.findViewById(R.id.cardview);
textView = view.findViewById(R.id.texty);
textView.setText(productName);
cview.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
Toast.makeText(getApplicationContext(), productName, Toast.LENGTH_SHORT).show();
}
});
}
}
Layout File:
<?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"
android:padding="16dp"
tools:context=".Diseaselist"
tools:orientation="vertical">
<TextView
android:id="#+id/texty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="30sp"/>
<android.support.v7.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:id="#+id/person_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/person_photo"
android:textSize="30sp" />
<TextView
android:id="#+id/person_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/person_name"
android:layout_toRightOf="#+id/person_photo" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/goodmeme"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Firestore structure Firestore Structure Screenshot 2
Upload Class code:
package com.Provendor.Provendor;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.Calendar;
public class Upload implements Parcelable {
private String mName;
private String mImageUrl;
private String mdisease;
private String mdate;
private float mconfidence;
#Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeFloat(mconfidence);
out.writeString(mName);
out.writeString(mImageUrl);
out.writeString(mdisease);
out.writeString(mdate);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Upload> CREATOR = new Parcelable.Creator<Upload>() {
public Upload createFromParcel(Parcel in) {
return new Upload(in);
}
public Upload[] newArray(int size) {
return new Upload[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Upload(Parcel in) {
mconfidence = in.readInt();
mName = in.readString();
mImageUrl = in.readString();
mdisease = in.readString();
mdate = in.readString();
}
public Upload() {
mName= ""; //empty constructor needed
}
public Upload(String name, String imageUrl, String disease, float confidence) {
if (name.trim().equals("")) {
name = "No Name";
}
mdisease=disease;
mdate=java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
mName = name;
mImageUrl = imageUrl;
mconfidence=confidence;
}
public String getName() {
return mName;
}
public String getDisease() {
return mdisease;
}
public float getConfidence() {
return mconfidence;
}
public String getDate() {
return mdate;
}
public void setName(String name) {
mName = name;
}
public void setdate() {
mdate=java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
}
public void setDisease(String disease) {
mdisease = disease;
}
public void setConfidence(float confidence) {
mconfidence = confidence;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
}
I expect the output to produce a list of diseases based on the firestore collection, however the recyclerview is left empty. When attached to debug, no errors come up! Thanks for looking this over!
You aren't getting anything from the database because the name of your fields inside the Upload class are different than the name of the fields that exist in the database. Both should match. To solve this, you either change all the name of your fields inside your Upload class to match the properties that exist in the database or your can use annotations. Because I see that you are using private fields and public getters, you should use the PropertyName annotation only in front of the getter, for instance your getName() getter should look like this:
#PropertyName("name")
public String getName() {
return mName;
}
I'm new to retrofit2 android. I'm trying to work around an app which displays earthquake information using retrofit and RecyclerView. But I'm unable to display any data fetch from the URL in JSON format.
Most of the times I'm getting No adapter attached; skipping layout error. I've searched a lot but didn't get it resolve.
I'm using HttpLoggingInterceptor to see response. Response body of my JSON data is showing in Verbose of Logcat but not in RecyclerView.
Sometimes no error nothing in verbose everything blank even app is blank no data.
Help me please with my issue.
URL from which I'm fetching data. I limit it to 2 so that you can see it clearly.
https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=2
This is my MainActivity.
public class EarthquakeActivity extends AppCompatActivity {
private static final String TAG = EarthquakeActivity.class.getSimpleName();
private RecyclerView recyclerView;
private List<Feature> featureList;
private DataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"onCreate() method called...");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_earthquke);
recyclerView = findViewById(R.id.earthquake_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClientBuilder.addInterceptor(loggingInterceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://earthquake.usgs.gov/")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClientBuilder.build())
.build();
EarthquakeRequestInterface requestInterface = retrofit.create(EarthquakeRequestInterface.class);
Call<EarthquakeResponse> responseCall =requestInterface.getJSON("geojson");
responseCall.enqueue(new Callback<EarthquakeResponse>() {
#Override
public void onResponse(Call<EarthquakeResponse> call, Response<EarthquakeResponse> response) {
if (response.isSuccessful()){
EarthquakeResponse earthquakeResponse = response.body();
adapter = new DataAdapter(earthquakeResponse.getFeatures());
recyclerView.setAdapter(adapter);
}
else {
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<EarthquakeResponse> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
}`
This is my adapter class.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private List<Feature> features;
public DataAdapter(List<Feature> features1) {
this.features = features1;
}
#NonNull
#Override
public DataAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.earthquake_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.earthquakeMag.setText(features.get(i).getProperties().getMag().toString());
viewHolder.earthquakePlace.setText(features.get(i).getProperties().getPlace());
viewHolder.earthquakeUrl.setText(features.get(i).getProperties().getUrl());
}
#Override
public int getItemCount() {
return features.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView earthquakeMag,earthquakePlace,earthquakeUrl;
public ViewHolder(View view) {
super(view);
earthquakeMag = view.findViewById(R.id.earthquake_mag);
earthquakePlace = view.findViewById(R.id.earthquake_place);
earthquakeUrl = view.findViewById(R.id.earthquake_url);
}
}
}
This is my API interface.
public interface EarthquakeRequestInterface {
#GET ("fdsnws/event/1/query")
Call<EarthquakeResponse> getJSON(#Query("format") String format);
}
This is my Response java class (POJO or Model class).
public class EarthquakeResponse {
#SerializedName("type")
#Expose
private String type;
#SerializedName("metadata")
#Expose
private Metadata metadata;
#SerializedName("features")
#Expose
private List<Feature> features = null;
#SerializedName("bbox")
#Expose
private List<Double> bbox = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
public List<Double> getBbox() {
return bbox;
}
public void setBbox(List<Double> bbox) {
this.bbox = bbox;
}
}
This is my Feature class (POJO class)
public class Feature {
#SerializedName("type")
#Expose
private String type;
#SerializedName("properties")
#Expose
private Properties properties;
#SerializedName("geometry")
#Expose
private Geometry geometry;
#SerializedName("id")
#Expose
private String id;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
This is Properties Java class (POJO class). It contains the data I'm interested in. I reduce it to only 3 for checking my code is working or not.
public class Properties {
#SerializedName("mag")
#Expose
private Double mag;
#SerializedName("place")
#Expose
private String place;
#SerializedName("url")
#Expose
private String url;
#SerializedName("detail")
#Expose
private String detail;
public Double getMag() {
return mag;
}
public void setMag(Double mag) {
this.mag = mag;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDetail() {
return detail;
}
}
There are other POJO classes like Geometry, Metadata which are present in JSON response but I'm not interested in it.
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for a list of earthquakes -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/earthquake_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is my custom adapter layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/earthquake_layout"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="16dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/earthquake_mag"
android:layout_gravity="top"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#android:color/black"
android:paddingLeft="10dp"
android:paddingRight="10dp"
tools:text="Place"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/earthquake_place"
android:layout_gravity="top"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#android:color/black"
android:paddingLeft="10dp"
android:paddingRight="10dp"
tools:text="Place"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/earthquake_url"
android:layout_gravity="top"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#android:color/black"
android:paddingLeft="10dp"
android:paddingRight="10dp"
tools:text="Place"
/>
</LinearLayout>
Sorry for my bad English or any improper way of asking a question. I'm new to stackoverflow. I recently sign up.
Please really need some serious help to overcome this.
Try to set the adapter outside the Retrofit method. Something like this:
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mItems = new ArrayList<Feature>;
adapter = new DataAdapter(mItems);
recyclerView.setAdapter(adapter);
// .. other code
EarthquakeRequestInterface requestInterface = retrofit.create(EarthquakeRequestInterface.class);
Call<EarthquakeResponse> responseCall =requestInterface.getJSON("geojson");
responseCall.enqueue(new Callback<EarthquakeResponse>() {
#Override
public void onResponse(Call<EarthquakeResponse> call, Response<EarthquakeResponse> response) {
if (response.isSuccessful()){
EarthquakeResponse earthquakeResponse = response.body();
mItems.addAll(earthquakeResponse.getFeatures());
adapter.notifyDatasetChanged();
} else {
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<EarthquakeResponse> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
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>