I am making an android app to fetch JSON data from URL and then showing it in a RecyclerView.
My JSON data
[{"email":"abc#gmail.com","photo":"http:\/\/www.example.com\/x.jpg","bookname":"one","price":"30","num":"3","avg":"3.9","author":"none"}]
but only bookname and photo keys values are fetching. Other parameters are empty but my code is correct because if it is wrong than even bookname shouldn't fetch.
My code is:
public class dashBoard extends AppCompatActivity {
private List<myDash> dash;
private Toolbar mToolbar;
Button read;
//Creating Views
int temp=0;
float starts=0;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public String ratenumS,numberS;
public String bookName,price,rating;
private RequestQueue requestQueue;
String mail_one;
private int requestCount = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_bord);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
dash = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
getDash();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
getDash();
}
});
//initializing our adapter
adapter = new dashCard(dash, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private JsonArrayRequest getDataFromDash(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar3);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);
SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(dashBoard.this);
mail_one = pre.getString("mail2", "DEFAULT VALUE");
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("http://www.example.com/getDash.php?page="+ String.valueOf(requestCount )+"&email="+mail_one,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
if(temp==0) {
Toast.makeText(dashBoard.this, "No More Items Available "+bookName+"book "+price+" "+ratenumS+" "+numberS+" "+mail_one, Toast.LENGTH_SHORT).show();
temp++;
}
}
}
//Returning the request
return jsonArrayRequest;
}
private void getDash() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromDash(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
myDash dash1 = new myDash();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
dash1.setImageUrl(json.getString("photo"));
dash1.setBook_name(json.getString("bookname"));
dash1.setNo_down(json.getString("download"));
dash1.setBook_price(json.getString("price"));
dash1.setStar_num(json.getString("num"));
dash1.setAvg_rate(Float.parseFloat(json.getString("avg")));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
dash.add(dash1);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
Does anybody have any idea why this code is not working?
My dashCard Activity.
public class dashCard extends RecyclerView.Adapter<dashCard.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<myDash> secDash1;
//Constructor of this class
public dashCard(List<myDash> secDash1, Context context){
super();
//Getting all superheroes
this.secDash1 = secDash1;
this.context = context;
}
//In
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dash_bord, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final myDash secDash = secDash1.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(secDash.getImageUrl(),ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(secDash.getImageUrl(), imageLoader);
holder.bookName.setText(secDash.getBook_name());
holder.price.setText(secDash.getBook_price());
holder.numberD.setText(secDash.getStar_num());
//holder.rate.setText(Float.toString(secDash.getAvg_rate()));
holder.download.setText(secDash.getNo_down());
// holder.star.setRating(secDash.getAvg_rate());
}
public int getItemCount() {
return secDash1.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
//Views
public NetworkImageView imageView;
public TextView bookName;
public TextView price;
public TextView numberD;
public TextView rate;
RatingBar star;
public TextView download;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.dashImage);
bookName = (TextView) itemView.findViewById(R.id.bookName4);
price = (TextView) itemView.findViewById(R.id.priceDash);
numberD = (TextView) itemView.findViewById(R.id.numberDash);
rate = (TextView) itemView.findViewById(R.id.ratenumDash);
star = (RatingBar) itemView.findViewById(R.id.rateDash);
download = (TextView) itemView.findViewById(R.id.download);
}
}
}
I think problem at:
dash1.setNo_down(json.getString("download"));
Your json has not download key for get value. When code run over this line, an exception has occurred and program go to catch block, other properties will never be assigned data.
I recommend that check json key are exist before get its value.
You dont have "download" as key in json because of that an exception is thrown which causes other keys to not assigned
Related
when I send new data or update the info, how can to change my recycle view?
I have used a dapter.notifyDataSetChanged(); , but it's not working...
I tried more method, but it all cannot change my recycler view
in my code
recyclerView = view.findViewById(R.id.recyclerCoin);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
listCoinDiamondModel = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getActivity());
getData();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
private void sendGift(String postUserID) {
final String postUserIDD = postUserID;
final String GiftAmount = this.GiftAmount.getText().toString().trim();
final String flag = "1";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_GIFTCOIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Log.d("FID", fid);
params.put("fid", fid);
params.put("GiftAmount", GiftAmount);
params.put("flag", flag);
params.put("postUserID", postUserIDD);
params.put("uid", getID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Load...");
progressDialog.dismiss();
final String GROUP_LIST = "https://example.com/aaa.php?flag=1&fid="+ getActivity().getIntent().getStringExtra("fid") +"&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GROUP_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "No More gift Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
final CoinDiamondModel coinDiamondModel = new CoinDiamondModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_Coin = "Coin";
String TAG_Diamond = "Diamond";
String TAG_UserName = "UserName";
String TAG_UserPhoto = "UserPhoto";
String TAG_UserID = "UserID";
//Log.d("NAME111", json.getString(json.getString(TAG_UserName)));
coinDiamondModel.setCoin(json.getString(TAG_Coin));
coinDiamondModel.setDiamond(json.getString(TAG_Diamond));
coinDiamondModel.setGiftFromUserName(json.getString(TAG_UserName));
coinDiamondModel.setGiftFromUserPhoto(json.getString(TAG_UserPhoto));
coinDiamondModel.setGiftFromUserID(json.getString(TAG_UserID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
listCoinDiamondModel.add(coinDiamondModel);
//adapter.addTheCoinData(coinDiamondModel);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
who knows what's happen and how can solve this?
could you told me how can I do, please?
adapter all code
public class CoinAdapter extends RecyclerView.Adapter<CoinAdapter.ViewHolder> {
private ImageLoader imageLoader;
private List<CoinDiamondModel> newcoinDiamondLists;
private RequestManager glide;
private Context context;
SessionManager sessionManager;
private String getID,memail;
public CoinAdapter(List<CoinDiamondModel> newcoinDiamondLists, Context context) {
this.newcoinDiamondLists = newcoinDiamondLists;
this.glide = Glide.with(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.coinlist, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
sessionManager = new SessionManager(getApplicationContext());
sessionManager.checkLogin();
HashMap<String, String> user = sessionManager.getUserDetail();
getID = user.get(sessionManager.USERID);
memail = user.get(sessionManager.EMAIL);
//String gid = getIntent.getStringExtra("xxx");
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
CoinDiamondModel newCoinDiamondModel = newcoinDiamondLists.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
holder.userName.setText(newCoinDiamondModel.getGiftFromUserName());
holder.userID.setText(newCoinDiamondModel.getGiftFromUserID());
holder.coinCount.setText(" x "+newCoinDiamondModel.getCoin());
glide.load(newCoinDiamondModel.getGiftFromUserPhoto()).into(holder.userPhoto);
}
#Override
public int getItemCount() {
return newcoinDiamondLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView userPhoto;
TextView userName,userID,coinCount;
ImageView coinImg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPhoto = (CircleImageView) itemView.findViewById(R.id.userPhoto);
userName = (TextView) itemView.findViewById(R.id.userName);
coinCount = (TextView) itemView.findViewById(R.id.coinCount);
userID = (TextView) itemView.findViewById(R.id.userID);
coinImg = (ImageView) itemView.findViewById(R.id.coinImg);
}
}
public void addTheCoinData(CoinDiamondModel coinDiamondModel){
if(coinDiamondModel!=null){
newcoinDiamondLists.add(coinDiamondModel);
notifyDataSetChanged();
}else {
throw new IllegalArgumentException("無資料!");
}
}
}
you can again set the adapter to recycler view after the response of the server
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
}
solution 2:
in your adapter write a function to update you list
and call function in activity
add this function to the adapter
public void updateList(List<CoinDiamondModel> list){
newcoinDiamondLists = list;
notifyDataSetChanged();
}
and call a function updateList of when you need an update recyclerview
The RecyclerView initialization and notifyDataSetChanged() is used properly. As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.
In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:
#Override
public int getItemCount() {
return listdata.length;
}
In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.coin_xml_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
In RecyclerView.Adapter check if RecyclerView.ViewHolder class is properly extended
and linked the UI elements from the xml with the adapter like below:
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView coinTextView;
public ViewHolder(View itemView) {
super(itemView);
this.coinTextView = (TextView) itemView.findViewById(R.id.coinTextView);
}
}
In RecyclerView.Adapter check if onBindViewHolder method is properly overridden and updated the list component UI properly like below:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.cointTextView.setText(listdata[position].getCoin());
}
Debug with a breakpoint and check if the listCoinDiamondModel.add(coinDiamondModel) is calling or not and coinDiamondModel object is not empty.
The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. As an example:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
you can update your adapter list manually like this:(write this function in your adapter)
public void updateCoinAdapterList(ArrayList<listCoinDiamondModel> recyclerItemsList) {
this.recyclerItemsList = recyclerItemsList;
this.notifyDataSetChanged();
}
you must set your adapter global variable and initialize it in OnCreate or OnResume, and call
adapter.updateCoinAdapterList(listCoinDiamondModel);
when your list changed
I want to implement one code where data will come from server and show on RecyclerView item, below is my mainActivity class where I am fetching the data from server but this code is not running just because of NullPointerException.
I am using Volley to fetch the data
public class MainActivity_Plan extends AppCompatActivity {
private List<Plan> planList = new ArrayList<>();
private RecyclerView recyclerView;
private PlanAdapter pAdapter;
private RequestQueue requestQueue;
String url;
// Session Manager Class
SessionManager session;
String matri_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plan_activity);
session = new SessionManager(this);
HashMap<String, String> user = session.getUserDetails();
matri_id = user.get(SessionManager.KEY_EMAIL);
Log.e("matri_id+++++++++++++",matri_id);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pAdapter = new PlanAdapter(planList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(pAdapter);
getInfo();
Log.e("url____________",url);
}
private void getInfo() {
url = ConfigPlan.DATA_URL+matri_id;
JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
Log.e("response---------",response.toString());
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(MainActivity_Plan.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
}
This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
Plan p = new Plan();
JSONObject json = null;
try {
json = array.getJSONObject(i);
//Adding data to the superhero object
p.setName(json.getString(ConfigPlan.KEY_PLAN_NAME));
p.setAmount(json.getString(ConfigPlan.KEY_PLAN_AMOUNT));
p.setDuration(json.getString(ConfigPlan.KEY_PLAN_DURATION));
p.setContacts(json.getString(ConfigPlan.KEY_PLAN_CONTACTS));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
planList.add(p);
}
}
}
Below is Adapter Class
public class PlanAdapter extends RecyclerView.Adapter<PlanAdapter.MyViewHolder> {
private List<Plan> planList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView plan_name, plan_duration, plan_contact, plan_amount;
public Button subscribeButton;
public MyViewHolder(View view) {
super(view);
plan_name = (TextView) view.findViewById(R.id.planName);
plan_duration = (TextView)view.findViewById(R.id.planDuration);
plan_contact = (TextView) view.findViewById(R.id.planContacts);
plan_amount = (TextView) view.findViewById(R.id.planAmount);
subscribeButton = (Button) view.findViewById(R.id.subscribeButton);
}
}
public PlanAdapter(List<Plan> planList) {
this.planList = planList;
}
#Override
public PlanAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plan_activity_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(PlanAdapter.MyViewHolder holder, int position) {
Plan plan = planList.get(position);
holder.plan_name.setText(plan.getName());
holder.plan_amount.setText(plan.getAmount());
holder.plan_contact.setText(plan.getContacts());
holder.plan_duration.setText(plan.getDuration());
}
#Override
public int getItemCount() {
return 0;
}
}
I think you might not have initialized requestQueue object of a class RequestQueue (as per your shared error image).
Please update adapter on list, after you done with parsing of code. You have to put "Adapter" Code in "OnResponse()" method. After parsing code.
not have initialized requestQueue object of a class RequestQueue
you forgot to pAdapter.notifyDataSetChanged(); after adding data in your planList Arraylist
change this in your adapter class
Change in getItemCount() method
#Override
public int getItemCount() {
return planList.size;
}
I have a recyclerview that gets the first 10 items, when I scroll it down sometimes it gets the others, sometimes not:
item 22
item 21
item 20
item 19
item 18
item 17
item 16
item 15
item 14
item 13
usually it stops at item 13. (not getting the onscroll items)
but sometimes it works and get the others (12,11,10,9,8,7,6,5,4,3,2,1...)
my scroll code:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (isLastItemDisplaying(recyclerView)) {
getData();
}
}
});
get data:
private void getData() {
requestQueue.add(getDataFromServer(requestCount, user_id));
}
getdata server
private JsonArrayRequest getDataFromServer(String requestCount, String user_id) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
requestCount = requestCount + "&user=" + user_id;
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(UserAreaActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
check last item
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
any ideas why it works sometimes and why not?
----------------------------> edit
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
//Imageloader to load image
private ImageLoader imageLoader;
private final Context context;
//List to store all posts
List<Posts> Posts;
//Constructor of this class
public CardAdapter(List<Posts> Post, Context context){
super();
//Getting all
this.Posts = Post;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.posts_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Posts post = Posts.get(position);
holder.post = post;
//Loading image from url
//imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
//Showing data on the views
//holder.imageView.setImageUrl(post.getImageUrl(), imageLoader);
Picasso.with(context).load(post.getImageUrl()).into(holder.imageView);
holder.textViewName.setText(post.getName());
holder.textViewPublisher.setText(post.getPublisher());
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return Posts.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//Views
public ImageView imageView;
public TextView textViewName;
public TextView textViewPublisher;
public Posts post;
public ImageView ProfilePic;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
}
#Override
public void onClick(View v) {
//...
}
}
}
}
----------------------------------------- edit 2
private JsonArrayRequest getDataFromServer(String requestCount, String user_id) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
requestCount = requestCount + "&user=" + user_id;
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(UserAreaActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount, user_id));
//Incrementing the request counter
//requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the object
Posts PostObj = new Posts();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the object
PostObj.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
PostObj.setName(json.getString(Config.TAG_NAME));
PostObj.setPublisher(json.getString(Config.TAG_PUBLISHER));
requestCount = PostObj.setId(json.getString(Config.TAG_ID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding object to the list
listPosts.add(PostObj);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
Have you try with ? :
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
// instead of findLastCompletelyVisibleItemPosition
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
How to use shared preferences in RecyclerView.Adapter..? i have used shared preference value in RecyclerView.Adapter..but nothing is saving in shared preference..where exactly i have to use shared preference ..?in RecyclerView.Adapter or activity..?
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String gd;
public static final String SHARED_PREF_NAME = "myloginapp";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String GROUPSNAME_SHARED_PREF = "groupname";
public CardAdapter(Context context) {
this.context = context;
}
//List of superHeroes
List<Group> groups;
public CardAdapter(List < Group > groups, Context context) {
super();
//Getting all the superheroes
this.groups = groups;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.groups_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder (ViewHolder holder,int position){
Group group1 = groups.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(group1.getPic(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(group1.getPic(), imageLoader);
holder.groupname.setText(group1.getGname());//i want to store this value in shared preference..
holder.groupinfo.setText(group1.getGinfo());
gd = holder.groupname.getText().toString();//variable gd is storing any value.
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount () {
return groups.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView groupname;
public TextView groupinfo;
public Button add;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
groupname = (TextView) itemView.findViewById(R.id.textViewName);
groupinfo = (TextView) itemView.findViewById(R.id.textViewRank);
add = (Button) itemView.findViewById(R.id.button7);
//String gd = holder.groupname.getText().toString();
SharedPreferences sharedPreferences1 = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences1.edit();
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
}
}
}
Viewgroup.java
public class Viewgroup extends AppCompatActivity {
//Creating a List of superheroes
private List<Group> listSuperHeroes;
private String vault;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
//Calling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Group group1 = new Group();
JSONObject json = null;
try {
json = array.getJSONObject(i);
group1.setPic(json.getString(Config.TAG_IMAGE_URL));
group1.setGname(json.getString(Config.TAG_NAME));
group1.setGinfo(json.getString(Config.TAG_INFO));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(group1);
}
//Finally initializing our adapter
adapter = new CardAdapter(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
/* recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final Button add = (Button) v.findViewById(R.id.button7);
final TextView txtStatusChange = (TextView) v.findViewById(R.id.textViewName);
//final TextView txtStatusChange1 = (TextView) v.findViewById(R.id.textView33);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Viewgroup.this, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// Log.e(TAG_IMAGE_URL, "hello text " + txtStatusChange.getText().toString() + " TAG " + txtStatusChange.getTag().toString());
Toast.makeText(Viewgroup.this, txtStatusChange.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
return false;
}
});*/
}
}
You should add editor.commit() or editor.apply() in order to save your data to Sharedpreferences . Add this below your code
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
editor.apply();
why the shared preference is not updating..?
Use onClick method of Button before starting Activity to save value in Sharedpreferences like:
...
gd = holder.groupname.getText().toString();
holder.add.setTag(gd);
...
#Override
public void onClick(View view) {
String strValue=view.getTag().toString();
... save strValue in Sharedpreferences
...
editor.putString(GROUPSNAME_SHARED_PREF, strValue);
editor.apply();
// start new Activity..
}
...
This is what I did. (If you cant access class "context" inside SharedPreferences)
Create a context of the adapter class by Context mConext; or private WeakReference<Context> mContext;
Instead giving mContext use this.mContext.get() wherever you need to use context inside the SharedPrefernce. like
SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);
I tried so many other solutions, but couldn't find the thing.
it works just add this.mcontext.getContext instead of this.mContext.get().
just use itemView.getContext() if you using this in side onCreateViewHolder view holder
GET DATA
just use itemView.getContext() before use getSharedPreferences
save is allso the same
Sharedpreferences prefs =
holder.itemView.getContext().getSharedPreferences("SHARED_PREFS", holder.itemView.getContext().MODE_PRIVATE);
String Variable= holder.prefs.getString("yourkey", null);
I am trying to create an app that parses data from a JSON parser and populates the recyclerview items with the data fetch from the JSON but whenever I run it it just freezes at loading and shows no error except adapter not attached skipping layout. I am stuck at a dead end as I am not able to get any further. How can I fix this what is the problem with the code .
MainActivity
public class MainActivity extends AppCompatActivity {
CollapsingToolbarLayout collapsingToolbarLayout;
ImageView image;
TextView personName;
TextView personProf;
RecyclerView rv;
private List<Person> personList;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
ImageView images;
RecyclerViewHeader header;
ImageView iv;
public String strurl;
URL url;
URI uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
personName= (TextView)findViewById(R.id.textView);
personProf=(TextView)findViewById(R.id.textView2);
images= (ImageView)findViewById(R.id.imageView);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("Capsule");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
//setPalette();
strurl = "http://www.humanfox.com/capsule/assets/img/jawed_headshot.jpg";
Typeface face2 = Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
Typeface face4= Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Bold.ttf");
image = (ImageView) findViewById(R.id.image);
Picasso.with(this)
.load("http://d152j5tfobgaot.cloudfront.net/wp-content/uploads/2013/06/Javed-Habib_11.jpg")
.into(image);
//header = (RecyclerViewHeader) findViewById(R.id.header);
//header.attachTo(rv,true);
rv =(RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
personList= new ArrayList<>();
getData();
}
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(COnfig.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
Person per = new Person();
JSONObject json = null;
try {
json = array.getJSONObject(i);
per.setImageUrl(json.getString(COnfig.TAG_IMAGE_URL));
per.setName(json.getString(COnfig.TAG_NAME));
per.setPassion(json.getString(COnfig.TAG_PROFESSION));
} catch (JSONException e) {
e.printStackTrace();
}
personList.add(per);
}
adapter = new RVAdapter(personList, this);
rv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
}
Recycler view Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private ImageLoader imageLoader;
Context context;
private List<Person> persons;
RVAdapter(List<Person> persons,Context context){
this.persons = persons;
this.context = context;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(persons.get(i).getImageUrl(), ImageLoader.getImageListener(personViewHolder.personPhoto, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));
personViewHolder.personName.setText(persons.get(i).getName());
personViewHolder.personProf.setText(persons.get(i).getPassion());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return persons.size();
}
public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
CardView cv;
TextView personName;
TextView personProf;
ImageView personPhoto;
Context context;
PersonViewHolder(final View itemView) {
super(itemView);
context = itemView.getContext();
itemView.setClickable(true);
itemView.setOnClickListener(this);
cv = (CardView) itemView.findViewById(R.id.cv);
personName = (TextView) itemView.findViewById(R.id.textView);
personProf = (TextView) itemView.findViewById(R.id.textView2);
personPhoto=(ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
final Intent intent;
int position =getAdapterPosition();
switch(position){
case 0:
context.startActivity(new Intent(context,caps1.class));
}
}
}
}
Custom Volley Request
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Make sure you have implemented send request and parse json on background thread not in Main thread. Otherwise, it will freeze because of your main thread can do one task and should do UI update not all tasks together.