Technology10/15/2019
How to create News App in android?
Sponsored Intelligence Dispatch
1. First of all create a News API from NewsApi.org.
2. Create a new project in Android Studio in a normal way.
Open your build.gradle file and add the following lines in your dependencies.
Open your build.gradle file and add the following lines in your dependencies.
compile 'com.squareup.picasso:picasso:2.5.2'
3. Open your AndroidManifest.xml file and add internet connect permission. Your manifest file will look like this-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androstock.newsapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
<activity android:name=".DetailsActivity"/>
</application>
</manifest>
4. Open your activity_main.xml file. Use a RelativeLayout to arrange ListView and Progressbar.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<ListView
android:id="@+id/listNews"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:divider="#F5F5F5"
android:dividerHeight="1dp"
android:visibility="visible"
/>
<ProgressBar
android:id="@+id/loader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
5. Now we will design the list item activity Open your list_row.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:layout_weight="7"
android:padding="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:padding="4dp">
<ImageView
android:id="@+id/galleryImage"
android:layout_width="70dp"
android:layout_height="50dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="7"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:shadowColor="#000"
android:shadowRadius="1.0"
android:textColor="#666666"
android:textSize="17sp"
android:layout_marginBottom="5dp"
android:maxLines="2"
android:scrollHorizontally="true"
android:ellipsize="end"
android:text="This is news title"/>
<TextView
android:id="@+id/sdetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#777777"
android:textSize="16sp"
android:maxLines="2"
android:minLines="2"
android:scrollHorizontally="true"
android:ellipsize="end"
android:text="This is news description bla bla bla..."/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="@+id/author"
android:textSize="15sp"
android:textColor="#42A5F5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="News Author"/>
</LinearLayout>
<TextView
android:id="@+id/time"
android:gravity="right"
android:textSize="14sp"
android:textColor="#42A5F5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
6. Now we will design the details activity to show the specific news article activity_details.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:id="@+id/loader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
Finally we are heading towards the Java coding.
7. Now we will create a Java file called Function.java where we will put our important methods like Internet Connection Checker and URL Execute method.
package com.androidcodeblock.newsapp;
import android.content.Context;
import android.net.ConnectivityManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Function {
public static boolean isNetworkAvailable(Context context)
{
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
public static String excuteGet(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
//connection.setRequestMethod("POST");
//connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("content-type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(false);
InputStream is;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = connection.getErrorStream();
else
is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
8. Now lets create the MainActivity.java
package com.androidcodeblock.newsapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
String API_KEY = "*********************"; // ### YOUE NEWS API HERE ###
String NEWS_SOURCE = "bbc-news";
ListView listNews;
ProgressBar loader;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
static final String KEY_AUTHOR = "author";
static final String KEY_TITLE = "title";
static final String KEY_DESCRIPTION = "description";
static final String KEY_URL = "url";
static final String KEY_URLTOIMAGE = "urlToImage";
static final String KEY_PUBLISHEDAT = "publishedAt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listNews = (ListView) findViewById(R.id.listNews);
loader = (ProgressBar) findViewById(R.id.loader);
listNews.setEmptyView(loader);
if(Function.isNetworkAvailable(getApplicationContext()))
{
DownloadNews newsTask = new DownloadNews();
newsTask.execute();
}else{
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
class DownloadNews extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String xml = "";
String urlParameters = "";
xml = Function.excuteGet("https://newsapi.org/v1/articles?source="+NEWS_SOURCE+"&sortBy=top&apiKey="+API_KEY, urlParameters);
return xml;
}
@Override
protected void onPostExecute(String xml) {
if(xml.length()>10){ // Just checking if not empty
try {
JSONObject jsonResponse = new JSONObject(xml);
JSONArray jsonArray = jsonResponse.optJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_AUTHOR, jsonObject.optString(KEY_AUTHOR).toString());
map.put(KEY_TITLE, jsonObject.optString(KEY_TITLE).toString());
map.put(KEY_DESCRIPTION, jsonObject.optString(KEY_DESCRIPTION).toString());
map.put(KEY_URL, jsonObject.optString(KEY_URL).toString());
map.put(KEY_URLTOIMAGE, jsonObject.optString(KEY_URLTOIMAGE).toString());
map.put(KEY_PUBLISHEDAT, jsonObject.optString(KEY_PUBLISHEDAT).toString());
dataList.add(map);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Unexpected error", Toast.LENGTH_SHORT).show();
}
ListNewsAdapter adapter = new ListNewsAdapter(MainActivity.this, dataList);
listNews.setAdapter(adapter);
listNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(MainActivity.this, DetailsActivity.class);
i.putExtra("url", dataList.get(+position).get(KEY_URL));
startActivity(i);
}
});
}else{
Toast.makeText(getApplicationContext(), "No news found", Toast.LENGTH_SHORT).show();
}
}
}
}
9. Now lets create the adapter class ListNewsAdapter.java to populate the listview list item using list_row.xml
package com.androidcodeblock.newsapp;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
class ListNewsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
public ListNewsAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ListNewsViewHolder holder = null;
if (convertView == null) {
holder = new ListNewsViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.list_row, parent, false);
holder.galleryImage = (ImageView) convertView.findViewById(R.id.galleryImage);
holder.author = (TextView) convertView.findViewById(R.id.author);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.sdetails = (TextView) convertView.findViewById(R.id.sdetails);
holder.time = (TextView) convertView.findViewById(R.id.time);
convertView.setTag(holder);
} else {
holder = (ListNewsViewHolder) convertView.getTag();
}
holder.galleryImage.setId(position);
holder.author.setId(position);
holder.title.setId(position);
holder.sdetails.setId(position);
holder.time.setId(position);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
try{
holder.author.setText(song.get(MainActivity.KEY_AUTHOR));
holder.title.setText(song.get(MainActivity.KEY_TITLE));
holder.time.setText(song.get(MainActivity.KEY_PUBLISHEDAT));
holder.sdetails.setText(song.get(MainActivity.KEY_DESCRIPTION));
if(song.get(MainActivity.KEY_URLTOIMAGE).toString().length() < 5)
{
holder.galleryImage.setVisibility(View.GONE);
}else{
Picasso.with(activity)
.load(song.get(MainActivity.KEY_URLTOIMAGE).toString())
.resize(300, 200)
.into(holder.galleryImage);
}
}catch(Exception e) {}
return convertView;
}
}
class ListNewsViewHolder {
ImageView galleryImage;
TextView author, title, sdetails, time;
}
From MainActivity.java we will open the DetailsActivity.java on news item click. There we will display the article page into WebView.
10. Now lets create the DetailsActivity.java
package com.androidcodeblock.newsapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
public class DetailsActivity extends AppCompatActivity {
WebView webView;
ProgressBar loader;
String url = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent intent = getIntent();
url = intent.getStringExtra("url");
loader = (ProgressBar) findViewById(R.id.loader);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.loadUrl(url);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
loader.setVisibility(View.GONE);
} else {
loader.setVisibility(View.VISIBLE);
}
}
});
}
}
You are done. Now run and test the app. You can add your custom designs and also other features now. It was really easy. Isn’t it?
Deep Structural Diagnostics.
Mastering JSON is only the first step. Use our industrial-grade workbench to format, validate, and synthesize models for your production APIs.
Sponsored Infrastructure
Industrial Analysis Active
