RecyclerView not showing data - java

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();

Related

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));

i want to make realtime changing data On RecyclerView

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

Data parsed correctly from server but Android recyclerview is empty

I made an online music player with PHP code server and I have no problem fetching data in JSON format. I have a problem with the Android side where no data is shown in my recyclerview although I initialized it correctly. Please help me to find out what's wrong.
Here's my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RequestQueue requestQueue;
Context context;
ListAdapter adapter;
LinearLayoutManager layoutManager;
List<Listening> list = new ArrayList<>();
String url = "https://www.learnhere.ir/listening.php";
AccessDataOnServer data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
requestQueue = Volley.newRequestQueue(context);
layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
adapter = new ListAdapter(list, context);
data = new AccessDataOnServer();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
data.getData(context, list, recyclerView, url, requestQueue);
}
}
ListAdapter:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {
List<Listening> listeningList;
Context context;
public ListAdapter(List<Listening> listeningList, Context context) {
this.listeningList = listeningList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Listening listening = listeningList.get(position);
holder.track.setText(listening.getTitle());
holder.term.setText(listening.getTerm());
Picasso.get().load(listening.getCover()).placeholder(R.mipmap.ic_launcher).into(holder.avatar);
}
#Override
public int getItemCount() {
return listeningList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
ImageView avatar;
TextView track, term;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.card_view);
avatar = itemView.findViewById(R.id.avatar);
track = itemView.findViewById(R.id.track_title);
term = itemView.findViewById(R.id.term);
}
}
}
Class to get my data by help of Volley Library:
public class AccessDataOnServer extends AppCompatActivity {
RequestQueue req;
Context context;
ListAdapter adapter;
List<Listening> list1 = new ArrayList<>();
String url = "https://learnhere.ir/listening.php";
public void getData(final Context con, final List<Listening> list1, final RecyclerView recyclerView, String url, RequestQueue req
) {
this.req = req;
req = Volley.newRequestQueue(con);
this.list1 = list1;
JsonObjectRequest job = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("music");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject job = jsonArray.getJSONObject(i);
String title = job.getString("title");
String cover = job.getString("cover");
String link = job.getString("track");
String term = job.getString("term");
Listening m = new Listening();
m.setTitle(title);
m.setTerm(term);
m.setCover(cover);
m.setTrackLink(link);
list1.add(m);
}
adapter = new ListAdapter(list1, con);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(con, "try error", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(con, "not response", Toast.LENGTH_SHORT).show();
}
});
req.add(job);
}
}
My data model:
public class Listening {
private String title;
private String term;
private String cover;
private String trackLink;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getTrackLink() {
return trackLink;
}
public void setTrackLink(String trackLink) {
this.trackLink = trackLink;
}
}
Your codes work correctly and there's no problem with them. Did you test it on emulator? Try to wipe data on emulator or test on physical device. Your problem should be solved.

Cannot cast onItem clicklistener inside Fragment Class form Adapter Class

I have an Fragment with recycleview where I populate it with json items from internet.
It load fine and Next step I want to is open new Activity when any row is clicked. It works in activity, thus I modified the same code for fragment but for fragment it throws exception in line
mExampleAdapter.setOnItemClickListener(getActivity());
with errror setOnItemClickListener of refrence adatper cannot be applied to Fragment activty and thus when I change line to
(ExampleAdapter.OnItemClickListener)
and when i build and run . Then app crashes with error that Mainactivity which holds framgnet cannot be cast in to .ExampleAdapter$OnItemClickListener
Here is my whole Fragment class
public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener{
public static final String YTD_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
String url="https://api.myjson.com/bins/16mecx";
public Mynotes() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_jsonfeed, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));
mExampleList = new ArrayList<>();
mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener((ExampleAdapter.OnItemClickListener) getActivity());
parseJSON();
return view;
}
private void parseJSON() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
mExampleList.add(new ExampleItem(videoTitle, link));
mExampleAdapter.notifyDataSetChanged();
}
} 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 intent = new Intent(getActivity(), NewActiviyt.class);
ExampleItem clickedItem = mExampleList.get(position);
intent.putExtra(YTD_LINK, clickedItem.getmLink());
startActivity(intent);
}
#Override
public void onRefresh() {
}
}
and my Adapter Class is
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 title = currentItem.getTitle();
// int likeCount = currentItem.getLikeCount();
// String imageUrl = currentItem.getImageUrl();
holder.mTextViewCreator.setText(title);
// holder.mTextViewLikes.setText("Likes: " + likeCount);
// Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTextViewCreator;
// public TextView mTextViewLikes;
// public ImageView mImageView;
public ExampleViewHolder(View itemView) {
super(itemView);
// mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
// mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_title);
}
#Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}
}
Thanks in advance.
replace getActivity with getContext when you work in fragment,
You can read more here
What is different between getContext and getActivity from Fragment in support library?
Your activity should implement ExampleAdapter.OnItemClickListener

