Skip to main content

Develop News App In Android Studio

Develop News App in Android Studio-


link for api -
newsapi.org


activity_detailed.xml

<?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:orientation="vertical"
    tools:context=".DetailedActivity">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:id="@+id/cardView"
            android:layout_margin="10dp"
            app:cardElevation="4dp"
            app:cardCornerRadius="4dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
            <FrameLayout
                android:layout_width="match_parent"
                android:padding="10dp"
                android:layout_height="250dp">
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/img"
                    android:scaleType="centerCrop"
                    android:id="@+id/image"/>
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    android:background="@drawable/gradient"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TITLE"
                    android:textSize="20dp"
                    android:padding="10dp"
                    android:textColor="@color/white"
                    android:id="@+id/tvId"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:orientation="horizontal">
                    <TextView
                        android:gravity="left"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Source"
                        android:textSize="16dp"
                        android:ems="15"
                        android:textColor="@color/white"
                        android:id="@+id/tvSource"/>
                    <TextView
                        android:gravity="right"

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Date"
                        android:textSize="16dp"
                        android:textColor="@color/white"
                        android:id="@+id/tvDate"/>
                </LinearLayout>
            </FrameLayout>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Description"
                    android:padding="5dp"
                    android:textColor="@color/red"
                    android:id="@+id/tvDesc"/>

    </LinearLayout>
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="10000dp"
            android:layout_marginTop="10dp"
            android:elevation="4dp"
            app:cardCornerRadius="10dp">

            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"></WebView>

        </androidx.cardview.widget.CardView>
    </LinearLayout>
</ScrollView>
</LinearLayout>

activity_main.xml

<?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:orientation="vertical"
    tools:context=".MainActivity">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/grey"
        android:padding="10dp"
        android:text="NEWS"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp"
        tools:fontFamily="serif" />
    <ImageButton
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:visibility="visible"
        android:id="@+id/floating"
     android:background="@drawable/pro"
        android:scaleType="centerCrop"/>
</RelativeLayout>

<Button
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:text="Refresh"
    android:id="@+id/refreshButton"
    android:textColor="@color/white"
    android:background="@drawable/black_background"/>


    <androidx.recyclerview.widget.RecyclerView
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"></androidx.recyclerview.widget.RecyclerView>

</LinearLayout>
activity_intro.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".Intro">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/intro"/>

</androidx.constraintlayout.widget.ConstraintLayout>
items.xml

<?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:id="@+id/cardView"
        android:layout_margin="10dp"
        app:cardElevation="4dp"
        app:cardCornerRadius="4dp">
        <FrameLayout
            android:layout_width="match_parent"
            android:padding="10dp"
            android:layout_height="200dp">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/img"
                android:scaleType="centerCrop"
                android:id="@+id/image"/>
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                android:background="@drawable/gradient"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TITLE"
                android:textSize="20dp"
                android:padding="10dp"
                android:textColor="@color/white"
                android:id="@+id/tvId"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:orientation="horizontal">
                <TextView
                    android:gravity="left"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Source"
                    android:textSize="16dp"
                    android:ems="15"
                    android:textColor="@color/white"
                    android:id="@+id/tvSource"/>
                <TextView
                    android:gravity="right"

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Date"
                    android:textSize="16dp"
                    android:textColor="@color/white"
                    android:id="@+id/tvDate"/>
            </LinearLayout>
        </FrameLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>
Java
Adapter.java
package com.example.newsapp;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.newsapp.Model.Articles;
import com.squareup.picasso.Picasso;

