i want to make realtime changing data On RecyclerView - java

I'am trying to make refresh every 1 sec in my RecyclerView but i don't know how can i do it iam using my API , when something changed in my api i want to make that change in my RecylerView whitout the swiper or i want to make the swiper swipe every 1 sec .. so this is my Code :
public class InformationNow extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private RequestQueue requestQueue;
private SwipeRefreshLayout refresh;
private ArrayList<TrashCanModel> trashCanModels = new ArrayList<>();
private JsonArrayRequest arrayRequest;
private Dialog dialog;
private RecyclerView recyclerView;
private InformationNowAdapter informationNowAdapter ;
private String url = "http://192.168.1.34:9090/TrashCanData/lastrow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_now);
refresh = (SwipeRefreshLayout) findViewById(R.id.Swiper);
recyclerView = (RecyclerView) findViewById(R.id.Now);
dialog = new Dialog(this);
refresh.setOnRefreshListener(this);
refresh.post(new Runnable() {
#Override
public void run() {
trashCanModels.clear();
getData();
}
});
}
private void getData() {
refresh.setRefreshing(true);
arrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
//JSONArray jsonArray = response.getJSONArray("users");
jsonObject = response.getJSONObject(i);
TrashCanModel cat = new TrashCanModel();
cat.setDistance(jsonObject.getInt("distance"));
cat.setTemperature(jsonObject.getInt("temperature"));
cat.setHumidity(jsonObject.getInt("humidity"));
Log.e("*********", cat.getDistance().toString());
Log.e("*********", cat.getTemperature().toString());
Log.e("*********", cat.getHumidity().toString());
trashCanModels.add(cat);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapterPush(trashCanModels);
refresh.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(InformationNow.this);
requestQueue.add(arrayRequest);
}
private void adapterPush(ArrayList<TrashCanModel> trashCanModels) {
informationNowAdapter = new InformationNowAdapter(this, trashCanModels);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(informationNowAdapter);
}
#Override
public void onRefresh() {
trashCanModels.clear();
getData();
}
}
and my adapter :
public class InformationNowAdapter extends RecyclerView.Adapter<InformationNowAdapter.MyViewHolder>{
private Context context ;
private ArrayList<TrashCanModel> trashCanModels;
private String url = "";
//
public InformationNowAdapter (Context context , ArrayList<TrashCanModel> trashCanModels) {
this.context = context;
this.trashCanModels=trashCanModels;
}
#NonNull
#Override
public InformationNowAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view ;
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.trashcan_list , parent , false);
return new InformationNowAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull InformationNowAdapter.MyViewHolder holder, int position) {
//holder.id.setText("#"+String.valueOf(position+1));
holder.distance.setText(trashCanModels.get(position).getDistance().toString());
holder.temperature.setText(trashCanModels.get(position).getTemperature().toString());
holder.humidity.setText(trashCanModels.get(position).getHumidity().toString());
}
#Override
public int getItemCount() {
return trashCanModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView distance , temperature , humidity ;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
distance = (TextView) itemView.findViewById(R.id.distance);
temperature = (TextView) itemView.findViewById(R.id.temperature);
humidity = (TextView) itemView.findViewById(R.id.humidity);
//
}
}
}
so how can i make refresh data every 1 sec !

You can use Timer to do that
Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
trashCanModels.clear();
getData();
}
}, 0, 1000);
call repeatTask.cancel() when you want to stop
But I think you should use push notification when your api change or use firebase or socket.io instead

Related

create recycler view in fragment?

