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()));
//^^^^^^^^
}
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>
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
}
});
I'm doing some tests with a project. I am using Volley to consume a Web Service and display the data in a ReciclerView. I get a response but they are not shown in the widget. I have put a Toast to verify that I really have a response from the web service. Something is failing. The list is displayed before you get the data from the web service, Why?
This is my Activity
public class ListMockio extends AppCompatActivity {
private RecyclerView mList;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private List<Movie> movieList;
private RecyclerView.Adapter adapter;
private String url = "http://www.mocky.io/v2/5b7af6c73400005f008ed7b2"; // LisT varios
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_mockio);
mList = (RecyclerView) findViewById(R.id.main_list);
movieList = new ArrayList<>();
adapter = new MovieAdapter(getApplicationContext(),movieList);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
// Call to web Service
getData();
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject jsonObject = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getInt("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
Toast.makeText(getApplicationContext(), "Respuesta " + jsonObject.getString("title"), Toast.LENGTH_SHORT).show();
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
Adapter code
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private Context context;
private List<Movie> list;
public MovieAdapter(Context context, List<Movie> list) {
this.context = context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Movie movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.textRating.setText(String.valueOf(movie.getRating()));
holder.textYear.setText(String.valueOf(movie.getYear()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textTitle, textRating, textYear;
public ViewHolder(View itemView) {
super(itemView);
textTitle = (TextView) itemView.findViewById(R.id.main_title);
textRating = (TextView) itemView.findViewById(R.id.main_rating);
textYear = (TextView) itemView.findViewById(R.id.main_year);
}
}
}
single_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/main_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="18sp"/>
<TextView
android:id="#+id/main_rating"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rating"/>
<TextView
android:id="#+id/main_year"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Year"/>
</LinearLayout>
And my ReciclerView activity_list_mockio.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
android:id="#+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
Result
In your declaration, in ListMockio class, change:
private RecyclerView.Adapter adapter;
To:
private MovieAdapter adapter;
Hopefully this should solve your issue.
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.
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