X

Android swipe to refresh view || Pull down refresh

 

Every app needs to fetch data on user interaction that may be using a refresh button or may be a swipe to refresh view or pull down to refresh view. In this blog we can get through Android swipe to refresh view tutorial.

In almost every app like youtube, facebook, twitter, instagram, gmail, yahoo and many more apps not only social media but also in news related apps where there is option to refresh we can find this view.

Swipe to refresh view is not used only for list views but also for updating all the components present on the screen.

In general we use android phone, there to answer a call or reject we use the same swipe to refresh view.Now a days to delete a row in list view and undo them also we use.

In this tutorial i will be using api which will be parsing dynamic results.

All the data, information, images got from

API : https://randomuser.me

 

 

Add required dependencies before getting started also make sure you are providing latest versions to avoid abnormal crashes in app due to deprecated codes.

 

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation ("com.github.bumptech.glide:glide:4.8.0") {
        exclude group: "com.android.support"
    }
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

 

 

activity_main.xml

Add a swipe to refresh view to the layout this is the key aspect of this tutorial

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/simpleSwipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

 

We are making a simple view by use of multiple textviews and a imageview to show user details in real time usage you may use accordingly.

 

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="30dp">

    <ImageView
        android:id="@+id/img_user"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginBottom="20dp"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/tv_dob"
        android:layout_below="@+id/img_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_age"
        android:layout_below="@+id/img_user"
        android:layout_toRightOf="@+id/tv_dob"
        android:gravity="right"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_gender"
        android:layout_below="@+id/tv_dob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_first_name"
        android:layout_below="@+id/tv_gender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_last_name"
        android:layout_below="@+id/tv_gender"
        android:layout_toRightOf="@+id/tv_first_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_address"
        android:layout_below="@+id/tv_first_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Address :  "
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_location"
        android:layout_below="@+id/tv_first_name"
        android:layout_toRightOf="@+id/tv_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_email"
        android:layout_below="@+id/tv_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tv_cell"
        android:layout_below="@+id/tv_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold"/>

</RelativeLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:background="#ffffff">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/simpleSwipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="30dp">

            <ImageView
                android:id="@+id/img_user"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:layout_marginBottom="20dp"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/tv_dob"
                android:layout_below="@+id/img_user"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_age"
                android:layout_below="@+id/img_user"
                android:layout_toRightOf="@+id/tv_dob"
                android:gravity="right"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_gender"
                android:layout_below="@+id/tv_dob"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_first_name"
                android:layout_below="@+id/tv_gender"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/tv_last_name"
                android:layout_below="@+id/tv_gender"
                android:layout_toRightOf="@+id/tv_first_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/tv_address"
                android:layout_below="@+id/tv_first_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="Address :  "
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/tv_location"
                android:layout_below="@+id/tv_first_name"
                android:layout_toRightOf="@+id/tv_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/tv_email"
                android:layout_below="@+id/tv_location"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/tv_cell"
                android:layout_below="@+id/tv_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textStyle="bold"/>

        </RelativeLayout>


    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.constraint.ConstraintLayout>

 

MainActivity.java

 

Initialize all the views in oncreate using init() method. Here you may also refer to databinding which is the fastest way to fetch the bind the UI components to the screen.

private void init() {

    img_user = findViewById(R.id.img_user);
    tv_dob = findViewById(R.id.tv_dob);
    tv_age = findViewById(R.id.tv_age);
    tv_gender = findViewById(R.id.tv_gender);
    tv_first_name = findViewById(R.id.tv_first_name);
    tv_last_name = findViewById(R.id.tv_last_name);
    tv_location = findViewById(R.id.tv_location);
    tv_email = findViewById(R.id.tv_email);
    tv_cell = findViewById(R.id.tv_cell);
    swipeRefreshLayout = findViewById(R.id.simpleSwipeRefreshLayout);


    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {

            fetchData();
            swipeRefreshLayout.setRefreshing(false);
        }
    });

}

 

Fetch data using retrofit library here we have onResponse and onFailure states for handling the result.