i want create a fragment and have inside a recycler view for show products ...
but when i render it is show this error : RecyclerView: No adapter attached; skipping layout
below i copy my codes;
this code is for adapter class :
private ArrayList<Products> ProductsList;
private Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}
and this one for web api class :
public class WebApiHandler {
Context context;
String apiLink = "";
ArrayList<Products> products = new ArrayList<>();
public WebApiHandler(Context context) {
this.context = context;
}
void apiConnect(String type) {
switch (type) {
case "getproducts": {
apiLink = Config.getProductsWebApi;
break;
}
}
ProgressDialog dialog = ProgressDialog.show(context, "Connecting...",
"please wait", false, false);
StringRequest request = new StringRequest(Request.Method.POST,
apiLink, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
showJson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
}
private void showJson(String response) {
products.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
VerticalFragment.productsArrayList = products;
IData iData = (IData) context;
iData.sendData();
}}
and my fragment code :
public class VerticalFragment extends Fragment implements IData {
RecyclerView rcVertical;
WebApiHandler webApiHandler;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical, container, false);
rcVertical = view.findViewById(R.id.rcVertical);
webApiHandler = new WebApiHandler(getContext());
webApiHandler.apiConnect("getproducts");
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getContext(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
#Override
public void sendData() {
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager((getContext())));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
}}
i should say i create a interface and have one method i say it sendData
This is a common error when there is no adapter attached to recyclerview upon showing recyclerview. It will not cause any harm to your app, but you could avoid it by setting empty adapter without data, and later when you get your data, provide it to your adapter and notify it
Edit - Example added
Create setter for your list in adapter. After that, in your fragment make adapter global and in onCreateView make instance of your adapter and attach it to recyclerview
adapter = new Adapter(new ArrayList<>(), getContext());
rcVertical.setAdapter(adapter);
...Initialize recyclerview...
And then in your sendData interface put your loaded values in it
adapter.setData(productsArrayList);
adapter.notifyDataSetChanged();

Issue with android Recyclerview adapter in JSON Parsing using volley

I am new to android development and recently working on a so called covid tracker app.
I ran into the issue of recyclerview "no adapter attached skipping layout". I'm using volley library for networking and parsing the data straight into my app. the json part is working absolutely fine, but the real issue I'm facing is my app crashes after opening and recyclerview is not showing any data.
My code goes like this:
This is the Mainactivity class:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerview;
private ExampleAdapter mExampleAdapter;
private ArrayList<exampleItem> mExampleList;
RequestQueue requestQueue;
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<>();
requestQueue = Volley.newRequestQueue(this);
fetchdata();
}
public void fetchdata(){
String url = "https://api.rootnet.in/covid19-in/stats/latest";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject data = response.getJSONObject("data");
JSONArray regionalArray = data.getJSONArray("regional");
for (int i = 0; i < regionalArray.length(); i++) {
JSONObject statewise = regionalArray.getJSONObject(i);
String statename = statewise.getString("loc");
int totalconfirmed = statewise.getInt("totalConfirmed");
int discharged = statewise.getInt("discharged");
int death = statewise.getInt("deaths");
mExampleList.add(new exampleItem(statename,totalconfirmed,discharged,death));
Log.i("list",statename+totalconfirmed+discharged+death);
}
Log.i("list", mExampleList.toString());
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mExampleAdapter.notifyDataSetChanged();
mRecyclerview.setAdapter(mExampleAdapter);
} catch (Exception e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
This is my adapter class:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<exampleItem> mExampleList;
public ExampleAdapter(Context context, ArrayList<exampleItem> exampleList){
mContext=context;
mExampleList=exampleList;}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.covid_data_layout,parent,false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
String stateName = currentItem.getState();
int confirmed = currentItem.getConfirmed();
int recovered = currentItem.getRecovered();
int death = currentItem.getDeath();
holder.statetextView.setText(stateName);
holder.confirmedtextview.setText(confirmed);
holder.recoveredTextView.setText(recovered);
holder.deathtextView.setText(death);
holder.activeTextView.setText(confirmed-recovered-death);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView statetextView;
public TextView confirmedtextview;
public TextView recoveredTextView;
public TextView deathtextView;
public TextView activeTextView;
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
statetextView = itemView.findViewById(R.id.state_textView);
confirmedtextview = itemView.findViewById(R.id.confirmed_textView);
recoveredTextView= itemView.findViewById(R.id.recovered_textView);
deathtextView = itemView.findViewById(R.id.death_textView);
activeTextView= itemView.findViewById(R.id.active_textView);
}
}
}
this is my javaclass for information:
public class exampleItem {
private String mState;
private int mConfirmed;
private int mRecovered;
private int mDeath;
public exampleItem(String state, int confirmed,int recovered,int death){
mState=state;
mConfirmed=confirmed;
mRecovered=recovered;
mDeath=death;
}
public String getState(){
return mState;
}
public int getConfirmed(){
return mConfirmed;
}
public int getRecovered(){
return mRecovered;
}
public int getDeath(){
return mDeath;
}
}
For any help, i'll be extremely grateful.
Thank you!
Remove mExampleAdapter.notifyDataSetChanged(); from your MainActivity and in Adapter calss update the code onBindViewHolder like this.
String stateName = mExampleList.get(position).getState();
int confirmed = mExampleList.get(position).getConfirmed();
int recovered = mExampleList.get(position).getRecovered();
int death = mExampleList.get(position).getDeath();
holder.statetextView.setText(stateName);
holder.confirmedtextview.setText(String.valueOf(confirmed));
holder.recoveredTextView.setText(String.valueOf(recovered));
holder.deathtextView.setText(String.valueOf(death));
holder.activeTextView.setText(String.valueOf(confirmed-recovered-death));

