android


how to auto update RecyclerView.Adapter in android?


This is My Code:
public class ItemsListActivity extends AppCompatActivity {
private List<AllItems> listItems;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items_list);
Button camera=(Button)findViewById(R.id.camera);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ItemsListActivity.this, Camera.class);
startActivity(i);
}
});
getData();
}
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems();
JSONObject json = null;
try {
json = array.getJSONObject(i);
items.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
items.setName(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
listItems.add(items);
}
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
adapter.notifyItemRangeChanged(0, listItems.size());
}
}
And This Is CardAdapter:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<AllItems> superHeroes;
public CardAdapter(List<AllItems> superHeroes, Context context){
super();
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_items_lists, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AllItems superHero = superHeroes.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
holder.textViewName.setText(superHero.getName());
}
#Override
public int getItemCount() {
return superHeroes.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
}
}
}
how do I update adapter data in order to display newly received items?
You are creating instance of adapter every time you parsing the data,
just create its instance once in onCreate() method like below:
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
and just notify the adapter with your parse data like below:
listItems.add(items);
adapter.notifyDataSetChanged();
will work for you.
Here what is happening that evertime your are calling getData() you are initializing adapter again . Instead you should initialize your adapter in onCreate and in getData just update the list that you are passing in adapter and call adapter.notifyDataSetChanged().
private List<AllItems> listItems;
private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_items_list); Button camera=(Button)findViewById(R.id.camera); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
camera.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { Intent i = new Intent(ItemsListActivity.this, Camera.class); startActivity(i); } }); getData(); }
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { loading.dismiss(); parseData(response); }
}, new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) { } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); }
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems(); JSONObject json = null;
try
{
json = array.getJSONObject(i); items.setImageUrl(json.getString(Config.TAG_IMAGE_URL)); items.setName(json.getString(Config.TAG_NAME)); } catch (JSONException e) { e.printStackTrace(); } listItems.add(items); }
}
adapter.notifyDataSetChanged().
}
And if you don't want to show previous items call lisItems.clear() before adding new items

Related Links

Android : Class not found when View contains R.syleable
Change Navigation Drawer background color for the selected item
Android: How to get the Checked items of checkbox in RecyclerView to send it to server
Cannot see toolbar in lollipop and higher
How to put the title of the Activity on the right of the toolbar
Android React Native Height 0 on Animated.View
Per app proxy/'port forwarding'(iOS or Android)
Nesting classes with Typescript
Call SOAP service from android with ksoap2
Xamarin: Error executing task ConvertResourcesCases: Path is invalid
tile provider and API 23 permissions
Android BLE CALLBACK_TYPE_ALL_MATCHES Not Working
Fill the CheckBox drawable image to CheckBox width in ListView adapter
Displaying images from Google Drive on an Android app
GcmNetworkManager maximum number of scheduled tasks
Android client server using Games API

Categories

HOME
ng-idle
ggplot2
telegram
toolbox
fftw
composite-primary-key
rendering
aws-cli
simulink
vert.x
odoo-8
extjs4.2
minecraft-forge
gson
bitnami
event-sourcing
null-pointer
feathersjs
foreign-keys
roundup
onload
maze
bulletphysics
mat
entity-relationship-model
spotipy
tpm
google-earth
ntp
autodesk-designautomation
xbox
left-join
cart
github3.py
vue-chartjs
reactjs.net
carriage-return
engine.io
latitude-longitude
parse-tree
diacritics
setup.py
mcustomscrollbar
attributeerror
congestion-control
memory-mapping
x-ray
context-sensitive-grammar
compiler-design
excel-dna
er-diagram
renaming
choice
smartfoxserver
custom-lists
deep
ikiwiki
ascii-art
asyncdisplaykit
dulwich
xmltype
mmwormhole
phpldapadmin
apache-spark-1.3
infosphere-spl
filesplitting
sonarqube-5.0
tweenlite
mdichild
unix-socket
live555
ray
unit-of-work
cffile
asdf
nevron
nebula
octal
qi4j
midlet
qtconcurrent
web-farm
fusefabric
multiplexing
box2d-iphone
saxparseexception
htdocs
mysql-error-1205
rmdir
cuteeditor
http-daemon
cdonts
collectionviewsource
mtu
metaweblog
uideviceorientation
delimited-text
folding
pbcopy
pnrp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App