In onSuccess store the data to the respective data model class User and populate it using swipe to refresh view.

In onFailure show a toast stating the reason.

 

private void fetchData() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    Api api = retrofit.create(Api.class);

    Call<User> call = api.getstatus();

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {

            User user = (User) response.body();

            setData(user);

        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {

            Toast.makeText(MainActivity.this, "" + t.getMessage().toString(), Toast.LENGTH_SHORT).show();

        }
    });
}

 

Set the image to the views using glide for image view in realtime you may use a for loop to parse the data and set it to the views

public void setData(User user) {

    Glide.with(this)
            .load(user.getResults().get(0).getPicture().getLarge())
            .into(img_user);

    tv_dob.setText("DOB :   "+user.getResults().get(0).getDob().getDate());
    tv_age.setText("Age :   "+user.getResults().get(0).getDob().getAge());
    tv_gender.setText("Gender :   "+user.getResults().get(0).getGender());
    tv_first_name.setText("Name :   "+user.getResults().get(0).getName().getFirst());
    tv_last_name.setText("  "+user.getResults().get(0).getName().getLast());
    tv_location.setText(""+user.getResults().get(0).getLocation().getCity() + ",\n"
            + user.getResults().get(0).getLocation().getState() + ",\n"
            + user.getResults().get(0).getLocation().getStreet() + ",\n"
            + user.getResults().get(0).getLocation().getPostcode());
    tv_email.setText("Email :   "+user.getResults().get(0).getEmail());
    tv_cell.setText("Mobile :   "+user.getResults().get(0).getCell());

}

 

public class MainActivity extends AppCompatActivity {

    ImageView img_user;
    SwipeRefreshLayout swipeRefreshLayout;
    TextView tv_dob, tv_age, tv_gender, tv_first_name, tv_last_name, tv_location, tv_email, tv_cell;

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

        init();
        fetchData();

    }

    private void init() {

        img_user = findViewById(R.id.img_user);
        tv_dob = findViewById(R.id.tv_dob);
        tv_age = findViewById(R.id.tv_age);
        tv_gender = findViewById(R.id.tv_gender);
        tv_first_name = findViewById(R.id.tv_first_name);
        tv_last_name = findViewById(R.id.tv_last_name);
        tv_location = findViewById(R.id.tv_location);
        tv_email = findViewById(R.id.tv_email);
        tv_cell = findViewById(R.id.tv_cell);
        swipeRefreshLayout = findViewById(R.id.simpleSwipeRefreshLayout);


        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                fetchData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }


    private void fetchData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);

        Call<User> call = api.getstatus();

        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {

                User user = (User) response.body();

                setData(user);

            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

                Toast.makeText(MainActivity.this, "" + t.getMessage().toString(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    public void setData(User user) {

        Glide.with(this)
                .load(user.getResults().get(0).getPicture().getLarge())
                .into(img_user);

        tv_dob.setText("DOB :   "+user.getResults().get(0).getDob().getDate());
        tv_age.setText("Age :   "+user.getResults().get(0).getDob().getAge());
        tv_gender.setText("Gender :   "+user.getResults().get(0).getGender());
        tv_first_name.setText("Name :   "+user.getResults().get(0).getName().getFirst());
        tv_last_name.setText("  "+user.getResults().get(0).getName().getLast());
        tv_location.setText(""+user.getResults().get(0).getLocation().getCity() + ",\n"
                + user.getResults().get(0).getLocation().getState() + ",\n"
                + user.getResults().get(0).getLocation().getStreet() + ",\n"
                + user.getResults().get(0).getLocation().getPostcode());
        tv_email.setText("Email :   "+user.getResults().get(0).getEmail());
        tv_cell.setText("Mobile :   "+user.getResults().get(0).getCell());

    }

}

 

 

 

 

AndroidManifest.xml

Add Internet permission to manifest file

 

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        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>

 

Output :

This screen depicts the on swipe to refresh view

 

If you have any query on this tutorial on swipe to refresh view do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

abhishek:
Related Post

This website uses cookies.