how to clear RecyclerView adapter data - android

Here in my UI, i have used two buttons to load different data to a RecyclerView. First time the data is displaying properly on click of each button. But if i click the button for the second time the data is adding to the adapter twice. I mean the the adapter is not cleared. it is keep on adding the data on click of button. I Think i have to do something with the adapter on click of a button. Can anyone pls let me know how to clear the adapter or where i am going wrong..
Here is the code.
public class GstVendorLocRetrieve extends AppCompatActivity {
private String vault;
private TextView txt;
public static final String DATA_URL = "http://oursite.com/getgstvendorlocation.php?vault_no=";
public static final String DATA_URL1 = "http://oursite.com/getgstcustomerlocation.php?vault_no=";
//Tags for my JSONRes
public static final String TAG_VendorID = "VendorID";
public static final String TAG_CustomerID = "Customer_ID";
public static final String TAG_ADDRESS = "Address";
private Button vendor;
private Button customer;
//Creating a List of superheroes
private List<GstVendLoc> listSuperHeroes;
private List<GstCustLoc> listSuperHeroes1;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationretrieve);
SharedPreferences sharedPreferences = getSharedPreferences(GstLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(GstLogin.EMAIL_SHARED_PREF,"Not Available");
vendor = (Button) findViewById(R.id.login);
customer = (Button) findViewById(R.id.login1);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
listSuperHeroes1 = new ArrayList<>();
vendor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData();
}
});
customer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerView.setAdapter(null);
getData1();
}
});
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//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){
for(int i = 0; i<array.length(); i++) {
GstVendLoc gst1 = new GstVendLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setVendorID(json.getString(TAG_VendorID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter17(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private void getData1(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL1+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData1(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GstCustLoc gst1 = new GstCustLoc();
JSONObject json = null;
try {
json = array.getJSONObject(i);
gst1.setCustomer_ID(json.getString(TAG_CustomerID));
gst1.setAddress(json.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes1.add(gst1);
}
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}

Use this code for clear RecycleView items
public void clear() {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}

You need to clear your Array List before you get data second time.
Do this inside parseData1 method before for loop.
listSuperHeroes.clear();
listSuperHeroes1.clear();

What you have to do is Update RecyclerView on button Click , Put below method in your adapter
public void updateData(ArrayList<ViewModel> viewModels) {
items.clear();
items.addAll(viewModels);
notifyDataSetChanged();
}
Than call this method with new data
ArrayList<ViewModel> viewModelsWithNewData = new ArrayList<ViewModel>();
adapter.updateData(viewModelsWithNewData );

you dont need to set adapter after geting data from the online
//Finally initializing our adapter
adapter = new CardAdapter18(listSuperHeroes1, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
you can initialize of set the adapter in the on create and add data in the 'listSuperHeroes1' and after parse data you can do adapter.notifyDataSetChanged();
this will change the list data.
and the solution for the getting the previous data you have to remove the all data from the listsuperHeroes1 this will help you if you getting any problem please comment .

I am just improving #Rony's answer.
If you should always check if the ArrayList is not null before attempting to call .size(), otherwise, you might end up with a null pointer exception
if (listSuperHeroes != null && !listSuperHeroes.isEmpty()) {
int size = listSuperHeroes.size();
listSuperHeroes.clear();
notifyItemRangeRemoved(0, size);
}

Related

listview data maintain after start new activity

i have two activty A and B in my app. i am loading data from api in my listview using json and store that data in listview using getter setter method
in activity A.
now i want to maintain data in listview after start B activity and when i back from B to A activity i dont wont to download data again from json.
i am right now doing it by sotirng api responce in string and after back from B to A i pass json string to adapter but it still take time to load listview
any idea how to prevent loading time and getting data instantly when i back from B to A.
here is code of my activty A
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
pref =getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
editor = pref.edit();
itemCount_database = new ItemCount_database(this);
item_adding_cart = new Item_adding_cart(this);
String fromhome =pref.getString("from_product_view_back_Btn","");
if(fromhome.equals("yes"))
{
editor.putString("from_product_view_back_Btn","no");
editor.commit();
overridePendingTransition(R.anim.right_in, R.anim.right_out);
stored_json();
recycler_adapter = new Product_list_Recycler_Adapter(this,datalist);
recyclerView.setAdapter(recycler_adapter);
recycler_adapter.setListener(ProductList_Activity.this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
else
{
overridePendingTransition(R.anim.left_in, R.anim.left_out);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
jsoncall();
}
initialised_actionbar();
checkout = (TextView)findViewById(R.id.txt_checkout_product_list);
txt_total_amount =(TextView)findViewById(R.id.total_amount_in_checkout_label);
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myint = new Intent(ProductList_Activity.this,Cart.class);
startActivity(myint);
}
});
footer =(LinearLayout) findViewById(R.id.footer);
footer.setVisibility(View.GONE);
cart_item_count =item_adding_cart.total_product_count(1);
if(cart_item_count==0 )
{
footer.setVisibility(View.GONE);
cart_count_background.setVisibility(View.GONE);
}
else
{
footer.setVisibility(View.VISIBLE);
cart_count_background.setVisibility(View.VISIBLE);
}
wishlist_item_count = item_adding_cart.getrowcount_wishlist();
if(wishlist_item_count==0)
{
// wishlist_count_backround.setVisibility(View.GONE);
}
else
{
// wishlist_count_backround.setVisibility(View.VISIBLE);
}
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
initialization();
hidePDialog();
}
}, 3000);
boolean popup_once=pref.getBoolean("total_item_cart_insert_qery",true);
if(popup_once)
{
editor.putBoolean("total_item_cart_insert_qery",false);
editor.commit();
item_adding_cart.insert_total_item_in_cart(0);
}
}
public void jsoncall() {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("sub_cate_id","24");
params.put("city_id","3");
CustomRequest_JsonObject servicelistrequest = new CustomRequest_JsonObject
(/*Request.Method.POST,*/
url,
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
stored_json_string = response.toString();
editor.putString("stored_json_prodcutlist",stored_json_string);
editor.commit();
try {
JSONArray data = response.getJSONArray("data");
for (int ie = 0; ie < data.length(); ie++) {
JSONObject dataobje = data.getJSONObject(ie);
ModelData_Product_list_act Model = new ModelData_Product_list_act();
Model.setProduct_id(dataobje.getString("product_id"));
Model.setTitle(dataobje.getString("title"));
Model.setImage(dataobje.getString("product_image"));
Model.setWieght(dataobje.getString("weight"));
Model.setLatest_price(dataobje.getString("mrp"));
Model.setDiscount(dataobje.getString("discount"));
Model.setPre_price(dataobje.getString("retail_price"));
Model.setUnit(dataobje.getString("unit"));
datalist.add(Model);
loadlistview();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePDialog();
Toast.makeText(getApplicationContext(), "error : " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
AppController.getInstance().addToRequestQueue(servicelistrequest);
}
public void stored_json() {
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
String mystored_json = pref.getString("stored_json_prodcutlist","");
try {
JSONObject myjsonojb = new JSONObject(mystored_json);
JSONArray data = myjsonojb.getJSONArray("data");
for (int ie = 0; ie < data.length(); ie++) {
JSONObject dataobje = data.getJSONObject(ie);
ModelData_Product_list_act Model = new ModelData_Product_list_act();
Model.setProduct_id(dataobje.getString("product_id"));
Model.setTitle(dataobje.getString("title"));
Model.setImage(dataobje.getString("product_image"));
Model.setWieght(dataobje.getString("weight"));
Model.setLatest_price(dataobje.getString("mrp"));
Model.setDiscount(dataobje.getString("discount"));
Model.setPre_price(dataobje.getString("retail_price"));
Model.setUnit(dataobje.getString("unit"));
datalist.add(Model);
// loadlistview();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
Instead of using startActivity use startActivityForResult(yourIntent,REQ_CODE)
Intent startActivity = new Intent(context,ClassName.class);
startActivityForResult(startActivity,REQ_CODE);
after your come back from Activity B ,so can send your list from activity and can get in Activity A.
Then onActivityResult callback method get your intent data
I Have another idea use background task is on create and store it to local db and display the data from local db in on resume .you always call list view from local db so when you come back b to a on resume will call so it will not call on create so it will not call background data

Fetch from MySQL and update UI parallely using the Volley library

I know there are already some questions associated with this topic.
I have visited every link, but didn't help.
What I am trying to do is fetching the values from MySQL and update the UI parallely without using an AsyncTask.
I am fetching the values based on an unique id which I am getting from another Activity.
I think that since I am using the Volley library I do not need an AsyncTask.
I am getting the values from a database in a toast, but I'm unable to update the UI.
Here is my class
public class DisplayInformationActivity extends Activity implements AppCompatCallback{
private CollapsingToolbarLayout collapsingToolbarLayout;
protected AppCompatDelegate delegate;
protected String UniqueID;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String,List<String>> listDataChild;
private ProgressDialog loading;
private String Name = "";
private String contact = "";
private String email = "";
protected void onCreate(Bundle savedInstanceState){
UniqueID = getIntent().getStringExtra("uniqueID");
Toast.makeText(this,UniqueID, Toast.LENGTH_LONG).show();
fetchEverything(UniqueID);
super.onCreate(savedInstanceState);
delegate = AppCompatDelegate.create(this,this);
delegate.onCreate(savedInstanceState);
delegate.setContentView(R.layout.displayhallinformation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
delegate.setSupportActionBar(toolbar);
android.app.ActionBar actionBar = getActionBar();
if(actionBar!=null)
actionBar.setDisplayHomeAsUpEnabled(true);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(Name);
dynamicToolbarColor();
toolBarTextAppearance();
expListView = (ExpandableListView) findViewById(R.id.expandableListView);
prepareListData();
listAdapter = new ExpandableListAdapter(this,listDataHeader,listDataChild);
expListView.setAdapter(listAdapter);
}
private void fetchEverything(String uniqueID) {
RequestQueue mRequestQueue = AppController.getInstance().getRequestQueue();
mRequestQueue.start();
loading = ProgressDialog.show(this,"Loading Information ...","",false,false);
loading.setCancelable(false);
String url = AppConfig.URL_DisplayInformation+"?"+"uniqueID="+uniqueID;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
}
private void showJSON(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(AppConfig.JSON_ARRAY);
JSONObject Data = result.getJSONObject(0);
Name = Data.getString(AppConfig.first_name)+" "+Data.getString(AppConfig.last_name);
contact = Data.getString(AppConfig.contact);
email = Data.getString(AppConfig.email);
}catch (JSONException e){
e.printStackTrace();
}
Toast.makeText(this, Name+" "+contact+" "+email, Toast.LENGTH_LONG).show();
}
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<String,List<String>>();
//Adding header to expandable list view
listDataHeader.add("Information");
listDataHeader.add("Contact");
//Adding child data
List<String> Information = new ArrayList<>();
Information.add("Name : "+Name);
List<String> contact = new ArrayList<>();
contact.add("Contact Number : "+ contact);
contact.add("Email : "+ email);
//Header child data
listDataChild.put(listDataHeader.get(0),Information);
listDataChild.put(listDataHeader.get(1),contact);
}
private void dynamicToolbarColor() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.images);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary)));
collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(ContextCompat.getColor(getApplicationContext(),R.color.colorPrimaryDark)));
}
});
}
private void toolBarTextAppearance() {
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
}
How can I update the UI asynchronously?
How can i update the ui parallely ?
You need to organize the "flow" better.
For example. (indentation meaning method calls)
onCreate
fetchEverything
addToRequestQueue(stringRequest)
onResponse
showJSON
collapsingToolbarLayout.setTitle(Name) // <---- Move this here
prepareListData() // <---- Move this here
expListView = new ExpandableListAdapter...
expListView.setAdapter(listAdapter) // <--- Move this here
Update UI
// ^^^ This section your question?
Currently your code might as well be doing this
onCreate
fetchEverything
addToRequestQueue(stringRequest)
collapsingToolbarLayout.setTitle(Name)
prepareListData()
expListView = new ExpandableListAdapter...
expListView.setAdapter(listAdapter)
...
(some unknown future point)
onResponse
showJSON
Toast.makeText
So, in other words, showJSON (and your Volley data) is not coming in until after you already setup your toolbar and adapter.