Show wrong data when filtered RecyclerView item is clicked

I have a RecyclerView with edittext for search in my android app. When I search in it and click on an item, it shows wrong data.
I know why it happens but I don't know how to fix it. I have tried many things but still I have the problem. i am new in programming, please help :).
Here is the code of my Adapter.
public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ProjectViewHolder> {
private Context mCtx;
private List<Project> projectList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ProjectAdapter(Context mCtx, List<Project> projectList) {
this.mCtx = mCtx;
this.projectList = projectList;
}
#Override
public ProjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.project_list, null);
return new ProjectAdapter.ProjectViewHolder(view);
}
#Override
public void onBindViewHolder(ProjectViewHolder holder, int position) {
Project project = projectList.get(position);
holder.textViewProject.setText(project.getProject());
}
#Override
public int getItemCount() {
return projectList.size();
}
class ProjectViewHolder extends RecyclerView.ViewHolder {
TextView textViewProject;
public ProjectViewHolder(View itemView) {
super(itemView);
textViewProject = itemView.findViewById(R.id.textViewProject);
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);
}
}
}
});
}
}
}
and this is my ListprojectActivity.java
public class ListprojectActivity extends AppCompatActivity implements ProjectAdapter.OnItemClickListener {
public static final String project_select = "project";
private static final String URL_PRODUCTS = "http://192.168.43.245/android_register_login/Api_1.php";
EditText editTextProject;
//a list to store all the products
List<Project> projectList;
//the recyclerview
RecyclerView recyclerView;
ProjectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listproject);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recylcerViewProject);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
editTextProject = findViewById(R.id.EditTextProject);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
DividerItemDecoration itemDecoration = new DividerItemDecoration(this, layoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(itemDecoration);
//initializing the productlist
projectList = new ArrayList<>();
editTextProject.addTextChangedListener (new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
final String query = s.toString().toLowerCase().trim();
final ArrayList<Project> filteredList = new ArrayList<>();
for (int i = 0; i < projectList.size(); i++) {
final String text = projectList.get(i).getProject().toLowerCase();
if (text.contains(query)) {
filteredList.add(projectList.get(i));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(ListprojectActivity.this));
adapter = new ProjectAdapter(ListprojectActivity.this, filteredList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(ListprojectActivity.this);
adapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
//this method will fetch and parse json
//to display it in recyclerview
loadProjects();
}
private void loadProjects() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject project = array.getJSONObject(i);
//adding the product to product list
projectList.add(new Project(
project.getInt("id_project"),
project.getString("project")
));
}
//creating adapter object and setting it to recyclerview
ProjectAdapter adapter = new ProjectAdapter(ListprojectActivity.this, projectList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(ListprojectActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
#Override
public void onItemClick(int position) {
Intent detailMasalah = new Intent(this, ListproblemActivity.class);
Project projectclick = projectList.get(position);
detailMasalah.putExtra(project_select, projectclick.getProject());
startActivity(detailMasalah);
}
}
and project.java
public class Project {
private int id_project;
private String project;
public Project (int id_project, String project) {
this.id_project = id_project;
this.project = project;
}
public int getId() {
return id_project;
}
public String getProject() {
return project;
}
}
Try this
#Override
public void onBindViewHolder(ProjectViewHolder holder, int position) {
Project project = projectList.get(position);
holder.textViewProject.setText(project.getProject());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = holder.getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
}
It happened because you are setting the listener in your ViewHolder class instead of your onBindViewHolder. As the viewholder is recycled, no new objects are created after some scrolling. The created object's click listener is bound to the item that first created it.
As Vishrut mentioned, you should move the listener to onBindViewHolder.

New fetch data is not show on recycler list when pull down to refresh

I want to implement one code where data will come on Scroll and if the data is add on list then we pull down(SwipeRefreshLayout) the new data will come on that list. In my below code the add on data is coming in response but not come in list? I have read many tutorials like this but data is coming on Swipe refresh but not shown on list. Thank you in advance
public class UpdatesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
SwipeRefreshLayout mSwipeRefreshLayout;
UserSessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
public String user_id;
TextView textView;
FloatingActionButton fab;
public int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_updates, container, false);
session = new UserSessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
// SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
getDataFromServer(1);
}
});
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
fab = (FloatingActionButton)v.findViewById(R.id.fab);
recyclerView = (RecyclerView) v.findViewById(R.id.updatesRecycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
textView = (TextView)v.findViewById(R.id.text);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), AddWebPostActivity.class);
startActivity(i);
}
});
getDataFromServer(a);
recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener((LinearLayoutManager) layoutManager) {
#Override
public void onLoadMore(int current_page) {
getDataFromServer(current_page);
}
});
}
public void getDataFromServer(int requestCount) {
Log.e("count",String.valueOf(requestCount));
final String DATA_URL = "https://XYZ.php?username="+user_id + "&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mSwipeRefreshLayout.setRefreshing(false);
Log.e("URL___________",DATA_URL);
Log.e("response___________", String.valueOf(response));
parseData(response);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.getCache().clear();
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setPost_title(json.getString(Config.TAG_POST_TITLE));
superHero.setPost_content(json.getString(Config.TAG_POST_CONTENT));
superHero.setPost_parent(json.getString(Config.TAG_POST_PARENT));
superHero.setPost_date(json.getString(Config.TAG_POST_DATE));
superHero.setPost_date_gmt(json.getString(Config.TAG_POST_DATE_GMT));
superHero.setScheduled_date(json.getString(Config.TAG_SCHEDULED_DATE));
superHero.setTo_ping(json.getString(Config.TAG_IP_ADDRESS));
superHero.setVisit_post(json.getString(Config.TAG_VISIT_POST));
superHero.setUr_id(json.getString(Config.TAG_UR_ID));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
}
/**
* Called when a swipe gesture triggers a refresh.
*/
#Override
public void onRefresh() {
getDataFromServer(1);
}
}
Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
UserSessionManager session;
public String user_id;
public String ur_id;
private Context context;
//String visit;
//List to store all superheroes
List<SuperHero> superHeroes;
//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
super();
//Getting all superheroes
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.web_post, parent, false);
// Session class instance
session = new UserSessionManager(context);
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
user_id = user.get(UserSessionManager.KEY_USER_ID);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
//Getting the particular item from the list
final SuperHero superHero = superHeroes.get(position);
holder.tvPostTitle.setText(superHero.getPost_title());
holder.tvPostContent.setText(superHero.getPost_content());
holder.tvPostDateTime1.setText(superHero.getPost_date() +" / " +superHero.getPost_date_gmt());
final String visit = superHero.getVisit_post();
holder.tvVisitPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,VisitWebView.class);
i.putExtra("visitURL",visit);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return superHeroes.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public TextView tvPostTitle,tvPostContent,tvPostDateTime1,tvVisitPost;
public ImageButton removeButton;
//Initializing Views
public ViewHolder(final View itemView) {
super(itemView);
tvPostTitle = (TextView) itemView.findViewById(R.id.tvPostTitle);
tvPostContent = (TextView) itemView.findViewById(R.id.tvPostContent);
tvPostDateTime1 = (TextView) itemView.findViewById(R.id.tvPostDateTime1);
tvVisitPost = (TextView) itemView.findViewById(R.id.tvVisitPost);
removeButton = (ImageButton) itemView.findViewById(R.id.removeButton);
}
}
}
use this method
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
getDataFromServer(1);
}
instead of this
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
getDataFromServer(1);
}
});
Please call adapter and pass fresh list data after this line
listSuperHeroes.add(superHero) in parseData(response) function ;
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter)
adapter.notifyDataSetChanged();