JSONArray data won't show on Fragment

I'm having problems with showing JSONArray data on the Fragment. I am verified my links, Strings etc. But on the Debug console my request showing correct. I am suspecting JSONArray request but i can't find any errors.
Please, help!
D/Request::: 010-8470-0486
010-8472-0964
010-8474-2372
D/Request::: 010-8475-0089
D/Request::: 010-8475-7585
010-8478-0007
D/Request::: 010-8478-0573
010-8479-0311
010-8479-9234
D/Request::: 010-8481-2030
This is my Fragment
public class FragmentDB extends Fragment {
private View v;
private RecyclerView recyclerView;
private String url = "http://www.example.com/api.php";
private List<ModelDB> modelDBList;
public FragmentDB() {
}
#SuppressWarnings("UnnecessaryLocalVariable")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
return v;
} else {
Intent i10 = new Intent(getActivity(), PermissionActivity.class);
startActivity(i10);
Objects.requireNonNull(getActivity()).finish();
}
v = inflater.inflate(R.layout.frag_db, container, false);
recyclerView = v.findViewById(R.id.rv_db);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
modelDBList = new ArrayList<>();
DbRvAdapter adapter = new DbRvAdapter(getContext(), modelDBList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setHasFixedSize(true);
Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getDBLogs();
return v;
}
#SuppressWarnings({"LogNotTimber", "deprecation"})
private void getDBLogs() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with the response
try {
for ( int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
ModelDB dblist = new ModelDB();
dblist.setPhone_number(obj.getString("phone_number"));
dblist.setInfo1(obj.getString("info1"));
modelDBList.add(dblist);
Log.d("Request:: ", obj.getString("phone_number"));
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("Volley", error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(Objects.requireNonNull(getActivity()).getApplicationContext());
rq.add(jsonArrayRequest);
}
}
and ModelDB class
public class ModelDB {
public String phone_number;
public String info1;
public ModelDB() {
}
public ModelDB(String phone_number, String info1) {
this.phone_number = phone_number;
this.info1 = info1;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getInfo1() {
return info1;
}
public void setInfo1(String info1) {
this.info1 = info1;
}
}
and adapter class
public class DbRvAdapter extends RecyclerView.Adapter<DbRvAdapter.ViewHolder> {
public static final String KEY_DBPHONENUMBER = "phone_number";
public static final String KEY_DBINFO = "info1";
private Context context;
private List<ModelDB> list;
public DbRvAdapter(Context context, List<ModelDB> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_db, parent, false);
return new ViewHolder(v);
}
#SuppressWarnings("RecyclerView")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelDB modelDB = list.get(position);
holder.textDBP.setText(modelDB.getPhone_number());
holder.textInfo1.setText(String.valueOf(modelDB.getInfo1()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelDB modelDB1 = list.get(position);
Intent skipIntent = new Intent(v.getContext(), NumberActivity.class);
skipIntent.putExtra(KEY_DBINFO, modelDB1.getInfo1());
skipIntent.putExtra(KEY_DBPHONENUMBER, modelDB1.getPhone_number());
v.getContext().startActivity(skipIntent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textDBP, textInfo1;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
textDBP = itemView.findViewById(R.id.tv_number);
textInfo1 = itemView.findViewById(R.id.tv_dbinfo);
}
}
}
Sorry for my bad English.
notify you adapter after the for loop body and declare the adapter globally
for ( int i = 0; i < response.length(); i++) {
............
modelDBList.add(dblist);
}
if(dblist != null and dblist.size() > 0){
adapter.notifyDataSetChanged();
}
It looks like you didn't update list of modelDB's inside adapter after the parsing of a network call result.

Categories

Resources