how to add Refresh swipe in RecyclerView - android

I have news app, which is provide news post from json url and I want to add refresh swipe to get news post. When I refresh the layout, how I can add it to my MainActivity and this my class here below:
public class MainActivity extends AppCompatActivity implements ExampleAdapter.OnItemClickListener {
public static final String EXTRA_URL = "imageUrl";
public static final String EXTRA_CREATOR = "creatorName";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
String API_KEY = "850e0efe6adf4eb38afefa14d33e4b48"; // ### YOUE NEWS API HERE ###
String NEWS_SOURCE = "bbc-news";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://newsapi.org/v1/articles?source="+NEWS_SOURCE+"&sortBy=top&apiKey="+API_KEY;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.optJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("title");
String imageUrl = hit.getString("urlToImage");
mExampleList.add(new ExampleItem(imageUrl, creatorName));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_CREATOR, clickedItem.getCreator());
startActivity(detailIntent);
}
}
Exampleadapter.java
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String imageUrl = currentItem.getImageUrl();
String creatorName = currentItem.getCreator();
holder.mTextViewCreator.setText(creatorName);
Picasso.with(mContext).load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextViewCreator;
public TextView mTextViewLikes;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
Exampleitem.java
public class ExampleItem {
private String mImageUrl;
private String mCreator;
public ExampleItem(String imageUrl, String creator) {
mImageUrl = imageUrl;
mCreator = creator;
}
public String getImageUrl() {
return mImageUrl;
}
public String getCreator() {
return mCreator;
}
}
activity_main.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="recylerviewjsonexample.codinginflow.com
.recylerviewjsonexample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray" />
exmple_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/text_view_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Creator Name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/text_view_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Like: " />
</LinearLayout>
</android.support.v7.widget.CardView>

Inside your XML file
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
In your java class you will clear your old list and than call your API method again
binding.refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (data_list != null) {
data_list.clear();
}
CallyourMethod();
binding.refreshLayout.setRefreshing(false);
}
});

You can place a SwipeRefreshLayout around your RecyclerView as:
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray" />
</android.support.v4.widget.SwipeRefreshLayout>
Inside your onCreateMethod() of MainActivity.java add
swipeRefreshLayout.setEnabled(true);
To show a loader when the list is swiped to refresh you can add:
swipeRefreshLayout.setProgressViewEndTarget(true, SWIPE_REFRESH_LAYOUT_OFFSET);
SwipeRefreshLayout provides the callback when the list is swiped to perform necessary action
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
//perform your action here
}
});

Related

multiple recyclerviews in one activity

