I use rretrofit library to get data from server. Try for Log, data successful giving for me.But in RecyclerView I don't have any data. Inside videoview I see only a black figure and both txtview are empty. How I can transfer this data to recyclerview?
My fragment with response:
public class FeaturedFragment extends Fragment {
RecyclerViewAdapter recyclerViewAdapter;
public static final String ROOT_URL = "https://api.vid.me/";
public List<Video> videos;
RecyclerView recList;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_featured, container, false);
recList = (RecyclerView) rootView.findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
try {
getVideos();
} catch (IOException e) {
e.printStackTrace();
}
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void getVideos() throws IOException {
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
Call<Videos> call = videoApi.getFeaturedVideo();
call.enqueue(new Callback<Videos>() {
#Override
public void onResponse(Call<Videos> call, Response<Videos> response) {
Log.d("MainActivity", "Status Code = " + response.code());
Log.d("MainActivity", "Status Code = " + response.body().videos.get(1).getTitle());
Log.d("MainActivity", "Status Code = " + response.body().videos.get(1).getScore());
Log.d("MainActivity", "Status Code = " + response.body().videos.get(1).getClipUrl());
videos = response.body().videos;
recyclerViewAdapter = new RecyclerViewAdapter(videos);
recList.setAdapter(recyclerViewAdapter);
}
#Override
public void onFailure(Call<Videos> call, Throwable t) {
}
});
}
}
RecyclerViewAdapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.VideoViewHolder> {
List<Video> call;
RecyclerViewAdapter(List<Video> call){
this.call = call;
}
#Override
public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row,parent,false);
VideoViewHolder videoViewHolder = new VideoViewHolder(v);
return videoViewHolder;
}
#Override
public void onBindViewHolder(VideoViewHolder holder, int position) {
String video_url = call.get(position).getClipUrl();
holder.videoView.setVideoURI(Uri.parse(video_url));
holder.video_name.setText(call.get(position).getTitle());
// holder.video_like.setText(call.get(position).getScore());
}
#Override
public int getItemCount() {
return call.size();
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
VideoView videoView;
TextView video_name;
TextView video_like;
public VideoViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card_view);
videoView = (VideoView)itemView.findViewById(R.id.videoview);
video_name = (TextView) itemView.findViewById(R.id.Videoname_textView);
video_like = (TextView) itemView.findViewById(R.id.like_textview);
}
}
}
card_view_row.xml:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="180dp"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="130dp"
android:padding="10dp"
>
<VideoView
android:layout_width="match_parent"
android:layout_height="130dp"
android:id="#+id/videoview"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/Videoname_textView"
android:text="NameofVideo"
android:layout_below="#id/videoview"
android:layout_marginTop="4dp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/like_textview"
android:text="Likes"
android:layout_alignRight="#id/videoview"
android:layout_below="#id/videoview"
android:layout_marginTop="4dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Does your list is has items but items is not show its contents? So, please check items view. If your list has no item, check your Adapter constructor or log itemcount
Related
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>
Silly question probably but i cant find why my RecyclerView not responding to clicks. The RV is in a fragment, i added an interface to the adapter and im implementing it to the fragment. But while trying the click the emulator does not even does the "click" sound
This is my adapter
public class ArtistsRvAdapter extends RecyclerView.Adapter<ArtistsRvAdapter.ArtistViewHolder> {
private List<Artist> mArtists;
private Context mContext;
final private ItemClickListener mItemClickListener;
public ArtistsRvAdapter(Context c, ItemClickListener listener){
mContext=c;
mItemClickListener =listener;
}
#NonNull
#Override
public ArtistsRvAdapter.ArtistViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
int layoutIdForListItem = R.layout.artist_list_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
ArtistViewHolder viewHolder = new ArtistViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ArtistViewHolder artistViewHolder, int position) {
Artist artist = this.mArtists.get(position);
Log.d("rv adapter ", "artist img " + artist.getArtistImageUrl());
String image = artist.getArtistImageUrl();
Picasso.get()
.load(image)
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_foreground)
.into(artistViewHolder.artistImage);
artistViewHolder.artistName.setText(artist.getArtistName());
Log.d("rv adapter ", "artist name " + artist.getArtistName());
artistViewHolder.artistGenre.setText(artist.getArtistGenre());
artistViewHolder.concertDate.setText(artist.getConcertDate());
artistViewHolder.concertLocation.setText(artist.getConcertLocation());
}
#Override
public int getItemCount() {
return (null != mArtists ? mArtists.size() : 0);
}
public class ArtistViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView artistImage;
TextView artistName;
TextView artistGenre;
TextView concertLocation;
TextView concertDate;
public ArtistViewHolder(View itemView){
super(itemView);
artistImage = itemView.findViewById(R.id.artist_image);
artistName = itemView.findViewById(R.id.artist_name);
artistGenre = itemView.findViewById(R.id.artist_genre);
concertLocation = itemView.findViewById(R.id.concert_location);
concertDate = itemView.findViewById(R.id.concert_date);
}
#Override
public void onClick(View v) {
String elementID = mArtists.get(getAdapterPosition()).getKey();
Log.d(" adapter " , "position clicked " + getAdapterPosition());
mItemClickListener.onItemClickListener(elementID);
}
}
public interface ItemClickListener {
void onItemClickListener(String itemId);
}
public void setArtists(List<Artist> artists){
mArtists = artists;
Log.d("rv " , "list artists " + mArtists);
notifyDataSetChanged();
}
}
And this is the fragment
public class BaseFragment extends Fragment implements ArtistsRvAdapter.ItemClickListener {
private ArtistsRvAdapter mAdapter;
private String LOG_TAG = BaseFragment.class.getSimpleName();
private View mRootView;
#BindView(R.id.rv)
RecyclerView recyclerView;
private Context mContext;
private AppDatabase mDb;
public BaseFragment(){}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mRootView= inflater.inflate(R.layout.base_fragment, container, false);
ButterKnife.bind(this, mRootView);
mContext = getActivity().getApplicationContext();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
mDb = AppDatabase.getInstance(getActivity());
mAdapter = new ArtistsRvAdapter(mContext, this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(mAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
((LinearLayoutManager) layoutManager).getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
setupViewModel();
return mRootView;
}
private void setupViewModel(){
Log.d(LOG_TAG, "getting artists from DB");
DetailsViewModel viewModel = ViewModelProviders.of(getActivity()).get(DetailsViewModel.class);
viewModel.getArtists().observe(this, new Observer<List<Artist>>() {
#Override
public void onChanged(List<Artist> artists) {
mAdapter.setArtists(artists);
}
});
}
#Override
public void onItemClickListener(String itemId) {
Intent i = new Intent(getActivity(), DetailsActivity.class);
i.putExtra("artistId", itemId);
startActivity(i);
}
}
This is the xml
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="6dp"
android:theme="#style/Theme.Bacon.AppBarOverlay"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:layout_gravity="bottom">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:src="#mipmap/logo"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/min_margin_dp"
android:layout_marginLeft="#dimen/min_margin_dp"
android:layout_marginTop="#dimen/rv_margin"
android:layout_marginEnd="#dimen/min_margin_dp"
android:layout_marginRight="#dimen/min_margin_dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout">
</androidx.recyclerview.widget.RecyclerView>
please add this line "itemView.setOnClickListener(this);" in "ArtistViewHolder"s constructor
public ArtistViewHolder(View itemView){
super(itemView);
artistImage = itemView.findViewById(R.id.artist_image);
artistName = itemView.findViewById(R.id.artist_name);
artistGenre = itemView.findViewById(R.id.artist_genre);
concertLocation = itemView.findViewById(R.id.concert_location);
concertDate = itemView.findViewById(R.id.concert_date);
itemView.setOnClickListener(this);
};
In your ArtistViewHolder after super(itemView); add
itemView.setOnClickListener(this);
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()));
//^^^^^^^^
}
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
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.