import java.util.List;
import java.util.Locale;

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

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
    Context context;
    List<Articles> articles;
    public Adapter(Context context, List<Articles> articles) {
        this.context = context;
        this.articles = articles;
    }


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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
   final Articles a=articles.get(position);
   String url=a.getUrl();
   holder.tvTitle.setText(a.getTitle());
   //get source ke saath .getname lagana hai 32.36 part 1
   holder.tvSource.setText(a.getSource().getName());
   holder.tvDate.setText(a.getPublishedAt());

   String imageUrl=a.getUrlToImage();
   //picasso ka syntax new 33.07 part1
        Picasso.get().load(imageUrl).into(holder.imageView);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context,DetailedActivity.class);
                intent.putExtra("title",a.getTitle());
                intent.putExtra("source",a.getSource().getName());
                intent.putExtra("time",a.getPublishedAt());
                intent.putExtra("imageUrl",a.getUrlToImage());
                intent.putExtra("url",a.getUrl());
                intent.putExtra("decs",a.getDescription());
                context.startActivity(intent);
            }
        });
    }


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

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle,tvSource,tvDate;
        ImageView imageView;
        CardView cardView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvTitle=itemView.findViewById(R.id.tvId);
            tvDate=itemView.findViewById(R.id.tvDate);
            tvSource=itemView.findViewById(R.id.tvSource);
            imageView=itemView.findViewById(R.id.image);
            cardView=itemView.findViewById(R.id.cardView);
        }
    }
    public String getCountry()
    {
        Locale locale=Locale.getDefault();
        String country=locale.getCountry();
        return country.toLowerCase();
    }
}
ApiClient.java
package com.example.newsapp;

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

@SuppressWarnings("ALL")
public class ApiClient {
    private static  final String BASE_URL="https://newsapi.org/v2/";
    private static ApiClient apiClient;
    private    static Retrofit retrofit;
    private  ApiClient()
    {
       retrofit=new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public static synchronized ApiClient getInstance()
    {
        if (apiClient==null)
        {
            apiClient=new ApiClient();
        }
        return apiClient;
    }
   public ApiInterface getApi()
   {
       return retrofit.create(ApiInterface.class);
   }
}
ApiInterface.java

package com.example.newsapp;

import com.example.newsapp.Model.Headlines;

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

public interface ApiInterface {
    @GET("top-headlines")
    Call<Headlines> getHeadlines(
        @Query("country") String country,
                @Query("apiKey") String apiKey
    );
}
DetailedActivity.java

package com.example.newsapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

public class DetailedActivity extends AppCompatActivity {
TextView tvTitle,tvSource,tvTime,tvDesc;
ImageView imageView;
WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed);
        tvTitle=findViewById(R.id.tvId);
        tvSource=findViewById(R.id.tvSource);
        tvTime=findViewById(R.id.tvDate);
        tvDesc=findViewById(R.id.tvDesc);
        webView=findViewById(R.id.webView);
        imageView=findViewById(R.id.image);

        Intent intent=getIntent();
       String title=intent.getStringExtra("title");
       String source=intent.getStringExtra("source");
       String time=intent.getStringExtra("time");
       String imageUrl=intent.getStringExtra("imageUrl");
       String url=intent.getStringExtra("url");
       String desc=intent.getStringExtra("desc");


       tvTitle.setText(title);
       tvSource.setText(source);
       tvTime.setText(time);
       tvDesc.setText(desc);

        Picasso.get().load(imageUrl).into(imageView);
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setJavaScriptEnabled(true);
       webView.getSettings().setLoadsImagesAutomatically(true);
       webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
       webView.setWebViewClient(new WebViewClient());
       webView.loadUrl(url);
    }
}
Intro.java

package com.example.newsapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class Intro extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro);
    }
}
MainActivity.java