I'm trying to make an app which has so many recyclerview, cardview init and all of them are in one activity. So, there are a lot of lists and these lists has horizontal orientation. I'm fetching data from JSON file and showing them on these lists. I know there is a long way to do it. But i believe there is more effective way to do it also. I'm not an expert. But i don't want to write so many different recyclerview, layoutmanager and adapter. So can you teach me how to do this?
Here is my codes;
Games.class;
public class Games extends AppCompatActivity {
RecyclerView recyclerView, recyclerView2;
ArrayList<ModelGames> modelGames;
private RequestQueue mQueue;
GamesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_games);
modelGames = new ArrayList<>();
recyclerView = findViewById(R.id.gamesPageRecyclerView);
recyclerView2 = findViewById(R.id.gamesPageRecyclerView2);
mQueue = Volley.newRequestQueue(this);
releasedOn19();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView.LayoutManager gamesLiLayoutManager = linearLayoutManager;
recyclerView.setLayoutManager(gamesLiLayoutManager);
adapter = new GamesAdapter(this, modelGames);
recyclerView.setAdapter(adapter);
}
private void releasedOn19() {
String popularIn2019 = "https://api.rawg.io/api/games?dates=2019-01-01,2019-12-31&ordering=-added";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, popularIn2019, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject result = jsonArray.getJSONObject(i);
String gameName = result.getString("name");
String gameImage = result.getString("background_image");
modelGames.add(new ModelGames(gameName, gameImage));
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
ModelGames;
public class ModelGames {
private String text, image;
public ModelGames(String text, String image) {
this.text = text;
this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
GamesAdapter;
public class GamesAdapter extends RecyclerView.Adapter<GamesAdapter.ViewHolder> {
private Context mContext;
private ArrayList<ModelGames> mList;
GamesAdapter(Context context, ArrayList<ModelGames> list){
mContext = context;
mList = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.rv_game_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ModelGames getItem = mList.get(position);
TextView gameName = holder.game_title;
ImageView gameImage = holder.game_image;
Glide.with(mContext).asBitmap().load(getItem.getImage()).into(gameImage);
gameName.setText(mList.get(position).getText());
}
#Override
public int getItemCount() {
return mList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView game_image;
TextView game_title;
public ViewHolder(#NonNull View itemView) {
super(itemView);
game_image = itemView.findViewById(R.id.cardviewImage);
game_title = itemView.findViewById(R.id.cardviewText);
}
}
}
And here is my activity_games.xml. I added second recyclerview. But i didn't use that in anywhere
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="165dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:text="2019 Yılında Çıkan Oyunlar"
android:textStyle="bold"
android:textSize="18sp"
android:gravity="center_horizontal|center_vertical"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/gamesPageRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="165dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:text="2018 Yılında Çıkan Oyunlar"
android:textStyle="bold"
android:textSize="18sp"
android:gravity="center_horizontal|center_vertical"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/gamesPageRecyclerView2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

Nested Recycler view is laggy while scrolling for the first time

Here, I have two recyclerview that has parentRecyclerViewAdapter and childRecyclerViewAdapter. Parent adapter has LinearLayoutManager.VERTICAL layout manager whereas Clild adapter has GridLayoutManager(mContext, 2) layout manager with itemDecoration.
When scrolling for the first time the RecyclerView scrolling is laggy and once the data is viewed the scrolling is smooth. Until the app instance is not completely removed the scrolling will be smooth and when the app reinitiate the scrolling is laggy again.
Please help me out to figure out this BUG!!
ParentRecyclerViewAdapter
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<SectionDataModel> dataList;
private Context mContext;
private RecyclerListItemClick onListClick;
public RecyclerViewDataAdapter(Context context, ArrayList<SectionDataModel> dataList) {
this.dataList = dataList;
this.mContext = context;
onListClick = (RecyclerListItemClick) context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
return new ItemRowHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_row_template_section, null));
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
ArrayList<SingleTemplateModel> templateModelArrayList = dataList.get(i).getTemplateModelArrayList();
String sectionName = dataList.get(i).getHeaderTitle();
itemRowHolder.itemTitle.setText(sectionName);
TemplateChooserAdapter itemListDataAdapter = new TemplateChooserAdapter(mContext, templateModelArrayList , dataList.get(i).getHeaderTitle());
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView itemTitle;
private RecyclerView recycler_view_list;
private ItemRowHolder(View view) {
super(view);
this.itemTitle = view.findViewById(R.id.itemTitle);
this.recycler_view_list = view.findViewById(R.id.recycler_view_list);
this.recycler_view_list.setOnClickListener(this);
this.recycler_view_list.setHasFixedSize(true);
this.recycler_view_list.setLayoutManager(new GridLayoutManager(mContext, 2));
this.recycler_view_list.addItemDecoration(new SpacesItemDecoration(2 , 25 , false));
}
#Override
public void onClick(View v) {
onListClick.onRecyclerItemClicked(dataList.get(getAdapterPosition()).getHeaderTitle());
}
}
}
ChildRecyclerAdapter
public class TemplateChooserAdapter extends RecyclerView.Adapter<TemplateChooserAdapter.ViewHolder> {
private static final String TAG = TemplateChooserAdapter.class.getSimpleName();
private Context context;
private ArrayList<SingleTemplateModel> templateModelArrayList;
private OnTemplatesListClicked onListClick;
public TemplateChooserAdapter(Context context, ArrayList<SingleTemplateModel> templateModelArrayList, String sectionName) {
this.context = context;
this.templateModelArrayList = templateModelArrayList;
onListClick = (OnTemplatesListClicked) context;
AppUtils.showLog(TAG, "CorporateUserAdapter");
}
#Override
public TemplateChooserAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(parent.getContext()).inflate(R.layout.single_row_template_chooser, parent, false)
);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.templateView.setImageResource(templateModelArrayList.get(position).getImage());
}
#Override
public int getItemCount() {
return templateModelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView templateView;
public ViewHolder(View itemView) {
super(itemView);
templateView = itemView.findViewById(R.id.template_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
templateModelArrayList.get(getAdapterPosition()).setShowIndicator(true);
onListClick.onTemplateClick(templateModelArrayList.get(getAdapterPosition())); // TODO send model when item clicked
}
}
}
Activity.java
private void recyclerViewJob() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(this, allSampleData);
recyclerView.setAdapter(adapter);
}
SectionDataModel.java
public class SectionDataModel {
private String headerTitle;
private ArrayList<SingleTemplateModel> templateModelArrayList;
public SectionDataModel() {
}
public SectionDataModel(String headerTitle, ArrayList<SingleTemplateModel> templateModelArrayList) {
this.headerTitle = headerTitle;
this.templateModelArrayList = templateModelArrayList;
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<SingleTemplateModel> getTemplateModelArrayList() {
return templateModelArrayList;
}
public void setTemplateModelArrayList(ArrayList<SingleTemplateModel> templateModelArrayList) {
this.templateModelArrayList = templateModelArrayList;
}
}
SingleTemplateModel.java
public class SingleTemplateModel {
private String title;
private String skuName;
private int image;
private boolean showIndicator;
public SingleTemplateModel(String title, String skuName, int image, boolean showIndicator) {
this.title = title;
this.skuName = skuName;
this.image = image;
this.showIndicator = showIndicator;
}
public String getSkuName() {
return skuName;
}
public void setSkuName(String skuName) {
this.skuName = skuName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public boolean isShowIndicator() {
return showIndicator;
}
public void setShowIndicator(boolean showIndicator) {
this.showIndicator = showIndicator;
}
}
single_row_template_section.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="30dp"
android:clickable="true"
android:focusable="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/itemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:text="Sample title"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
android:paddingLeft="5dp"
android:paddingBottom="10dp"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
single_row_template_chooser.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="280dp"
card_view:cardElevation="6dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/template_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#mipmap/model_9" />
</RelativeLayout>
</android.support.v7.widget.CardView>
I think you can try to lazy load your images from resources. There are libraries like Picasso or Glide that will help you with that.
So it may look like this:
Picasso:
import com.squareup.picasso.Picasso;
...
public class TemplateChooserAdapter extends RecyclerView.Adapter<TemplateChooserAdapter.ViewHolder> {
...
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Picasso.with(holder.itemView.getContext()).load(templateModelArrayList.get(position).getImage()).into(holder.templateView);
}
...
}

Android volley recyclerview not showing data

I spent a lot of time debugging this code but unfortunately could not find the bug, can someone help me find the issue in this code. I am not able to see data on the activity page. Although I have found the I am getting response data from the server.
Activity Class
public class SelectServiceActivity extends AppCompatActivity {
private TextView textView;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_service);
recyclerView = (RecyclerView) findViewById(R.id.select_service_rv);
String serviceTypeId = getIntent().getStringExtra(AppConstants.SELECTED_SERVICE_TYPE_ID);
getProductDetailsByProductId(serviceTypeId);
}
private void getProductDetailsByProductId(String serviceTypeId) {
final List<SelectServiceBean> selectServiceList = new ArrayList<>();
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
APIEndpoints.SERVICE_LIST_URI + serviceTypeId,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
selectServiceList.add(DatabaseObjectsMapper.selectServiceBeanMapper((JSONObject) response.get(i)));
} catch (JSONException e) {
Toast.makeText(SelectServiceActivity.this, "Something went wrong : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
recyclerView.setAdapter(new SelectServiceAdapter(getApplicationContext(),selectServiceList));
} else {
Toast.makeText(SelectServiceActivity.this, "No Response From Server!", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SelectServiceActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
VolleySingleton.getInstance(SelectServiceActivity.this).addToRequestQueue(jsonArrayRequest);
}
}
Adapter Class
public class SelectServiceAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<SelectServiceBean> selectServiceList;
public SelectServiceAdapter(final Context context, final List<SelectServiceBean> selectServiceList) {
this.context = context;
this.selectServiceList = selectServiceList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(context).inflate(R.layout.item_select_service, parent, false);
return (new Item(row));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((Item) holder).serviceTypeIssue.setText(selectServiceList.get(position).getServiceTypeIssue());
((Item) holder).serviceTypeIssue.setText(selectServiceList.get(position).getServiceType());
}
#Override
public int getItemCount() {
return selectServiceList.size();
}
public static class Item extends RecyclerView.ViewHolder {
private TextView serviceTypeIssue;
private TextView serviceType;
public Item(View view) {
super(view);
serviceTypeIssue = view.findViewById(R.id.service_type_issue);
}
}
}
Single View Item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/service_type_issue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Sample text" />
<android.support.v7.widget.AppCompatCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1sp"
android:background="#color/lightGrey" />
</LinearLayout>
Recyclerview File
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/select_service_rv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
From docs
A LayoutManager must be provided for RecyclerView to function.
You need to add the layoutManager
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_service);
recyclerView = (RecyclerView) findViewById(R.id.select_service_rv);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
//^^^^^^^^^^^
recyclerView.setLayoutManager(mLayoutManager);
//^^^^^^^^^^^^^^^^^^^^
String serviceTypeId = getIntent().getStringExtra(AppConstants.SELECTED_SERVICE_TYPE_ID);
getProductDetailsByProductId(serviceTypeId);
}
Improvement :
Initialize serviceType in Item class and use it in onBindViewHolder
public Item(View view) {
super(view);
serviceTypeIssue = view.findViewById(R.id.service_type_issue);
serviceType = view.findViewById(R.id.yourID);
//^^^^^^^
}
Keep a reference to new SelectServiceAdapter so that later you can use notify functions for more optimal performance
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((Item)holder).serviceTypeIssue.setText(selectServiceList.get(position).getServiceTypeIssue());
((Item)holder).serviceType.setText(String.valueOf(selectServiceList.get(position).getServiceType()));
//^^^^^^^^
}

