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!
Related
I have a problem, when i swipe to refresh the data, the first swipe is ok but after that every swipe reload and add the same data over and over again, by the end i have a list with same items over and over... I'm using a loader. I tried to clear before but i don't understand what's wrong with my code, if someone could explain it to me. Thank You.
Here my code :
public static final String EXTRA_URL = "imageUrl";
public static final String EXTRA_APKNAME = "apkname";
public static final String EXTRA_APKSIZE = "apksize";
public static final String EXTRA_APKFILE = "apkfile";
private RecyclerView mRecyclerView;
private MyAdapter mExampleAdapter;
private ArrayList<one_item> mExampleList;
private RequestQueue mRequestQueue;
private SwipeRefreshLayout swipeRefreshLayout;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
mExampleAdapter = new MyAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, activity_detail.class);
one_item clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getmImageUrl());
detailIntent.putExtra(EXTRA_APKNAME, clickedItem.getMapkname());
detailIntent.putExtra(EXTRA_APKSIZE, clickedItem.getMapksize());
detailIntent.putExtra(EXTRA_APKFILE, clickedItem.getMapkfile());
startActivity(detailIntent);
}}
My adapter:
private ArrayList<one_item> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.one_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
one_item currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String apkname = currentItem.getMapkname();
String apksize = currentItem.getMapksize();
String apkfile = currentItem.getMapkfile();
holder.mTextViewname.setText(apkname);
holder.mTextViewsize.setText(apksize);
holder.mTextViewfile.setText(apkfile);
Picasso.get().load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextViewname, mTextViewsize, mTextViewfile;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image);
mTextViewname = itemView.findViewById(R.id.name);
mTextViewsize = itemView.findViewById(R.id.size);
mTextViewfile = itemView.findViewById(R.id.file);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});}}}
my activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recommended Apps"
android:textColor="#000"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginBottom="10dp"
/>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/refreshlayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:padding="5dp" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Just use mExampleList.clear() at the first line of your parseJSON() function
and then you'll be able to add the "updated" items.
In addition I'd suggest that you move swipeRefreshLayout.setRefreshing(false) to the end of Volley onResponse and onError() implementation -
Right now you're telling the swipeRefreshLayout to stop refreshing before the request(that happens asynchronously) has finished
You are initializing your adapter every time you do a swipe.
Change this constructor of MyAdapter code.
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
to,
public MyAdapter(Context context) {
mContext = context;
}
public setExampleList(ArrayList<one_item> exampleList){
mExampleList = exampleList;
}
Now change your onCreate function to.
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
//Changed Code
mExampleAdapter = new MyAdapter(MainActivity.this);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
//Changed Code
mExampleAdapter.setExampleList(mExampleList);
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
I have added a comment of the code block where I have made the changes.
Feel free to comment in case you have any queries.
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 want that when anyone click on the CardView with Status=undone there should run an API and the database is updated and the refreshed data is loaded in RecyclerView.
This is my UpdateStatus.class having the RecyclerView data:
TextView Cid,Tno,Tname,Cono,Work;
private static final String
URL_GETDATA="";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_status);
Bundle bundle = getIntent().getExtras();
String cid = bundle.getString("checkID");
String tno = bundle.getString("trainno");
String tname = bundle.getString("trainname");
String cno = bundle.getString("coachno");
String works = bundle.getString("work");
Cid=(TextView)findViewById(R.id.idValue);
Cid.setText(cid);
Tno=(TextView)findViewById(R.id.tnoValue);
Tno.setText(tno);
Tname=(TextView)findViewById(R.id.tnameValue);
Tname.setText(tname);
Cono=(TextView)findViewById(R.id.cnoValue);
Cono.setText(cno);
Work=(TextView)findViewById(R.id.workValue);
Work.setText(works);
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final AlertDialog dialog=new SpotsDialog(this, "Loading Data ...");
dialog.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_GETDATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
Log.v("Response",response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
ListItem item;
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.getString("status").equals("done")){
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.done
);
}else {
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.update
);
}
listItems.add(item);
}
adapter=new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
Bundle bundle = getIntent().getExtras();
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("checkID",bundle.getString("checkID"));
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my Adapter.class where the CardView data is loaded onClick on Card the Status is checked and An API will run using Volley and UpdateStatus activity must be refreshed with new data:
private List<ListItem> listItems;
private Context context;
private static final String
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final ListItem listItem=listItems.get(position);
holder.planned.setText(listItem.getPlanned());
holder.actual.setText(listItem.getActual());
holder.status.setImageResource(listItem.getmImageResourceid());
Intent i=new Intent(context,UpdateStatus.class);
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listItem.getStatus().equals("undone")){
//update code here
}
Toast.makeText(context,"You Clicked "+listItem.getStatus(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView planned,actual;
public ImageView status;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
planned=(TextView)itemView.findViewById(R.id.planned_date);
actual=(TextView)itemView.findViewById(R.id.actual_date);
status=(ImageView)itemView.findViewById(R.id.status);
linearLayout=(LinearLayout)itemView.findViewById(R.id.linearLayout);
}
}
In OnResponse from volley when you adding a new data to your recyclerView just called a method recyclerView.notifyDataSetChanged() after recyclerView.setAdapter(adapter)
see the changes in you code below-:
#Override
public void onResponse(String response) {
dialog.dismiss();
Log.v("Response",response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
ListItem item;
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.getString("status").equals("done")){
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.done
);
}else {
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.update
);
}
listItems.add(item);
}
adapter=new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.notifyDataSetChanged()
} catch (JSONException e) {
e.printStackTrace();
}
}
},
Or for better user experience you can use recyclerView.notifyItemInserted(int position) instead of recyclerView.notifyDataSetChanged(). see documentation
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 3 years ago.
My recyclerView turns out to be blank when i try to load data from JSON.
In logcat, it says, "No adapter attached; skipping layout"
This is my activity
public class MainActivity extends AppCompatActivity {
private RecyclerView news;
private RecyclerView.Adapter news_adapter;
private List<News_Item> listItems;
private static final String news_data = "Url to Json file";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
news = (RecyclerView) findViewById(R.id.news);
news.setHasFixedSize(true);
news.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading News...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
news_data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("articles");
for(int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
News_Item item = new News_Item(
o.getString("title"),
o.getString("description"),
o.getString("author"),
o.getString("urlToImage"),
o.getString("URL")
);
listItems.add(item);
}
news_adapter = new News_Adapter(listItems,getApplicationContext());
news.setAdapter(news_adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
But it works fine when i load dummy data in it as follow
listItems = new ArrayList<>();
for(int i= 0; i<=10 ; i++){
News_Item news_item = new News_Item(
"Heading" + (i+1),
"Lorem Ipsum",
"Lorem Ipusm",
"Lorem Ipsum",
"Lorem Ipsum"
);
listItems.add(news_item);
}
news_adapter = new News_Adapter(listItems,this);
news.setAdapter(news_adapter);
I tried to read some other questions on here on stackoverflow, but most of them did't helped question 1,
question 2,
question 3
Here is my News_adapter
public class News_Adapter extends RecyclerView.Adapter<News_Adapter.ViewHolder> {
private List<News_Item> listItems;
private Context context;
public News_Adapter(List<News_Item> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final News_Item item = listItems.get(position);
holder.news_title.setText(item.getTitle());
holder.news_desc.setText(item.getSubtitle());
holder.news_author.setText(item.getAuthor());
Picasso.with(context)
.load(item.getImg_url())
.into(holder.news_img);
holder.card_body.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "item clicked "+item.getTitle() , Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView news_title,news_desc,news_author;
public ImageView news_img;
public RelativeLayout card_body;
public ViewHolder(View itemView) {
super(itemView);
news_author = (TextView) itemView.findViewById(R.id.news_author);
news_desc = (TextView) itemView.findViewById(R.id.news_desc);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_img = (ImageView) itemView.findViewById(R.id.news_img);
card_body = (RelativeLayout) itemView.findViewById(R.id.card_body);
}
}
}
Put the lines -
news_adapter = new News_Adapter(listItems,getApplicationContext());
news.setAdapter(news_adapter);
in your onCreate() method just before your loadRecyclerViewData() call
So onCreate() is like -
listItems = new ArrayList<>();
news_adapter = new News_Adapter(listItems,getApplicationContext());
news.setAdapter(news_adapter);
loadRecyclerViewData();
Then in your onResponse() method do news_adapter.notifyDataSetChanged(); instead of the above 2 lines.
UPDATE 1
Replace your line o.getString("URL") with o.getString("url"). Also instead of using getString always use optString so that if some info is not coming from JSON, your code doesn't break.
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);
}