package com.example.newsapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.newsapp.Model.Articles;
import com.example.newsapp.Model.Headlines;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

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

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Adapter adapter;
final  String API_KEY="d2df6a66321b4346b86d9e139b26100c";
Button button;
ImageButton floatingActionButton;
List<Articles> articles=new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
    button=findViewById(R.id.refreshButton);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        final String country=getCountry();
    floatingActionButton=(ImageButton)findViewById(R.id.floating);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,Intro.class);
            startActivity(intent);
        }
    });

        retrieveJson(country,API_KEY);
       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               retrieveJson(country,API_KEY);
           }
       });
    }
    public  void retrieveJson(String country,String apiKey)
    {
        Call<Headlines> call=ApiClient.getInstance().getApi().getHeadlines(country,apiKey);
        call.enqueue(new Callback<Headlines>() {
            @Override
            public void onResponse(Call<Headlines> call, Response<Headlines> response) {
                if (response.isSuccessful() && response.body().getArticles()!=null){
                    articles.clear();
                    articles=response.body().getArticles();

                    adapter =new Adapter(MainActivity.this, articles);
                      recyclerView.setAdapter(adapter);
                }
            }

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

                Toast.makeText(MainActivity.this,"There is An Error",Toast.LENGTH_SHORT).show();
            }
        });
    }
    public String getCountry()
    {
        Locale locale=Locale.getDefault();
        String country=locale.getCountry();
        return country.toLowerCase();
    }
}
Articles.java
package com.example.newsapp.Model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Articles {
    @SerializedName("source")
    @Expose
    private Source source;
    @SerializedName("author")
    @Expose
    private String author;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("url")
    @Expose
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @SerializedName("urlToImage")
    @Expose
    private String urlToImage;
    @SerializedName("publishedAt")
    @Expose
    private String publishedAt;

    public Source getSource() {

        return source;
    }

    public void setSource(Source source) {

        this.source = source;
    }

    public String getAuthor() {

        return author;
    }

    public void setAuthor(String author) {

        this.author = author;
    }

    public String getTitle() {

        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {

        this.description = description;
    }

    public String getUrlToImage() {

        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {

        this.publishedAt = publishedAt;
    }
}
Headlines.java
package com.example.newsapp.Model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class Headlines {
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("totalResults")
    @Expose
    private String totalResults;
    @SerializedName("articles")
    @Expose
    private List<Articles> articles;

    public String getStatus() {
        return status;
    }

    public String getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(String totalResults) {
        this.totalResults = totalResults;
    }

    public List<Articles> getArticles() {
        return articles;
    }

    public void setArticles(List<Articles> articles) {
        this.articles = articles;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
Source.java
package com.example.newsapp.Model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Source {
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

Comments

  1. Thanks... I really leant a lot.
    Its just that you didn't make the tutorial with a voice more explanation.
    What if I want to add some categories like business news, entertainment news, technology news,etc on newsapi.org to my app?

    ReplyDelete
  2. Thanks a lot i really learn many things from it and it help me

    ReplyDelete
  3. event manager For example a group of engineers at Boeing re-designed the manufacturing process for making doors on their airplanes. happy anniversary quotes, happy saturday and cow puns

    ReplyDelete
  4. This post is so helpfull and attractive.keep updating with more information...
    Data Science Future
    Career In Data Science

    ReplyDelete

Post a Comment

Popular posts from this blog

Create a socket for HTTP for web page upload and download

Create a socket for HTTP for web page upload and download. Aim: To write a java program for socket for HTTP for web page upload and download . Algorithm 1.Start the program. 2.Get the frame size from the user 3.To create the frame based on the user request. 4.To send frames to server from the client side. 5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. 6.Stop the program Program : Client import javax.swing.*; import java.net.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Client{ public static void main(String args[]) throws Exception{ Socket soc; BufferedImage img = null; soc=new Socket("localhost",4000); System.out.println("Client is running. ");  try { System.out.println("Reading image from disk. "); im...

Write a code simulating ARP /RARP protocols

   Write a code simulating ARP /RARP protocols . Aim:        To write a java program for simulating ARP/RARP protocols ALGORITHM: server 1. Create a server socket and bind it to port. 2. Listen for new connection and when a connection arrives, accept it. 3. Send server ‟ s date and time to the client. 4. Read client ‟ s IP address sent by the client. 5. Display the client details. 6. Repeat steps 2-5 until the server is terminated. 7. Close all streams. 8. Close the server socket. 9. Stop. Client 1. Create a client socket and connect it to the server ‟ s port number. 2. Retrieve its own IP address using built-in function. 3. Send its address to the server. 4. Display the date & time sent by the server. 5. Close the input and output streams. 6. Close the client socket. 7. Stop. Program Program for Address Resolutuion Protocol (ARP) using TCP Client: import java.io.*; import java.net.*; impor...

Write program to find ε – closure of all states of any given NFA with ε transition.

 Write program to find ε – closure of all states of any given NFA with ε transition. Agenda 1.Program 2.Input/Output 1.Program #include <stdio.h> #include <string.h> char  result[ 20 ][ 20 ], copy[ 3 ], states[ 20 ][ 20 ]; void  add_state( char  a[ 3 ],  int  i) {   strcpy(result[i], a); } void  display( int  n) {    int  k =  0 ;   printf( "nnn Epsilon closure of %s = { " , copy);    while  (k < n) {     printf( " %s" , result[k]);     k++;   }   printf( " } nnn" ); } int  main() {   FILE * INPUT;   INPUT = fopen( "input.dat" ,  "r" );    char  state[ 3 ];    int  end, i =  0 , n, k =  0 ;  ...