RecyclerView not showing data

I am new to android, developing an android application but I stuck here. RecyclerView shows empty. There are no errors or crashes in the log. I deleted and created new but same issue. I cant find what's wrong.
java code for main activity
public class HomeActivity extends AppCompatActivity {
private RecyclerView rcview1;
private RecyclerView.Adapter cmpadapter1;
private List<commdtylist> listitems2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
rcview1 = (RecyclerView) findViewById(R.id.commoditylist);
rcview1.setItemAnimator(new DefaultItemAnimator());
listitems2 = new ArrayList<>();
rcview1.setHasFixedSize(true);
viewcmp();
}
public void viewcmp() {
StringRequest stringRequest=new StringRequest(Request.Method.POST, otpur, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray jsonArray = jobj.getJSONArray("Details");
for (int i = 0; i < jsonArray.length(); i++) {
jobj = jsonArray.getJSONObject(i);
commdtylist item = new commdtylist(
jobj.getString("quantity_entitle"),
jobj.getString("comm_code"),
jobj.getString("item_description")
);
listitems2.add(item);
}
cmpadapter1 = new CommdityviewAdapter(listitems2, getApplicationContext());
rcview1.setAdapter(cmpadapter1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = new HashMap<>();
param.put("rc_no", crd);
return param;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
commdtylist
public class commdtylist {
private String quantity_entitle;
private String comm_code;
private String item_description;
public commdtylist(String quantity_entitle, String comm_code, String item_description) {
this.quantity_entitle = quantity_entitle;
this.comm_code = comm_code;
this.item_description = item_description;
}
public String getquantity_entitle() {
return quantity_entitle;
}
public String getcomm_code() {
return comm_code;
}
public String getitem_description() {
return item_description;
}
}
Adapter
public class CommdityviewAdapter extends RecyclerView.Adapter<CommdityviewAdapter.RViewHolder> {
private List<commdtylist> listitems2;
private Context context;
int lastPosition = -1;
public CommdityviewAdapter(List<commdtylist> listitems2, Context context) {
this.listitems2 = listitems2;
this.context = context;
}
public static Toast t = null;
#Override
public RViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.view_cmdstyle,parent,false);
return new RViewHolder(v);
}
#Override
public void onBindViewHolder(final RViewHolder holder,final int position) {
final commdtylist listitem=listitems2.get(position);
holder.quantity_entitle.setText(listitem.getquantity_entitle());
holder.comm_code.setText(listitem.getcomm_code());
holder.item_description.setText(listitem.getitem_description());
setAnimation(holder.itemView, position);
}
private void setAnimation(View itemView, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.up_from_bottom);
itemView.startAnimation(animation);
lastPosition = position;
}
else{
Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.down_from_top);
//android.R.anim.slide_in_left
itemView.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return listitems2.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class RViewHolder extends RecyclerView.ViewHolder{
public TextView quantity_entitle,comm_code,item_description;
public RViewHolder(View itemView) {
super(itemView);
quantity_entitle=(TextView)itemView.findViewById(R.id.quantity_entitle);
comm_code=(TextView)itemView.findViewById(R.id.comm_code);
item_description=(TextView)itemView.findViewById(R.id.item_description);
}
}
}
You have to add LayoutManager to RecyclerView . Use setLayoutManager (RecyclerView.LayoutManager layout) method to set LayoutManager to RecyclerView. If you don't set any LayoutManager you will not see any data.
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
Hope to help you.
Please set RecyclerView's layoutmanager with setLayoutManager method.
Set the layout manager to the recylerView
rcview1.setAdapter(cmpadapter1);
rcview1.setLayoutManager(new LinearLayoutManager(this));
make some change in home activity like
private CommdityviewAdapter cmpadapter1; // replace private RecyclerView.Adapter cmpadapter1;
rcview1.setLayoutManager(new LinearLayoutManager(this));
and when you set the adapter in recyclerview then after notifiy to adapter.
cmpadapter1.notifyDataSetChanged();

Categories

Resources