<repo_name>orestislef/Techblogproject<file_sep>/app/src/main/java/com/orestislef/techblogproject/MainActivity.java
package com.orestislef.techblogproject;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.google.android.material.navigation.NavigationView;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    RecyclerView NewsRecyclerview;
    RecyclerViewPostAdapter recyclerViewPostAdapter;
    List<PostItem> mData;
    boolean isDark = false;
    ConstraintLayout rootLayout;
    EditText searchInput;
    CharSequence search = "";

    public int postsPerPage = 30;
    public int category = 0;
    private static final String TAG = "MainActivity";
    public String imageUrl;

    private DrawerLayout drawer;
    private Toolbar toolbar;
    private ActionBarDrawerToggle toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // let's make this activity on full screen

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        // hide the action bar

//        getSupportActionBar().hide();


        // ini view

//        rootLayout = findViewById(R.id.root_layout);
        drawer = findViewById(R.id.drawer_layout);
        searchInput = findViewById(R.id.search_input);
        NewsRecyclerview = findViewById(R.id.news_rv);
        mData = new ArrayList<>();

        // load theme state

        toolbar = findViewById(R.id.toolbar);
        toolbar.setVisibility(View.GONE);
        setSupportActionBar(toolbar);
        drawer.findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        if (savedInstanceState == null) {
            navigationView.setCheckedItem(R.id.nav_home);
        }

        getData();


        // adapter ini and setup

        recyclerViewPostAdapter = new RecyclerViewPostAdapter(this, mData, isDark);
        NewsRecyclerview.setAdapter(recyclerViewPostAdapter);
        NewsRecyclerview.setLayoutManager(new LinearLayoutManager(this));

        searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                recyclerViewPostAdapter.getFilter().filter(s);
                search = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        Log.d(TAG, "onNavigationItemSelected: selected: " + menuItem);
        switch (menuItem.getItemId()) {
            case R.id.nav_home:
                category = 0;
                break;
            case R.id.nav_smartphones:
                category = 8;
                break;
            case R.id.nav_gear:
                category = 24;
                break;
            case R.id.nav_reviews:
                category = 58;
                break;
            case R.id.nav_workshop:
                category = 1033;
                break;
            case R.id.nav_internet:
                category = 49;
                break;
            case R.id.nav_cars:
                category = 9131;
                break;
            case R.id.nav_homecinema:
                category = 57;
                break;
            case R.id.nav_software:
                category = 584;
                break;
            case R.id.nav_computers:
                category = 29;
                break;
            case R.id.nav_business:
                category = 24;
                break;

        }
        mData.clear();
        getData();

        drawer.closeDrawer(GravityCompat.START);
        setSupportActionBar(toolbar);

        toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else
            super.onBackPressed();
    }

    public void getData() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(getResources()
                        .getString(R.string.base_url))
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
        Call<List<WPPost>> call;
        if (category == 0) {
            call = service.getPostPerPage(postsPerPage);
        } else {
            call = service.getPostByCategory(category);
        }

        call.enqueue(new Callback<List<WPPost>>() {
            @Override
            public void onResponse(@NonNull Call<List<WPPost>> call, @NonNull Response<List<WPPost>> response) {
                Log.e(TAG, "onResponse: " + response.body());

                for (int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) {
                    int mId = response.body().get(i).getId();
                    Log.d(TAG, "onResponseID: " + mId);
                    final String mediaUrl = response.body().get(i).getLinks().getWpAttachment().get(0).getHref();
                    final String mTitle = response.body().get(i).getTitle().getRendered();
                    String mSubtitle = response.body().get(i).getExcerpt().getRendered();

                    mSubtitle = mSubtitle.replace("<p>", "");
                    mSubtitle = mSubtitle.replace("</p>", "");
                    mSubtitle = mSubtitle.replace("[&hellip;]", "");

                    final String finalMContent = response.body().get(i).getContent().getRendered();

                    final String mDate = response.body().get(i).getDate();

                    Log.d(TAG, "onResponse: "
                            + "\n================================================================================================================================================================================================================================================"
                            + "\nid: \t\t" + mId
                            + "\nTitle: \t\t" + mTitle
                            + "\nSubtitle: \t" + mSubtitle
                            + "\nContent: \t\t" + finalMContent
                            + "\n================================================================================================================================================================================================================================================");

                    Retrofit retrofit2 = new Retrofit.Builder()
                            .baseUrl(getResources().getString(R.string.base_url))
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

                    RetrofitArrayApi service2 = retrofit2.create(RetrofitArrayApi.class);

                    Call<List<WPPostID>> call2 = service2.getWpAttachment(mediaUrl);
                    Log.d(TAG, "getRetrofitImageMediaUrl: " + mediaUrl);
                    final String finalMSubtitle = mSubtitle;
                    call2.enqueue(new Callback<List<WPPostID>>() {
                                      @Override
                                      public void onResponse(@NonNull Call<List<WPPostID>> call, @NonNull Response<List<WPPostID>> response) {

                                          Log.e(TAG, "onResponse: " + response.body());

                                          if (response.body() != null) {
                                              if (response.body().size() != 0) {
                                                  imageUrl = response.body().get(0).getMediaDetails().getSizes().getThumbnail().getSourceUrl();
//                                              imageUrl = response.body().get(0).getSourceUrl();
                                                  Log.d(TAG, "onResponseImage: " + "\n******************************************************************************************" + "\n\t with media " + imageUrl + "\n******************************************************************************************");
                                              } else {
                                                  imageUrl = "";
                                                  Log.d(TAG, "onResponseImage: " + "\n******************************************************************************************" + "\n\t null media\n" + imageUrl + "\n******************************************************************************************");
                                              }
                                          }
                                          mData.add(new PostItem(mTitle, finalMSubtitle, finalMContent, mDate, imageUrl));
                                          recyclerViewPostAdapter.notifyItemInserted(mData.size() - 1);
                                      }

                                      @Override
                                      public void onFailure(@NonNull Call<List<WPPostID>> call, Throwable t) {
                                      }
                                  }
                    );
                }

            }

            @Override
            public void onFailure(@NonNull Call<List<WPPost>> call, Throwable t) {
            }
        });
    }
}
<file_sep>/README.md
# Techblogproject

Techblog.gr website Testing retrofit2 implementation to populate threds into recyclerView
<file_sep>/app/src/main/java/com/orestislef/techblogproject/RecyclerViewPostAdapter.java
package com.orestislef.techblogproject;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter;
import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class RecyclerViewPostAdapter extends RecyclerView.Adapter<RecyclerViewPostAdapter.NewsViewHolder> implements Filterable {
    Context mContext;
    List<PostItem> mData;
    List<PostItem> mDataFiltered;

    public RecyclerViewPostAdapter(Context mContext, List<PostItem> mData, boolean isDark) {
        this.mContext = mContext;
        this.mData = mData;
        this.mDataFiltered = mData;
    }

    public RecyclerViewPostAdapter(Context mContext, List<PostItem> mData) {
        this.mContext = mContext;
        this.mData = mData;
        this.mDataFiltered = mData;

    }

    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View layout;
        layout = LayoutInflater.from(mContext).inflate(R.layout.item_news, viewGroup, false);
        return new NewsViewHolder(layout);
    }

    @Override
    public void onBindViewHolder(@NonNull final NewsViewHolder newsViewHolder, int position) {

        // bind data here

        // we apply animation to views here
        // first lets create an animation for user photo
        newsViewHolder.img_user.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_transition_animation));

        // lets create the animation for the whole card
        // first lets create a reference to it
        // you ca use the previous same animation like the following

        // but i want to use a different one so lets create it ..
        newsViewHolder.container.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_scale_animation));


        newsViewHolder.tv_title.setText(mDataFiltered.get(position).getTitle());
        newsViewHolder.tv_content.setHtml(mDataFiltered.get(position).Excerpt, new HtmlHttpImageGetter(newsViewHolder.tv_content));
//        newsViewHolder.tv_content.setHtml(mDataFiltered.get(position).getContent());
        newsViewHolder.tv_date.setText(calculateTimeAgo(mDataFiltered.get(position).getDate()));
        if (mDataFiltered.get(position).image.equals("")) {
            newsViewHolder.img_user.setVisibility(View.GONE);
        } else {
            int finalPos = position;
            Glide.with(mContext)
                    .load(mDataFiltered.get(position)).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    new Handler().post(() -> Glide.with(mContext)
                            .load(mDataFiltered.get(finalPos).image)
                            .into(newsViewHolder.img_user));
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    return false;
                }
            }).into(newsViewHolder.img_user);
        }
        int finalPos = position;
        newsViewHolder.container.setOnClickListener(v ->
                newsViewHolder.tv_content.
                        setHtml(mDataFiltered.get(finalPos).Content,
                                new HtmlHttpImageGetter(newsViewHolder.tv_content)));
    }

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

    public String calculateTimeAgo(@NonNull String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
        try {
            long time = sdf.parse(date).getTime();
            long now = System.currentTimeMillis();
            CharSequence ago =
                    DateUtils.getRelativeTimeSpanString(time, now, DateUtils.SECOND_IN_MILLIS);
            return ago + "";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                String Key = constraint.toString();
                if (Key.isEmpty()) {
                    mDataFiltered = mData;
                } else {
                    List<PostItem> lstFiltered = new ArrayList<>();
                    for (PostItem row : mData) {

                        if (row.getTitle().toLowerCase().contains(Key.toLowerCase())) {
                            lstFiltered.add(row);
                        }
                    }
                    mDataFiltered = lstFiltered;
                }


                FilterResults filterResults = new FilterResults();
                filterResults.values = mDataFiltered;
                return filterResults;

            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {


                mDataFiltered = (List<PostItem>) results.values;
                notifyDataSetChanged();

            }
        };
    }

    public static class NewsViewHolder extends RecyclerView.ViewHolder {


        HtmlTextView tv_content;
        TextView tv_title, tv_date;
        ImageView img_user;
        RelativeLayout container;


        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            container = itemView.findViewById(R.id.container);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_content = itemView.findViewById(R.id.tv_description);
            tv_date = itemView.findViewById(R.id.tv_date);
            img_user = itemView.findViewById(R.id.img_user);
        }
    }
}