Android setonclicklistener is not working recycler header

I am developing an app using recycler header. And my recycler having header. The source code recycler header is shown in https://github.com/blipinsk/RecyclerViewHeader.
I want to active the set on click listener in recycler header. when i click the recycler header it shows a toasted message. My code is given below.
I am using in fragment.
HomeFragment.java
public class HomeFragment extends android.support.v4.app.Fragment {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
RecyclerViewHeader recyclerHeader;
String GET_JSON_DATA_HTTP_URL;
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
String JSON_IMAGE_ID = "id";
String JSON_MRP = "mrp";
String JSON_RATE = "rate";
String JSON_DISCOUNT = "discount";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Home");
GET_JSON_DATA_HTTP_URL = Util.URL_SERVER + "categories.php";
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview3);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
recyclerHeader = (RecyclerViewHeader) rootView.findViewById(R.id.header);
recyclerHeader.attachTo(recyclerView);
recyclerHeader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG", "clicked");
}
});
JSON_DATA_WEB_CALL();
// Inflate the layout for this fragment
return rootView;
}
public void JSON_DATA_WEB_CALL(){
final ProgressDialog progressDialog = new ProgressDialog(getContext(), R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Loading");
progressDialog.show();
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
Log.d("LOGTAG", "Response :"+response);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleName(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setImageId(json.getString(JSON_IMAGE_ID));
GetDataAdapter2.setMrp(json.getString(JSON_MRP));
GetDataAdapter2.setDiscount(json.getString(JSON_DISCOUNT));
//Log.d("LOGTAG", "JSON_MRP : "+json.getString(JSON_MRP)+"JSON_RATE : "+json.getString(JSON_RATE)+"JSON_DISCOUNT :"+json.getString(JSON_DISCOUNT));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static String categoryId;
Context context;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
private final View.OnClickListener mOnClickListener = new MyOnClickListener();
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.subcategory_items, parent, false);
v.setOnClickListener(mOnClickListener);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
Viewholder.Mrp.setText(getDataAdapter1.getMrp());
Viewholder.Discount.setText(getDataAdapter1.getDiscount());
categoryId = getDataAdapter1.getImageTitleName();
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//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.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView imageid;
public NetworkImageView networkImageView ;
public CardView cardView ;
public TextView Mrp;
public TextView Rate;
public TextView Discount;
public ViewHolder(final View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
cardView = (CardView) itemView.findViewById(R.id.cardview1);
Mrp = (TextView) itemView.findViewById(R.id.textViewMrp) ;
Rate = (TextView) itemView.findViewById(R.id.textViewRate) ;
Discount = (TextView) itemView.findViewById(R.id.textViewDiscount) ;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
Log.d("LOGTAG", "position : "+pos);
Log.d("LOGTAG", "position : "+getDataAdapter.get(pos).getImageId());
ProductFragment fragobj=new ProductFragment();
Bundle bundle=new Bundle();
bundle.putString("subcategory_Product_ID", getDataAdapter.get(pos).getImageId());
fragobj.setArguments(bundle);
switchFragment(R.id.container_body, fragobj); //replace container ID
}
});
}
}
public void switchFragment(int id, Fragment fragment) {
if (context == null)
return;
//MainActivity is your activity where FriendsFragment is called
if (context instanceof HomeActivity) {
HomeActivity homeActivity = (HomeActivity) context;
homeActivity.loadFragment(id, fragment);
}
}
private class MyOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
GetDataAdapter getDataAdapter = new GetDataAdapter();
}
}
}
fragment_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/title_padding"
android:paddingRight="#dimen/title_padding">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"/>
<com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="#dimen/header_height"
android:layout_gravity="center_horizontal|top"
android:layout_margin="#dimen/recycler_divider_width"
android:background="#drawable/rounded_background_header">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="?selectableItemBackgroundBorderless"
android:fontFamily="sans-serif-light"
android:textAllCaps="false"
android:text="#string/header"
android:textColor="#color/clouds"
android:textSize="20sp"/>
</com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader>
</FrameLayout>
layout_item
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/recycler_divider_width"
android:background="#drawable/round_background_green">
<TextView
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_gravity="center"
android:gravity="center"
android:fontFamily="sans-serif-light"
android:text="#string/item"
android:textSize="16sp"
android:textColor="#color/clouds" />
</FrameLayout>
You're setting your OnClickListener on the RecyclerViewHeader, when I believe you want to set it on the button you have inside your RecyclerViewHeader.
Add an android:id to the Button in your RecyclerViewHeader
<Button
android:id="#+id/button_header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="?selectableItemBackgroundBorderless"
android:fontFamily="sans-serif-light"
android:textAllCaps="false"
android:text="#string/header"
android:textColor="#color/clouds"
android:textSize="20sp"/>
Find this Button in your HomeFragment
recyclerHeader = (RecyclerViewHeader) rootView.findViewById(R.id.header);
recyclerHeader.attachTo(recyclerView);
Button headerButton = (Button) recyclerHeader.findViewById(R.id.button_header);
Set OnClickListener on the headerButton instead of the RecyclerViewHeader
headerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG", "clicked");
}
});
I think the reason why onClickListener don't work for RecyclerViewHeader because inside RecyclerViewHeader you have a Button.
This button will display above RecyclerViewHeader have width/height match RecyclerViewHeader.
So you will never be able to click on RecyclerViewHeader, just able to click on Button
If you still want to handle onClickListener on RecyclerViewHeader, you need set the size of Button smaller then you can click RecyclerViewHeader

