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

Performance of hybrid apps vs native apps
Intrupt Incoming call in android and display my custome UI
How can I check if an app is running on an Android TV
How to link listview items to different activities in android?
OverScroller fling doesn't always finish animation where it's supposed to
Usage of onPause, onResume , onStop when declaring min-sdk
Where are Android Studio SDK platform files stored
How to save history using QuickBlox android sdk 1.2 version
on activity result method is not getting called in facebook login
Aviary sdk error
How to list number of apps installed or running only on the sd card in Android?
Recieving data from Android watch to phone
NETWORK_PROVIDER and GPS_PROVIDER returns null in fragments
Return of default sms app android isn't returning Messages
Xamarin : Using ArrayAdapter in an Android Fragment
Send large string from Android to MVC

Categories

HOME
paraview
awk
eslint
string
nvd3.js
dns
pyqt
fftw
sh
knitr
polling
retrofit2
drop-down-menu
heap
plist
java.util.logging
line
rtf
spring-social
libc
flash-player
scrolltop
magnetic-cards
keytool
job-scheduling
soci
pyramid
enterprise-miner
beautifier
shared
jackson-modules
amazon-quicksight
magento-1.8
complex-numbers
cart
fstream
autolisp
gojs
android-maps-extensions
sharding
python-import
baidu-map
yowsup
searchkit
protege4
git-rewrite-history
release
typesafe-config
setup.py
escpos
stylecop
dapper-simplecrud
linter
trojan
custom-font
vibrate
branch-prediction
rocks
simplepie
neon
android-dateutils
http-status-code-401
boost-serialization
kiosk
nullable
ascii-art
state-restoration
opl
iokit
rewrite
roadkill-wiki
ons-api
canalyzer
typemock
jsvc
mirror
snoop
ejb-2.x
dbaccess
showdialog
android-cookiemanager
android-vibration
memset
dsym
qscrollarea
getopt
ice-cube
facebook-timeline
wimax
redis-py
wcf-configuration
stress
agility.js
u2netdk
jqote
django-paypal
codebase
twitterizer
facebook-iframe
dot-emacs
silverlight-oob
web-application-project
scrubyt
fdf
commercial-application
netbeans6.1

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