Recycler view not rendering the data list

I'm trying to implement a recycler view in fragment using Volley library.
Data is loaded and logged successfully from the server but not displayed at all in the recycler fragment.
The request fetches the data and logs it but nothing renders in the fragment. There are no XML errors.
HitVideoFragment.java
public class HitVideoFragment extends Fragment {
private RecyclerView recyclerView;
private HitVideoAdapter adapter;
private List<HitVideo> hitVideoList = new ArrayList<HitVideo>();
public HitVideoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hit_video, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//Initializing Views
recyclerView = (RecyclerView) this.getActivity().findViewById(R.id.hitvideo_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new HitVideoAdapter(hitVideoList);
recyclerView.setAdapter(adapter);
//Calling method to get data
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this.getActivity(),"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(AppConfig.URL_HIT_VIDEOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("Some tag", "onResponse: "+response.toString());
hitVideoList = new ArrayList<HitVideo>();
for(int i = 0; i<response.length(); i++) {
HitVideo hitVideo = new HitVideo();
JSONObject json = null;
try {
json = response.getJSONObject(i);
hitVideo.setTitle(json.getString("name"));
hitVideo.setUrl(json.getString("url"));
hitVideo.setUsername(json.getString("user_id"));
hitVideo.setHits(json.getInt("hits"));
} catch (JSONException e) {
e.printStackTrace();
}
hitVideoList.add(hitVideo);
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Hit Video", "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
Context _context = getActivity().getApplicationContext();
SharedPreferences pref;
String token;
if (_context != null) {
pref = _context.getSharedPreferences(Config.PREF_NAME, Config.PRIVATE_MODE);
if (pref != null) {
token = pref.getString(Config.USER_TOKEN, null);
headers.put("Authorization", "Bearer " + token);
}
}
return headers;
}
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
This is not throwing any exceptions. And the model and adapters are doing their job fine. Thanks in advance.
I am probably too late to this,
But I had the same issue and I fixed it by returning the list.size() on the getItemCout() method in the Adapter class.

Issues with Volley caching mechanism

I have a website which publishes news on daily basis.
Now, I'm sending a JsonArrayRequest to retrieve and parse the title and summary of each news published on the website. The parsed items are then used to populate RecyclerView.
The problem I'm having is the way volley implements caching .
Let's take this scenario: the app is installed, launched and the RecyclerView is populated. The user reads the news and forgets about the app
Later, the user launches the app and the items are fetched and RecyclerView is populated.
Between the first and the second launch, new news are published on the website. But in the second launch, these new items are not displayed. However, if the user manually go to app settings and clear cache of the app, and relaunch, the new items are displayed.
You get my point?
While I don't want to disable Volley caching, how do I make it to always fetch new items?
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to get data
getData();
} else {
//Codes for building Alert Dialog
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Codes for Showing progress dialog
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//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){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_VIDEO_TITLE));
newsItem.setNews_body(jsonObject.getString(ConfigNews.TAG_VIDEO_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
Option 1) Delete Cache
before you make a call you can delete the whole cache by myDiskBasedCache.clear() or specific entries by myDiskBasedCache.remove(entryUrl)
Option 2) Custom CacheParser (in the Request)
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
Response<Bitmap> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
Option 3) send requests that does not cache
myRequest.setShouldCache(false);
Option 4) use custom Cache implementation
UPDATE:
Example with your code:
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Response<JSONArray> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
};
UPDATE 2
Http protocol caching supports many ways to define how the client can cache responses and when to update them. Volley simplifies those rules to:
entry.ttl (time to live in ms) if greater than the current time then cache can be used otherwise fresh request needs to be made
and
entry.softTtl (soft time to live in ms :) if greater than the current time
cache is absolutely valid and no request to the server needs to be made, otherwise new request is still made (even if the ttl is good) and if there is a change new response will be delivered.
note that if ttl is valid and softTtl is not you can receive 2 onResponse calls