No adapter attached skipping layout in recyclerview using fragment

I got an error in recycler view using fragment. I have read stackoverflow answers but it not solve. PLease help me.
Recycler reference tutorial
http://www.android-examples.com/android-recyclerview-listview-with-imageview-textview-json/
When i use in without fragment it work as fine but in fragment it shows error.
My codes shown below.
FriendsFragment.java
public class FriendsFragment extends android.support.v4.app.Fragment {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.43.7/work/ecom/2/1.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
// Inflate the layout for this fragment
return rootView;
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("LOGTAG", "Response :"+response);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//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.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
}
}
}
fragment_friends.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ecom.fragment2.FriendsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
recyclerview_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.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="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Image Name"
android:id="#+id/textView_item"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
You should make your custom linearlayout manager. Sometimes there is a scenario: If you scroll fast then there causes Exception in you recycleView. To avoid this problem you have to implement your custom layout manager like below:
public class CustomLinearLayoutManager extends LinearLayoutManager {
private Context mContext;
public CustomLinearLayoutManager(Context context, int orientation,boolean reverseLayout){
super(context, orientation, reverseLayout);
mContext=context;
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
Constants.errorLog("onLayoutChildren :" , e.toString());
}
}
}
Now use this layout manager in your recycleview like this:
LinearLayoutManager recyclerViewlayoutManager = new CustomLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(recyclerViewlayoutManager );
Hope you will now avoid the exception i mentioned.
The problem is adding permission in manifest file.
Add
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
It work as fine.

Categories

Resources