SwipeRefreshLayout with Live Json Data in Android


SwipeRefreshLayout with Live Json Data


Output Screen







Add dependency in Gradle:
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld">

<uses-permission-sdk-23 android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:name=".SingleTask"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Address.java
package com.example.helloworld;

import com.google.gson.annotations.SerializedName;

public class Address {
@SerializedName("street")
private String street;
@SerializedName("suite")
private String suite;
@SerializedName("city")
private String city;
@SerializedName("zipcode")
private String zipcode;
@SerializedName("geo")
private Geo geo;

public Address(String street, String suite, String city, String zipcode, Geo geo) {
this.street = street;
this.suite = suite;
this.city = city;
this.zipcode = zipcode;
this.geo = geo;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getSuite() {
return suite;
}

public void setSuite(String suite) {
this.suite = suite;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getZipcode() {
return zipcode;
}

public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}

public Geo getGeo() {
return geo;
}

public void setGeo(Geo geo) {
this.geo = geo;
}
}

Company.java
package com.example.helloworld;

import com.google.gson.annotations.SerializedName;

public class Company {
@SerializedName("name")
private String name;
@SerializedName("catchPhrase")
private String catchPhrase;
@SerializedName("bs")
private String bs;

public Company(String name, String catchPhrase, String bs) {
this.name = name;
this.catchPhrase = catchPhrase;
this.bs = bs;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCatchPhrase() {
return catchPhrase;
}

public void setCatchPhrase(String catchPhrase) {
this.catchPhrase = catchPhrase;
}

public String getBs() {
return bs;
}

public void setBs(String bs) {
this.bs = bs;
}
}

CustomUserAdapter.java
package com.example.helloworld;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class CustomUserAdapter extends RecyclerView.Adapter<CustomUserAdapter.MyView>{
private List<User> userList;

public CustomUserAdapter(List<User> userList) {
this.userList=userList;
}

@NonNull
@Override
public MyView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyView(view);
}

@Override
public void onBindViewHolder(@NonNull MyView holder, int position) {
User user = userList.get(position);
holder.tname.setText(user.getName());
holder.temail.setText(user.getEmail());
holder.tcompany.setText(user.getCompany().getName());
holder.twebsite.setText(user.getWebsite());

}

@Override
public int getItemCount() {
return userList.size();
}



class MyView extends RecyclerView.ViewHolder {
private TextView tcompany, tname, twebsite, temail;

public MyView(@NonNull View itemView) {
super(itemView);
tcompany = itemView.findViewById(R.id.company);
tname = itemView.findViewById(R.id.name);
twebsite = itemView.findViewById(R.id.website);
temail = itemView.findViewById(R.id.email);
}
}
}

Geo.java
package com.example.helloworld;

import com.google.gson.annotations.SerializedName;

public class Geo {
@SerializedName("lat")
private String lat;
@SerializedName("lng")
private String lng;

public Geo(String lat, String lng) {
this.lat = lat;
this.lng = lng;
}

public String getLat() {
return lat;
}

public void setLat(String lat) {
this.lat = lat;
}

public String getLng() {
return lng;
}

public void setLng(String lng) {
this.lng = lng;
}
}

MainActivity.java
package com.example.helloworld;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.SearchView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private UserOperation userOperation;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SingleTask singleTask = (SingleTask) getApplication();
userOperation = singleTask.getRetrofit().create(UserOperation.class);

initViews();


swipeRefreshLayout.setRefreshing(true);

swipeRefreshLayout.postDelayed(new Runnable() {
@Override
public void run() {
getUserData();
}
},2000);

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getUserData();
}
}, 2000);
}
});
swipeRefreshLayout.setColorSchemeResources(R.color.black, R.color.colorAccent,
         R.color.colorPrimaryDark);

}

private void initViews() {
swipeRefreshLayout = findViewById(R.id.myrefresh);

recyclerView = findViewById(R.id.myrec);

}

private void getUserData() {

userOperation.getAllUsers().enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Log.e("error", response.body() + "");
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
CustomUserAdapter customStudentAdapter = new CustomUserAdapter(response.body());
recyclerView.setAdapter(customStudentAdapter);
swipeRefreshLayout.setRefreshing(false);
}

@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(MainActivity.this, "There is some problem", Toast.LENGTH_SHORT).show();
}
});


}

}

SingleTask.java
package com.example.helloworld;

import android.app.Application;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SingleTask extends Application {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";

@Override
public void onCreate() {
super.onCreate();
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}

}

public Retrofit getRetrofit(){
return retrofit;
}
}

User.java
package com.example.helloworld;

import com.google.gson.annotations.SerializedName;

public class User {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("username")
private String username;
@SerializedName("email")
private String email;
@SerializedName("phone")
private String phone;
@SerializedName("website")
private String website;
@SerializedName("company")
private Company company;
@SerializedName("address")
private Address address;

public User(int id, String name, String username, String email, String phone,
                String website, Company company, Address address) {
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.phone = phone;
this.website = website;
this.company = company;
this.address = address;
}

public Company getCompany() {
return company;
}

public void setCompany(Company company) {
this.company = company;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getWebsite() {
return website;
}

public void setWebsite(String website) {
this.website = website;
}
}

UserOperation.java
package com.example.helloworld;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface UserOperation {
@GET("/users")
Call<List<User>> getAllUsers();
}

res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myrefresh">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/myrec"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

res/layout/item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardMaxElevation="10dp"
app:cardUseCompatPadding="true">


<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">


<TableRow>

<TextView
android:text="Name : "
android:textStyle="bold" />

<TextView android:id="@+id/name" />
</TableRow>

<TableRow>

<TextView
android:text="Email : "
android:textStyle="bold" />

<TextView android:id="@+id/email" />
</TableRow>

<TableRow>

<TextView
android:text="Company : "
android:textStyle="bold" />

<TextView android:id="@+id/company" />
</TableRow>

<TableRow>

<TextView
android:text="Website : "
android:textStyle="bold" />

<TextView android:id="@+id/website" />
</TableRow>
</TableLayout>


</androidx.cardview.widget.CardView>

res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>

<color name="darkyellow">#D19F09</color>
<color name="white">#fff</color>
<color name="black">#000</color>
</resources>

res/values/strings.xml
<resources>
<string name="app_name">RecyclerView Tutorial</string>
</resources>

res/values/styles.xml
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

No comments: