I want to display a String of names in the text view of recycler view. the .xml of this step is below
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:id="#+id/youtube_row_card_view"
android:layout_height="120dp"
android:layout_marginLeft="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
app:cardCornerRadius="10dp"
app:contentPadding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/video_thumbnail_image_view"
android:layout_width="140dp"
android:layout_height="90dp"
android:contentDescription="#string/thumbnail_image_view_desc"
android:scaleType="centerCrop" ></com.google.android.youtube.player.YouTubeThumbnailView>
<TextView
android:id="#+id/icon_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#android:color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
the adapter class CustomAdapter is below
package com.CurrentMediaPakLiveNews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> {
Context context;
ArrayList<itemModel> items;
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
}
}
public CustomAdapter(Context context, ArrayList<itemModel> items) {
this.context = context;
this.items = items;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.youtube_video_custom_layout, parent, false);
viewHolder viewHolder = new viewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
}
#Override
public int getItemCount() {
return items.size();
}
}
while the itemModel class is declared as:
package com.CurrentMediaPakLiveNews;
public class itemModel {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
the MainActivity declaration for textview is below:
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragmentX;
import java.util.ArrayList;
import java.util.Collections;
import adapter.SecondYoutubeVideoAdapter;
import adapter.YoutubeVideoAdapter;
import utils.Constants;
import utils.RecyclerViewOnClickListener;
import utils.RecyclerViewOnClickListener2;
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private AdView mAdView2;
//custom adapter
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView secondrecyclerView;
ArrayList<itemModel> items;
String[] iconName = {"GEo","Ary","Sama","Hum","dawn","gnn","aj","92","news1","neo"};
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private ArrayList<String> secondyoutubeVideoArrayList;
//youtube player to play video when new video selected
private YouTubePlayer youTubePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
private void setUpRecyclerView() {
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++) {
itemModel itemModel = new itemModel();
itemModel.setName(iconName[i]);
items.add(itemModel);
}
private void populateRecyclerView() {
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
the output is displaying everything except for the TEXTVIEW. no list is being displayed. I have tried ecery solution on stackoverflow regarding dependencies, class import etc but couldnt find any solution. Please can somebody help me in this as I am not a regular developer but a self learner.
My YoutubeVideoAdapter.java is below
package adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import com.CurrentMediaPakLiveNews.R;
import java.util.ArrayList;
import holder.YoutubeViewHolder;
import utils.Constants;
/**
* Created by sonu on 10/11/17.
*/
public class YoutubeVideoAdapter extends RecyclerView.Adapter<YoutubeViewHolder> {
private static final String TAG = YoutubeVideoAdapter.class.getSimpleName();
private Context context;
private ArrayList<String> youtubeVideoModelArrayList;
//position to check which position is selected
private int selectedPosition = 0;
public YoutubeVideoAdapter(Context context, ArrayList<String> youtubeVideoModelArrayList) {
this.context = context;
this.youtubeVideoModelArrayList = youtubeVideoModelArrayList;
}
#Override
public YoutubeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.youtube_video_custom_layout, parent, false);
return new YoutubeViewHolder(view);
}
#Override
public void onBindViewHolder(YoutubeViewHolder holder, final int position) {
//if selected position is equal to that mean view is selected so change the cardview color
if (selectedPosition == position) {
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
} else {
//if selected position is not equal to that mean view is not selected so change the cardview color to white back again
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, android.R.color.white));
}
/* initialize the thumbnail image view , we need to pass Developer Key */
holder.videoThumbnailImageView.initialize(Constants.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
//when initialization is sucess, set the video id to thumbnail to load
youTubeThumbnailLoader.setVideo(youtubeVideoModelArrayList.get(position));
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
//when thumbnail loaded successfully release the thumbnail loader as we are showing thumbnail in adapter
youTubeThumbnailLoader.release();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
//print or show error when thumbnail load failed
Log.e(TAG, "Youtube Thumbnail Error");
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
//print or show error when initialization failed
Log.e(TAG, "Youtube Initialization Failure");
}
});
}
#Override
public int getItemCount() {
return youtubeVideoModelArrayList != null ? youtubeVideoModelArrayList.size() : 0;
}
/**
* method the change the selected position when item clicked
* #param selectedPosition
*/
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
//when item selected notify the adapter
notifyDataSetChanged();
}
}
You are applying differente adapters to the same recyclerview, which means the last one that will be visible will be the last one.
You can see it here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
If you notice, you are doing firstrecyclerView.setAdapter(adapterf) where you attach the CustomAdapter. Then, you do again firstrecyclerView.setAdapter(adapter) where you attach the YoutubeVideoAdapter. Only the last adapter will take place, since it overrides the previous one.
EDIT:
As I can understand, you want to render a view where you display an YoutubeThumbnail and a TextView underneath that thumbnail. In your CustomAdapter, you are using a list of itemModel. Consider adding an attribute to that itemModel that holds the Youtube video URL. If you do it this way, you can show the thumbnail and the TextView at the same time, you just need to modify your CustomAdapter to the same as your YoutubeVideoAdapter.
I.e:
Your ItemModel would look like this:
public class itemModel {
String name;
String youtubeUrl;
public itemoModel(String name, String youtubeUrl){
this.name = name;
this.youtubeUrl = youtubeUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYoutubeUrl(){
return this.youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl){
this.youtubeUrl = youtubeUrl;
}
}
And your CustomAdapter:
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public YouTubeThumbnailView thumbnail;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
this.thumbnail = itemView.findViewById(R.id.video_thumbnail_image_view);
}
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
YouTubeThumbnailView thumbnail = holder.thumbnail;
String youtubeUrl = items.get(position).getYoutubeUrl();
//Do what you need to do with the youtubeUrl
}
This way you just need to use one adapter and one recyclerView with the code you've already done here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
Let me know if it helped you!
Related
I want to loop through all CardViews and change the text and color of a TextView within a single CardView item using a button click. The following code seems to produce the desired results but I'm not certain that it's the most effective code or even accurate (index).
CustomAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private Context context;
private List<MyModel> list;
public CustomAdapter(Context context, List<MyModel> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
holder.textName.setText(list.get(position).getName());
holder.textAge.setText(String.valueOf(list.get(position).getAge()));
}
#Override
public int getItemCount() {
return list.size();
}
}
CustomViewHolder
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView textName, textAge;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
textName = itemView.findViewById(R.id.textName);
textAge = itemView.findViewById(R.id.textAge);
}
}
MainActivity
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List<MyModel> myModelList;
CustomAdapter customAdapter;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
}
private void loadData() {
recyclerView = findViewById(R.id.recycler_main);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
myModelList = new ArrayList<>();
myModelList.add(new MyModel("Joe", 21));
myModelList.add(new MyModel("Jane", 26));
myModelList.add(new MyModel("Kyle", 19));
myModelList.add(new MyModel("Scott", 30));
customAdapter = new CustomAdapter(this, myModelList);
recyclerView.setAdapter(customAdapter);
}
public void onClickBtn(View v)
{
String searchString = "Kyle";
for (int x = recyclerView.getChildCount(), i = 0; i < x; ++i) {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
TextView txtName = holder.itemView.findViewById(R.id.textName);
if (txtName.getText().toString().equals(searchString.toString())) {
txtName.setText("Found " + txtName.getText().toString());
txtName.setTextColor(Color.GREEN);
customAdapter.notifyItemChanged(x);
}
}
}
}
MyModel
public class MyModel {
String name = "";
int age = 0;
public MyModel(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
It's important that I iterate through the list in button click event. Functionality to be changed later. Really appreciate any advice and feedback. Thanks a lot.
I'm new to Android Studio. I'm trying to custom a Fragment automatically created by the IDE using the option create -> new Fragment (List). I'm not able to show the List retrieved from an http page, but if I manually add items to my list, the emulator let me see it. How can I solve this problem?
municipioFragment.java
package com.example.is2_app.ui.municipio;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class municipioFragment extends Fragment {
// TODO: Customize parameters
private int mColumnCount = 1;
private List<News> lstNews;
private OnListFragmentInteractionListener mListener;
public municipioFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstNews = new ArrayList<>();
getURL();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_municipio_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(News item);
}
public void getURL() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.comune.candida.av.it").get();
Element content = doc.getElementById("b370");
Elements subcontent = content.getElementsByTag("p");
String Text = null;
String Href = null;
int i = 0;
for (Element link : subcontent) {
Href = link.attr("href");
Text = link.text();
builder.append("\n").append(Text);
i = i + 1;
lstNews.add(new News(Integer.toString(i), Text));
}
} catch (IOException e) {
builder.append("Error: ").append(e.getMessage()).append("\n");
}
}
}).start();
}
}
MunicipioRecyclerViewAdapter.java
package com.example.is2_app.ui.municipio;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.is2_app.R;
import com.example.is2_app.ui.municipio.municipioFragment.OnListFragmentInteractionListener;
import java.util.List;
public class MymunicipioRecyclerViewAdapter extends RecyclerView.Adapter<MymunicipioRecyclerViewAdapter.ViewHolder> {
private final OnListFragmentInteractionListener mListener;
List<News> mData;
public MymunicipioRecyclerViewAdapter(List<News> mData, OnListFragmentInteractionListener listener) {
this.mData = mData;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_municipio, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mData.get(position).getId());
holder.mContentView.setText(mData.get(position).getContent());
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.item_number);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
fragment_municipio.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" /> </LinearLayout>
fragment_municipio_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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:id="#+id/list"
android:name="com.example.is2_app.ui.municipioFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.municipio.municipioFragment"
tools:listitem="#layout/fragment_municipio" />
So getUrl() is running in a Thread. In addition, getting the Document with JSoup is gonna need some time. This means that onCreateView will probably run before your lstNews is filled with the data you are scraping from the Document.
So you want to update your dataset; then, you want to notify your Adapter that your dataset changed.
Add this method to your Adapter
public void updateData(List<News> mData) {
this.mData = mData;
this.notifyDataSetChanged();
}
And after the for loop in getUrl(), you want to do the following:
runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerViewAdapter.updateData(lstNews);
}
});
Where, recyclerViewAdapter is defined alongside recyclerView and initialized in the onCreateView.
So the following line:
recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
Will become:
recyclerViewAdapter = new MymunicipioRecyclerViewAdapter(lstNews, mListener);
recyclerView.setAdapter(recyclerViewAdapter);
The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the attached image. As of now when one clicks the image only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RecyclerView code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CardView code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MainActivity
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RecyclerViewAdapter
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
ImageAdapter
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DataAdapter
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
This worked by creating a new activity, then in on item click, get the item clicked position URL, send an intent to the activity with the image URL as extras. Get the image url from the intent in the activity then load the image.
The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the image. As of now when one clicks the image it only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RECYCLERVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CARDVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MAIN ACTIVITY
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RECYCLERVIEWADAPTER
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
IMAGEADAPTER
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DATAADAPTER
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
just when the user clicked on an item do like me...
Intent i = new Intent(context,BigImageActivity);
intent.putExtra("image_url",iamge_url);
context.startActivity(i);
in big_image_layout.xml
<ImageView
android:id="#+id/iv_big_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in onCreate BigImageActivity:
String img_url = getIntent.getStringExtra("image_url");
and for showing image use Glide:
Glide.with(context)
.load(img_url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontAnimate()
.into(iv_big_image);
and done!!!
I hope this useful for you.
I made it to show full images by fetching the url and parsing it to a new activity. Thanks for the positive responses
On RecyclerView data is not showing.
I have tried hard but i am unable to get the solution even i have search lot of questions on StackoverFlow and on other platforms as well.
I want to do like below attached image:
preview_image
Here's the code:
activity_data_sekretaris.xml
<?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"
tools:context=".Sekretaris.DataSekretarisActivity"
android:background="#color/colorPrimary">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/rc_data"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
SekretarisAdapter.java
package tgs.app.absensi;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import tgs.app.absensi.model.Sekretaris;
public class SekretarisAdapter extends RecyclerView.Adapter<SekretarisAdapter.ViewHolder> {
private List<Sekretaris.Siswa> dataSiswa;
private List<Sekretaris.Kelas> dataKelas;
public SekretarisAdapter(List<Sekretaris.Siswa> dataSiswa, List<Sekretaris.Kelas> dataKelas) {
this.dataSiswa = dataSiswa;
this.dataKelas = dataKelas;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_sekretaris, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.text_no.setText(dataSiswa.get(i).getId_siswa());
viewHolder.text_nis.setText(dataSiswa.get(i).getNIS());
viewHolder.text_nama.setText(dataSiswa.get(i).getNama_lengkap());
viewHolder.text_jenisk.setText(dataSiswa.get(i).getJenis_kelamin());
viewHolder.text_kelas.setText(dataKelas.get(i).getNama_kelas());
viewHolder.text_jurusan.setText(null);
viewHolder.text_status.setText(dataSiswa.get(i).getStatus());
}
#Override
public int getItemCount() {
return dataSiswa.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text_no, text_nis, text_nama, text_jenisk, text_kelas, text_jurusan, text_status;
public ViewHolder(#NonNull View itemView) {
super(itemView);
text_no = itemView.findViewById(R.id.text_no);
text_nis = itemView.findViewById(R.id.text_nis);
text_nama = itemView.findViewById(R.id.text_nama);
text_jenisk = itemView.findViewById(R.id.text_jenisKelamin);
text_kelas = itemView.findViewById(R.id.text_kelas);
text_jurusan = itemView.findViewById(R.id.text_jurusan);
text_status = itemView.findViewById(R.id.text_status);
}
}
}
DataSekretarisActivity.java
package tgs.app.absensi.Sekretaris;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import tgs.app.absensi.R;
import tgs.app.absensi.SekretarisAdapter;
import tgs.app.absensi.model.Sekretaris;
import tgs.app.absensi.retrofit.Api;
import tgs.app.absensi.retrofit.ApiInterface;
public class DataSekretarisActivity extends AppCompatActivity {
SwipeRefreshLayout swipe_refresh;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_sekretaris);
swipe_refresh = findViewById(R.id.swipe_refresh);
recyclerView = findViewById(R.id.rc_data);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
DataSekretaris();
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipe_refresh.setRefreshing(true);
DataSekretaris();
}
});
getSupportActionBar().setTitle("Data Absen Siswa");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void DataSekretaris(){
ApiInterface apiInterface = Api.getUrl().create(ApiInterface.class);
Call<Sekretaris> call = apiInterface.getSekretarisCall();
call.enqueue(new Callback<Sekretaris>() {
#Override
public void onResponse(Call<Sekretaris> call, Response<Sekretaris> response) {
swipe_refresh.setRefreshing(false);
List<Sekretaris.Siswa> detailSiswa = response.body().getReadSiswa();
List<Sekretaris.Kelas> detailKelas = response.body().getReadKelas();
recyclerView.setAdapter(new SekretarisAdapter(detailSiswa, detailKelas));
}
#Override
public void onFailure(Call<Sekretaris> call, Throwable t) {
}
});
}
#Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
}
could anyone fix my error? Thanks in advance.
You should first setup the RecyclerView correctly, like #AndrésR.C. says, by using a default adapter.
So, initialize your RecyclerView with something like this:
private RecyclerView mRvSekretaris;
private SekretarisAdapter mSkretarisAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mRvSekretaris = findViewById(R.id.rc_data);
mRvSekretaris.setLayoutManager(new LinearLayoutManager(this));
// initialize list with empty item
List<Sekretaris.Siswa> detailSiswa = new ArrayList<>();
List<Sekretaris.Kelas> detailKelas = new ArrayList<>();
mSkretarisAdapter = new SekretarisAdapter(detailSiswa, detailKelas);
mRvSekretaris.setAdapter(mSkretarisAdapter);
then when you want to refresh the list, you just need to swap the items adapter with swap method in your adapter:
mSkretarisAdapter.swap(detailSiswa, detailKelas);
with the following swap method:
public class SekretarisAdapter extends RecyclerView.Adapter<SekretarisAdapter.ViewHolder> {
private List<Sekretaris.Siswa> dataSiswa;
private List<Sekretaris.Kelas> dataKelas;
...
public swap(List<Sekretaris.Siswa> dataSiswa, List<Sekretaris.Kelas> dataKelas) {
this.dataSiswa = dataSiswa;
this.dataKelas = dataKelas;
notifyDataSetChanged();
}
}
Please take note that you should not swapping all the items instead you need to use something like DiffUtil
You can set adapter before making network call and passing empty lists,and making both list objects global
// initialize list with empty item
detailSiswa = new ArrayList<>();
detailKelas = new ArrayList<>()
mRvSekretaris.setLayoutManager(new LinearLayoutManager(this));
mSkretarisAdapter = new SekretarisAdapter(detailSiswa, detailKelas);
mRvSekretaris.setAdapter(mSkretarisAdapter);
And when you want to refresh the list, just call the refreshLists(dataSiswa,dataKelas);
private void refreshLists(ArrayListList<Sekretaris.Siswa> dataSiswa, ArrayListList<Sekretaris.Kelas> dataKelas){
detailSiswa.clear();
detailKelas.clear();
if(dataSiswa.size>0 && dataKelas.size>0){
detailSiswa.add(dataSiswa);
detailKelas.add(dataKelas);
}
mSkretarisAdapter.notifyDataSetChanged();
}
Also, while setting data from lists in BindViewHolder, make sure that size of dataKelas should be equal to or greater than dataSiswa as because BindViewHolder will be called as many number of times as is the size of dataSiswa because of
public int getItemCount() {
return dataSiswa.size();
}
So, when you are accessing any field from dataKelas, it can thrown null pointer exception if size of dataKelas is smaller than that of dataSiswa.