Which is the right method to make a connection with server using volley?

This is may be dumb question but i could not find the solution for my problem first of all am new for android development am making connection with server using google volley to bind the recyclerview in my fragment i have written the volley connection statement in oncreateview method whenever i open that fragment its making connection with server fetching the same record as it was before here what should i do is when response is made then only i need to fetch that data from server because of this am getting same data again and again whenever i open this fragment am really confused with this can anybody help me here let me post my code:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
//Creating Views
Context context;
SharedPreferences.Editor editor;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
Task_DB task_dbobj;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
context=getActivity().getBaseContext();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Gson gsong = new Gson();
String jsons = sharedPreferences.getString(MY_PREFERENCE_KEY, "");
Type type = new TypeToken<ArrayList<Model_Task_List>>() {
}.getType();
model_task_lists = gsong.fromJson(jsons, type);
if(model_task_lists==null) {
model_task_lists = new ArrayList<Model_Task_List>();
//Showing a progress dialog
}
taskadapter = new Task_List_Adapter(model_task_lists, getContext());
recyclerView.setAdapter(taskadapter);
SharedPreferences sharedPreferences=getActivity().getSharedPreferences(LoginActivity.login,0);
String yogan=sharedPreferences.getString("user_id",null);
String Url = "http://xxx.xx.x.xxx/xxx/xxx.svc/getlist/GetTask/"+yogan;
//Creating a json array request
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.GET, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
TaskList(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
Log.e("yog", error.toString());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
return view;
}
public void TaskList(JSONObject jsonObject) {
String yogs = jsonObject.toString();
try {
JSONObject yog = new JSONObject(yogs);
JSONArray yogan = new JSONArray(yog.getString("GetTaskResult"));
for (int i = 0; i < yogan.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject yogesh = yogan.getJSONObject(i);
modelobj.setSubject(yogesh.getString("Subject"));
modelobj.setUserName(yogesh.getString("UserName"));
modelobj.setTaskStatus(yogesh.getString("TaskStatus"));
model_task_lists.add(modelobj);
taskadapter.notifyDataSetChanged();
// task_dbobj.insert(modelobj);
}
//Finally initializing our adapter
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
context=getActivity().getApplicationContext();
SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(context);
editor = sharedpref.edit();
Gson gson=new Gson();
String god = gson.toJson(model_task_lists);
editor.putString(MY_PREFERENCE_KEY, god);
editor.commit();
super.onStop();
}
}
I would be very glad if someone tells the solution for my problem !!! you people are here to help beginners like us hope someone helps !!!
First of all, I would suggest to change your library, Volley is not completely upgraded to API 23 (since org.apache package is removed you will have to use legacy code), so I suggest to move to okHttp or some other library.
In case you want to stick with Volley you should create Volley.newRequestQueue(getContext()); inside onCreate() method in your Application class, and then reuse same queue, not creating new one each time inside fragment.

Categories

Resources