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
Related
I have a problem. I download JSON from my PHP script:
[{
"Nazwa": "Rower",
"Cena": "300"
}, {
"Nazwa": "Rower mtb",
"Cena": "350"
}]
This script downloading JSON:
public class MainActivity extends AppCompatActivity
{
public List<Post> postList;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view)
{
EditText editText = findViewById(R.id.editText);
final String name = editText.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://shoppingcentreeshop.000webhostapp.com/androidAppScripts/szukajProduk tu.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.v(TAG, response);
Gson gson = new Gson();
Type type = new TypeToken<List<Post>>(){}.getType();
postList = gson.fromJson(response, type);
int size = postList.size();
Log.v(TAG, "SIZE = "+size);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, postList);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewAdapter);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<String, String> ();
params.put("name_product", name);
return params;
}
};
requestQueue.add(stringRequest);
}
}
I parse this using GSON to this class:
public class Post
{
#SerializedName("Nazwa")
#Expose
private String nazwa;
#SerializedName("Cena")
#Expose
private String cena;
//getters and setters
}
I adding postList to RecyclerViewAdapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
List<Post> listPost;
Context context;
public RecyclerViewAdapter(Context mContext, List<Post> list)
{
context = mContext;
listPost = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position)
{
final Post post = listPost.get(position);
holder.title.setText(post.getCena());
holder.price.setText(post.getCena());
}
#Override
public int getItemCount()
{
return listPost.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView title;
TextView price;
public ViewHolder(View itemView)
{
super(itemView);
title = itemView.findViewById(R.id.titleNazwa);
price = itemView.findViewById(R.id.price);
}
}
}
Why in my recyclerview I have only text from first index in postList.
I know, there is a lot of code, but I don't know where is problem in code.
I use JSON to get data from server to RecyclerView first time
so please bear with me
I restarted Android Studio, and this is working !
I don't know why !
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 series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//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){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
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've a recyclerview adapter with 3 textviews. I used a model class to set texts. Now I want to use the same adapter with different layout and in a different class which only have 1 textview. When I tried, I got NullPointerException (may be becuz the other 2 textviews are blank). Is there any way to use same adapter with different layout and in different class?
// second class - I used 1 textview
public class Customers extends AppCompatActivity{
private CShowProgress cShowProgress;
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cShowProgress = CShowProgress.getInstance();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showCustomers();
}
private void showCustomers() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(Customers.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
return linearLayoutManager;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
// first class - I used all 3 textviews
public class Walkin extends Fragment{
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String DASHBOARD = "My API";
#Nullable
#Override
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.walkin, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showDashboard();
}
private void showDashboard() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("walkinlist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
model.setTime(obj.getString("serviceDuration"));
model.setServname(obj.getString("service"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
return linearLayoutManager;
}
}
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> {
private List<TimeLineModel> mFeedList;
int resource;
private Context mContext;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) {
this.resource = resource;
this.mContext = mContext;
mFeedList = feedList;
}
#Override
public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(TimeLineViewHolder holder, int position) {
TimeLineModel timeLineModel = mFeedList.get(position);
holder.servicename.setText(timeLineModel.getServname());
holder.custname.setText(timeLineModel.getCustname());
holder.time.setText(timeLineModel.getTime());
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
// ViewHolder class
public class TimeLineViewHolder extends RecyclerView.ViewHolder {
public TextView servicename, custname, time;
public TimeLineViewHolder(View itemView, int viewType) {
super(itemView);
servicename = (TextView) itemView.findViewById(R.id.tv_service);
custname = (TextView) itemView.findViewById(R.id.tv_cust);
time = (TextView) itemView.findViewById(R.id.tv_time);
}
}
You can use the getItemViewType().
Make your adapter(here TimeLineAdapter) extend RecyclerView.Adapter only.
You can change the Adapter's constructer to recieve ItemType and use it in the getItemViewType
Override the int getItemViewType (int position) method in your adapter.
In the onCreateViewHolder you can differentiate between which layout you want to inflate by using the viewType parameter.
In onBindViewHolder use instanceof to check which ViewHolder was created and call the related bind functions
A Sample Code-
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter{
.....
int type;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) {
.....
.....
type=layoutType;
}
#Override
public int getItemViewType(int position) {
return type;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==1){
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}else{
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder2(view, viewType);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof TimeLineViewHolder){
TimeLineModel timeLineModel = mFeedList.get(position);
((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname());
......
}
else if(holder instanceof TimeLineViewHolder2){
....
....
}
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}