refresh by swiping/pulling down on the app screen.

0
50

refresh by swiping/pulling down on the app screen | In this tutorial, you will learn how to make your own “Latest News App”.  This will be done by using API for downloading latest news from the Internet in JSON format. News titles are fetched to a ListView which can be refreshed by swiping/pulling down on the app screen.

You are going to use: API, JSON parsing,  Asynchronous Task & Swipe Refresh layout.

Output: –

Download APK – [media-downloader media_id=”1145″ texts=”here”]

Download Project -[media-downloader media_id=”1146″ texts=”here”]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

WHAT IS API.

An application program interface (API) is code that allows two software programs to communicate with each other.The API defines the correct way for a developer to write a program that requests services from an application.

There are many Open API’s which are free of cost and provide users data in JSON format for easy reading.

Ex- OpenWeatherMap.org API (for current weather and forecast info)

NewsAPI.org (for news headline from range of sources)

Here we are going to use newsapi.org for gaining our latest news headlines.

URL : https://newsapi.org/v1/articles?source=the-hindu&sortBy=top&apiKey={API_KEY}

First of all, one needs to generate their own API KEY, which is the name given to some form of secret token which is submitted alongside web service (or similar) requests in order to identify the origin of the request. It’s free of cost and help site to divide traffic between all legitimate users. Once you open the link in any browser, it will show your API.

So, this is how an API (JSON format) looks like

{
"status": "ok",
"source": "the-hindu",
"sortBy": "top",
"articles": [
     {
"author": "PTI",
"title": "U.K. Secretary of State certifies Mallya extradition request",
"description": "The industrialist is wanted in India for loans default of over Rs 9,000 crore.",
      },
     {
"author": "Sidhartha Roy",
"title": "Airliners ban Shiv Sena MP for brazen assault on Air India staffer",
"description": "Carriers seek ''no fly'' list to bar unruly passengers.",
     }
]//end of articles object
}//end of API 

This API whole is JSON Object and different elements of that main JSON object are status, source,sortBy And articles. The name of these elements can easily specify what value they are storing.

We can see here that ‘articles’ is containing two objects. And these two objects contain information like author, title, and description of a single news headline. We are here interested in reading the title of top 10 news articles.

Related:

Android ViewPager to Swipe the Screen Left or Right

Drag and Swipe with RecyclerView

Detecting Swipe Gestures Android Tutorial

Swipeable RecyclerView in Android

Swipeable RecyclerView in Android using Kotlin.

Inside onCreate() function,

downloadtask task = new downloadtask();    task.execute("https://newsapi.org/v1/articles?source=thehindu&sortBy=latest&apikey={your_own_api_key}");
Put your URL with your own API key inside execute() for launching that URL and get information within your app.

Inside on PostExecute() function of AsyncTaskclass:-

protected void onPostExecute(String result) {
super.onPostExecute(result);
	try {
JSONObjectjsonObject = new JSONObject(result);
            String articles = jsonObject.getString("articles");

JSONArrayarr = new JSONArray(articles);
int j=0;
for(inti=0;i<10;i++){			
JSONObjectarticleObjects = arr.getJSONObject(i);
                String description= articleObjects.getString("title");

                j=i+1;
int id= getResources().getIdentifier("News"+ j,"id", getPackageName());
TextViewtextView = (TextView) findViewById(id);
textView.setText(description);
            }
        } catch (JSONException e) {
e.printStackTrace();
        } 

the result contains all the text which our URL downloaded.

jsonObject is created of JSONObject type. In JSONObject  ‘result’ is passed, which will break down into Heading, Value pairs and we can get values in string format by using String articles = jsonObject.getString(“articles”);

Here String articles store 2 objects (as mentioned in above API example) in string format.

 

JSONArrayarr = new JSONArray(articles);

This command will create an array of objects inside articles string. By this, we can easily access them.

We are only looking for 10 news article, thus exit condition of for loop is i<10

JSONObjectarticleObjects = arr.getJSONObject(i);

Here, an object is created which contains info only on one news topic. This news topic will be it from the top.

String description= articleObjects.getString("title");

//This will store the value of title string in a variable.

int id = getResources().getIdentifier("News" + j, "id", getPackageName());

TextViewtextView = (TextView) findViewById(id);

textView.setText(description);

 

We need to setText of 10 text views. So for this, we need to set the text of each text view separately which is a long procedure.

I declared my textViews ID in XML file like this “News1”, “News2”,……….“News10”.

getIdentifier() does this task by letting us form ID from the text (“News”) and a variable(1,2,…10).

PULL DOWN TO REFRESH

To refresh our news, one way is closing our App and then opening it again. Well, that not what we wanted. What if we could just Swipe down to refresh. It’s very easy. We will use SwipeRefreshLayout.

Inside onCreate()

swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
downloadtask task = new downloadtask();
	task.execute("https://newsapi.org/v1/articles?source=the-hindu&sortBy=latest&apikey=={your_own_api_key}");
swipeContainer.setRefreshing(false);
}

onRefresh() tells what will happen after swiping down,

  1. To execute our URL again.
  2. Once executed, we need to stop refreshing it, as it will keep on fetching updated news and never stop. setRefreshing(false);sets false refreshing once task executed.

Inside XML layout

<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
	...
	...
</ListView>

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

Wrap ListView (whose content you want to refresh) by SwipeRefreshLayout.

Inside values/attr.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_refresh"
android:showAsAction="never"
android:title="@string/menu_refresh"/>
</menu>

Put this inside <resources>….</resources>tag

Add internet permission:

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

 

Add this line inside AndroidManifest.xml to give App permission of using the internet. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here