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;
}
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 am Trying to get response in recyclerview. I am getting response in log but when i adding it to recyclerView no data is displaying. I am unable to understand what i am missing. This irritate me so much, Please help
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
ArrayList<Model> arrayList;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
return new MyViewHolder(itemView);
}
public RecyclerViewAdapter(ArrayList<Model> arrayList) {
this.arrayList = arrayList;
System.out.println("size 111 "+arrayList.size());
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
Model model = arrayList.get(i);
myViewHolder.tvName.setText(model.getName());
myViewHolder.tvEmail.setText(model.getEmail());
myViewHolder.tvMobile.setText(model.getMobile());
}
#Override
public int getItemCount() {
System.out.println("size "+arrayList.size());
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvName, tvEmail, tvMobile;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmail = (TextView) itemView.findViewById(R.id.tvEmail);
tvMobile = (TextView) itemView.findViewById(R.id.tvMobile);
}
}
}
And this is my Activity Class
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
Model model;
ArrayList<Model> arrayList;
RecyclerView recyclerView;
RecyclerViewAdapter recyclerViewAdapter;
String url = "https://api.androidhive.info/volley/person_array.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<>();
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerViewAdapter = new RecyclerViewAdapter(arrayList);
recyclerView.setAdapter(recyclerViewAdapter);
getData();
}
protected void getData() {
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading......");
dialog.show();
JsonArrayRequest arrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
dialog.hide();
for (int i=0;i<response.length();i++){
try {
JSONObject object = (JSONObject) response.get(i);
String name = object.getString("name");
System.out.println("name "+name);
String email = object.getString("email");
JSONObject object1 = object.getJSONObject("phone");
String mobile = object1.getString("mobile");
System.out.println("mobile "+mobile);
model = new Model(name,email,mobile);
arrayList.add(model);
System.out.println("activity sizee"+arrayList.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
Tried everything, but nothing worked please help me out this problem. Where i am making mistake. Please help
You need to notify the changes using notifyDataSetChanged after for loop to tell the adapter to update the listview. The adapter observer will be notified internally that the data source has been changed and it need to go through it and do rebind the data with the layout
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
dialog.hide();
for (int i=0;i<response.length();i++){
try {
JSONObject object = (JSONObject) response.get(i);
String name = object.getString("name");
System.out.println("name "+name);
String email = object.getString("email");
JSONObject object1 = object.getJSONObject("phone");
String mobile = object1.getString("mobile");
System.out.println("mobile "+mobile);
model = new Model(name,email,mobile);
arrayList.add(model);
System.out.println("activity sizee"+arrayList.size());
} catch (JSONException e) {
e.printStackTrace();
}
recyclerViewAdapter.notifyDataSetChanged();
//^^^^^^^^^^^^^^^^^^^^^
}
I'm traying to get data from my mysql database and display them in a list view but the probleme is that the list view show only one attribut and for the others i have an error:RecyclerView: No adapter attached; skipping layout
this is my adapter :
public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder>{
private List<ListItem> ListData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback{
void onItemClick(int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback){
this.itemClickCallback = itemClickCallback;
}
public DerpAdapter(List<ListItem> listData, Context c){
this.inflater = LayoutInflater.from(c);
this.ListData = listData;
}
#Override
public DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row,parent,false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
ListItem item = ListData.get(position);
holder.title.setText(item.getTitle());
holder.subtitle.setText(item.getSubtitle());
holder.gaga.setText(item.getGaga());
}
#Override
public int getItemCount() {
return ListData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView subtitle;
private TextView gaga;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.lbl_item_text);
subtitle = (TextView) itemView.findViewById(R.id.lbl_item_sub_title);
gaga = (TextView) itemView.findViewById(R.id.gaga);
}
#Override
public void onClick(View view) {
/* if(view.getId() == R.id.cont_item_root){
}else{
}*/
}
}
this is my list item:
public class ListItem {
private String title;
private String subtitle;
private String gaga;
public String getGaga() {
return gaga;
}
public void setGaga(String gaga) {
this.gaga = gaga;
}
public ListItem(String title, String subtitle, String gaga) {
this.title = title;
this.subtitle = subtitle;
this.gaga = gaga;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getSubtitle() {
return subtitle;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
and finally this is my mainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
First, your initial setting of the adapter variable is commented out:
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
This will always set the adapter to null, you need to change it to this:
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
Also, I don't see a call to start the Volley RequestQueue, make sure you are calling requestQueue.start(); before adding the stringRequest.
Then verify that that code for setting the adapter is being executed. You may always be hitting the ErrorListener which never sets the adapter.
You are trying to set null reference adapter to the RecyclerView, firstly you initialize adapter then set into the RecyclerView.
#Bobbake4 this is the code:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
requestQueue.add(stringRequest);
}
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
I am trying to pass the string data which I get from web service and trying to show them in recyclerview. Here is the code which initializes the recyclerview's data.
private static final String URL_CROSSSERVICE = "http://xxx";
private static final String TOKEN = "xxx";
private static final String USER_NAME = "xx";
List<NewsData> newsDatas = new ArrayList<>();
Toolbar toolbar;
private RecyclerView rv;
public NavigationDrawerFragment drawerFragment;
String newsImageUrl, newsTitle,newsDesc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Haberler");
setSupportActionBar(toolbar);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
rv= (RecyclerView) findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
NewsAdapter adapter= new NewsAdapter(this, newsDatas);
rv.setAdapter(adapter);
initializeData();
}
.
.
.
private void initializeData() {
RequestQueue requestQueue;
VolleySingleton volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_CROSSSERVICE,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject sitePage = response;
try {
JSONArray newsPageContents= sitePage.getJSONArray("Contents");
for (int i = 0; i < newsPageContents.length(); i++) {
JSONObject newsContent = (JSONObject) newsPageContents.get(i);
newsTitle = newsContent.getString("Name");
newsDesc = newsContent.getString("Description");
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Token", TOKEN);
headers.put("Username", USER_NAME);
return headers;
}
};
requestQueue.add(request);
newsDatas.add(new NewsData(newsTitle, newsDesc, R.mipmap.ic_launcher));
newsDatas.add(new NewsData("Lavery Maiss", "25 years old", R.mipmap.ic_launcher));
newsDatas.add(new NewsData("Lillie Watts", "35 years old", R.mipmap.ic_launcher));
}
Last two lines are intentionally left hard coded, in order to see if adapter is working or not. Here is the adapter class.
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context context;
List<NewsData> datas;
public NewsAdapter(Context context,List<NewsData> datas){
this.datas=datas;
this.context=context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
NewsViewHolder newsViewHolder= new NewsViewHolder(v);
return newsViewHolder;
}
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
holder.newsName.setText(datas.get(position).Name);
holder.newsDesc.setText(datas.get(position).Description);
holder.newsImage.setImageResource(datas.get(position).photoURL);
}
#Override
public int getItemCount() {
return datas.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class NewsViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView newsName;
TextView newsDesc;
ImageView newsImage;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardview_news);
newsName = (TextView) itemView.findViewById(R.id.newsTitle);
newsDesc = (TextView) itemView.findViewById(R.id.newsDesc);
newsImage = (ImageView) itemView.findViewById(R.id.newsImage);
}
}
}
The problem is following. As you can see at the first code block, when I try to add string to NewsDatas array,it is not shown on recylerview, but hardcoded lines works fine. newsTitle and newsDesc are both string. Do you know why it happens? Thank you!
Using adapter.notifyDataSetChanged() after you added data to NewsData.
I found the solution. I added my datas in the for loop and after the addition I called rv.getAdapter().NotifyDatasetChanged(); like this:
public void onResponse(JSONObject response) {
JSONObject sitePage = response;
try {
JSONArray newsPageContents = sitePage.getJSONArray("Contents");
for (int i = 0; i < newsPageContents.length(); i++) {
JSONObject newsContent = (JSONObject) newsPageContents.get(i);
newsTitle = newsContent.getString("Name");
newsDesc = newsContent.getString("Description");
Utils.message(newsTitle);
Utils.message(newsDesc);
newsDatas.add(new NewsData(newsTitle, newsDesc, R.mipmap.ic_launcher));
rv.getAdapter().notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
}
Thanks #Tan Tran!