I have a problem. I don't understand how you can implement pdf viewing quickly. I use urlconnection to open pdf but it takes a very long time to load. I want to make caching so that when I re-view the pdf, there would be no download. Please tell me how this can be done?I would be very grateful if someone could tell me and show me how to do this.
My code:
myPDFListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
setContentView(R.layout.viewfile_activity);
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
pdfView=findViewById(R.id.pdfView);
uploadPDF uploadPDF = uploadPDFS.get(position);
new RetrievePDFStream().execute(uploadPDF.url);
}
});
}
class RetrievePDFStream extends AsyncTask<String,Void,InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream)
.enableSwipe(true)
.load();
}
}
private void viewAllFiles() {
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot postSnapshot : snapshot.getChildren()){
uploadPDF uploadPDF = postSnapshot.getValue(com.tokha.diplom.uploadPDF.class);
uploadPDFS.add(uploadPDF);
}
String[] uploads = new String[uploadPDFS.size()];
for(int i = 0;i<uploads.length;i++){
uploads[i] = uploadPDFS.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, uploads){
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView myText = (TextView) view.findViewById(android.R.id.text1);
myText.setTextColor(getResources().getColor(R.color.autorization));
return view;
}
};
myPDFListView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Related
There is a problem with the data displayed in the recyclerview when I run my program
it looks like this:
.
For the data that is displayed I use firebase like this the
data structure:
When I want to display data in recyclerview in a fragment, but the data doesn't appear. I use Firebase as database
NotaAdapter.java
public class NotaAdapter extends RecyclerView.Adapter<NotaAdapter.MyViewHolder> {
Context context;
ArrayList<ListNota> listnota;
public NotaAdapter (Context c,ArrayList<ListNota> p) {
this.context = c;
this.listnota = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_nota, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.no_nota.setText(listnota.get(i).getId_nota());
myViewHolder.total_harga.setText(String.valueOf(listnota.get(i).getTotal_seluruh()));
final String getnoNOta = listnota.get(i).getId_nota();
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoDetailNota = new Intent(context, DetailNotaAct.class);
gotoDetailNota.putExtra("no_nota", getnoNOta);
context.startActivity(gotoDetailNota);
}
});
}
#Override
public int getItemCount() {
return listnota.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView no_nota, total_harga;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
no_nota = itemView.findViewById(R.id.xid_nota);
total_harga = itemView.findViewById(R.id.xtotal_seluruh);
}
}
}
ListNota.java
public class ListNota {
private String id_nota;
private Integer total_seluruh;
public ListNota() {
}
public ListNota(String id_nota, Integer total_seluruh) {
this.id_nota = id_nota;
this.total_seluruh = total_seluruh;
}
public String getId_nota() {
return id_nota;
}
public void setId_nota(String id_nota) {
this.id_nota = id_nota;
}
public Integer getTotal_seluruh() {
return total_seluruh;
}
public void setTotal_seluruh(Integer total_seluruh) {
this.total_seluruh = total_seluruh;
}
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
TextView txt_history, txt_toko, txt_report, txt_nama_toko, txt_jenis_toko;
LinearLayout btn_buat_nota;
DatabaseReference databaseUser, databaseToko, databaseNota;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
String id_Toko = "";
ProgressDialog progress;
RecyclerView nota_place;
ArrayList<ListNota> list;
NotaAdapter notaAdapter;
private View Notaview;
public HistoryFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Notaview = inflater.inflate(R.layout.fragment_history, container, false);
txt_nama_toko = (TextView) Notaview.findViewById(R.id.txt_nama_toko);
txt_jenis_toko = (TextView) Notaview.findViewById(R.id.txt_jenis_toko);
txt_history = (TextView) Notaview.findViewById(R.id.txt_history);
txt_toko = (TextView) Notaview.findViewById(R.id.txt_toko);
txt_report = (TextView) Notaview.findViewById(R.id.txt_report);
btn_buat_nota = (LinearLayout) Notaview.findViewById(R.id.btn_buat_nota);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Memuat Data");
progress.setCancelable(false);
progress.show();
getUsernameLocal();
databaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
id_Toko = dataSnapshot.child("id_toko").getValue().toString();
databaseToko = FirebaseDatabase.getInstance().getReference().child("Toko").child(id_Toko);
databaseToko.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
txt_nama_toko.setText(dataSnapshot.child("nama_toko").getValue().toString());
//cek apakah child jenis toko ada
if (dataSnapshot.hasChild("jenis_toko")){
txt_jenis_toko.setText(dataSnapshot.child(" jenis_toko").getValue().toString());
}else{
txt_jenis_toko.setText("Jenis toko belum disetting");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_buat_nota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id_nota = generateRandomString(16);
Intent gotoBuatNota = new Intent(getActivity(), BuatNotaAct.class);
gotoBuatNota.putExtra("id_nota", id_nota);
startActivity(gotoBuatNota);
}
});
nota_place = (RecyclerView) Notaview.findViewById(R.id.nota_place);
notaAdapter = new NotaAdapter(getContext(), list);
nota_place.setAdapter(notaAdapter);
nota_place.setLayoutManager(new LinearLayoutManager(getActivity()));
return Notaview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<ListNota>();
loaddata();
}
private void loaddata(){
databaseNota = FirebaseDatabase.getInstance().getReference().child("Nota").child(id_Toko);
databaseNota.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ListNota p = dataSnapshot1.getValue(ListNota.class);
list.add(p);
}
progress.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public String generateRandomString(int length){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int i = 0; i < length; i++){
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
you are reading it from the wrong node, you are passing reference that you want to read data from the node Named "users".
Your Database reference should look like this
databaseUser = FirebaseDatabase.getInstance().getReference("Nota").child("Toko_Kita20082020371").child(username_key_new);
Also make sure your list should have all the variables that a node has.
For example a node has
name,id,price,description;
then same varibles should be declared in your list to successfully ready dta from the firebase.
I'm developing an android app where the details from the Firebase Realtime Database will be shown in Recycler View.
I want to make it like expandable recyclerview.
But I'm getting a error when i tried to use my adapter.
Variable 'adapter' might not have been initialised
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Employee>()
.setQuery(mAttendanceDatabase, Employee.class)
.build();
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> adapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final EmployeeViewHolder holder, final int position, #NonNull Employee model) {
String employee_Id = getRef(position).getKey();
assert employee_Id != null;
mAttendanceDatabase.child(employee_Id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String employee_Name = dataSnapshot.child("employeeName").getValue().toString();
holder.employeeName.setText(employee_Name);
holder.btn_viewMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.getItem(position); //I'm getting error here
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_view_layout, parent, false);
EmployeeViewHolder viewHolder = new EmployeeViewHolder(view);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class EmployeeViewHolder extends RecyclerView.ViewHolder{
TextView employeeName;
ImageButton btn_viewMore;
public EmployeeViewHolder(#NonNull View itemView) {
super(itemView);
employeeName = itemView.findViewById(R.id.employeeName_evl);
btn_viewMore = itemView.findViewById(R.id.viewMoreBtn);
}
}
I can't find any proper solution. Help me with this.
try to put the adapter over this in a variable:
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Employee>()
.setQuery(mAttendanceDatabase, Employee.class)
.build();
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> adapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final EmployeeViewHolder holder, final int position, #NonNull Employee model) {
String employee_Id = getRef(position).getKey();
assert employee_Id != null;
final FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> thisAdapter = this;
mAttendanceDatabase.child(employee_Id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String employee_Name = dataSnapshot.child("employeeName").getValue().toString();
holder.employeeName.setText(employee_Name);
holder.btn_viewMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
thisAdapter.getItem(position); //I'm getting error here
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_view_layout, parent, false);
EmployeeViewHolder viewHolder = new EmployeeViewHolder(view);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
Edit
To support my case I made a minimal Example:
I am trying to set some strings in the sharedPreferences but when I restart the app , the preference is coming empty and so "null" is returned in getString method .
public class settingsView extends Fragment {
DataSnapshot citiesSnap;
Spinner theaterSpinner, citySpinner;
String selectedCity, selectedTheater;
String[] cities = {"Bagalkot", "Belgaum", "Bellary", "Bijapur", "Chitradurga", "Davanagere", "Dharwad", "Gadag", "Hassan", "Hosapete", "Hospet", "Hubli", "Mysore", "Shimoga", "Tumkur"};
List<String>theaters ;
public settingsView() {
Log.d("testing" , "settingsview constructor called");
citiesSnap = null;
theaterSpinner = null;
citySpinner = null;
selectedCity = null;
selectedTheater = null;
theaters = null ;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("testing", "Called onActivityCreated");
citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);
theaterSpinner = (Spinner) getActivity().findViewById(R.id.theaterSpinner);
final SharedPreferences mSettings = this.getActivity().getPreferences(Context.MODE_PRIVATE);
selectedCity = mSettings.getString("selectedCity", "null" );
selectedTheater = mSettings.getString("selectedTheater", "null");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, cities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(adapter);
updateTheatersSpinner(selectedCity);
if(theaters!=null)
theaterSpinner.setSelection(theaters.indexOf(selectedTheater));
FirebaseDatabase.getInstance().getReference("movies/karnataka").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
citiesSnap = dataSnapshot;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
updateTheatersSpinner(citySpinner.getSelectedItem().toString());
mSettings.edit().putString("selectedCity" , citySpinner.getSelectedItem().toString()).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
mSettings.edit().putString("selectedTheater" , theaterSpinner.getSelectedItem().toString()).commit() ;
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settingsview, container, false);
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit().putString("selectedCity", selectedCity).putString("selectedTheater", theaterSpinner.getSelectedItem().toString()).commit();
}
public void updateTheatersSpinner(String city) {
if (citiesSnap != null) {
ArrayList<String> theaterlist = new ArrayList<>();
for (DataSnapshot snapshot : citiesSnap.child(city).getChildren()) {
theaterlist.add(snapshot.getKey());
}
this.theaters = theaterlist ;
Log.d("firebasedata", "theaterlist : " + theaterlist.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, theaterlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.theaterSpinner.setAdapter(adapter);
}
}
}
You have the class fields selectedCity and selectedTheater which you never update so they are always null, but then in onSaveInstanceState you save those fields, so when your activity closes, it writes null to both fields in the SharedPreferences. You should update those fields when the spnner changes.
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedCity = citySpinner.getSelectedItem().toString(); // <--
updateTheatersSpinner(selectedCity);
mSettings.edit().putString("selectedCity", selectedCity).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedTheater = theaterSpinner.getSelectedItem().toString(); // <--
mSettings.edit().putString("selectedTheater", selectedTheater).commit();
}
});
Then, in onSaveInstanceState
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit()
.putString("selectedCity", selectedCity)
.putString("selectedTheater", selectedTheater)
.commit();
}
Please help me. I want to show the username only once from firebase. Although the user have multiple record in the firebase, I just want to view the name of user who make order. The user can make multiple order, but I just want to show their name once.
I tried many ways but can't succeed. Someone who know about this? Thank you very much.
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance();
mItems = new ArrayList<>();
wordDulicate = new ArrayList<>();
tempList = new ArrayList<>();
if(UID != null){
mItemsKey = new ArrayList<>();
mOrderedItemRef = mDatabase.child("OrderedItem");
Log.d(TAG, " mOrderedItemRef:" + mOrderedItemRef);
mOrderedItemVEL = mOrderedItemRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
wordDulicate.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
mItems.add(orderedItem);
mItemsKey.add(d.getKey());
}
updateUI();
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "get item databaseError: "+databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy(){
super.onDestroy();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public void onDetach(){
super.onDetach();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_admin_list_user_order, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.admin_order_recycler_view);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI(){
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder{
OrderedItem mItems;
TextView mNameTextView;
ItemHolder(final View itemView){
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_username);
/* if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("LongLogTag")
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Item?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}*/
}
void bindData(OrderedItem s){
mItems = s;
mNameTextView.setText(s.getUserName());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<OrderedItem> mItems;
ItemAdapter(ArrayList<OrderedItem> Items){
mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.admin_listed_user_order,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
OrderedItem s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
}
Since you rely on a key and a value, why not use a map instead? Maps have a key and a value, and you can check whether or not an item with a key is present by getting the key, instead of having to iterate through the list and find duplicates.
First you need to initialize it:
Map<String, ArrayList<OrderedItem>> items = new HashMap<>();
The value is an ArrayList to keep any existing data
then put the items:
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
items.putIfAbsent(d.getKey(), new ArrayList<>());//create a list if it doesn't exist
items.get(d.geyKey()).add(orderedItem);//add the item
}
and clearing with a map is the same as with lists
I have a recyclerview and i'm trying to implement Endless Scroll with this popular android Endless scroll Library. It almost working well, except that when i get to the buttom of the current list, it reloads and starts from the top instead of continuing from the last visible item.
This is my Scroll Listerner.
scrollListener = new EndlessRecyclerViewScrollListener(manager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
loadMore(page);
++page;
}
};
mRecyclerView.addOnScrollListener(scrollListener);
This is my loadMore()
public void loadMore(int page) {
String url = myurl + page;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.i("Responses", response);
ArrayList<Deal> deals = new JsonConverter<Deal>().toArrayList(response, Deal.class);
dealArrayList.addAll(deals);
adapter = new DealAdapter(getApplicationContext(), dealArrayList);
mRecyclerView.setAdapter(adapter);
newList = deals;
adapter.notifyItemRangeInserted(newList.size(), dealArrayList.size());
stopAnim();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getApplicationContext(), "Bad Network Connection. Please Try Again", Toast.LENGTH_LONG).show();
stopAnim();
}
}
);
int socketTimeout = 30000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
mSwipeRefresh.setRefreshing(false);
}
I can't figure out whats wrong.
Help.
Edited..
My app calls this function when it first lunches and then call the loadMore function when i scroll.
public void firstRun(int page) {
String url = myurl + page;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("Responses", response);
dealArrayList = new JsonConverter<Deal>().toArrayList(response, Deal.class);
adapter = new DealAdapter(getApplicationContext(), dealArrayList);
mRecyclerView.setAdapter(adapter);
newList = dealArrayList;
adapter.notifyDataSetChanged();
stopAnim();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getApplicationContext(), "Bad Network Connection. Please Try Again", Toast.LENGTH_LONG).show();
stopAnim();
}
}
);
int socketTimeout = 30000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
mSwipeRefresh.setRefreshing(false);
}
This is my Adapter
public class DealAdapter extends RecyclerView.Adapter<DealAdapter.ViewHolder> {
private Context context;
private ArrayList<Deal> deals;
public DealAdapter(Context context, ArrayList<Deal> deals) {
this.context = context;
this.deals = deals;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.card_view, parent, false);
final ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Deal deal = deals.get(position);
holder.mCardTitle.setText(deal.title);
holder.mCardLocation.setText(deal.location);
holder.mCardDiscount.setText(String.valueOf(deal.discount));
holder.mCardPrice.setText(deal.price);
holder.mCardContact.setText(deal.contact);
holder.mCardDescription.setText(deal.description);
String url = myurl + deal.image;
Picasso.with(context)
.load(url).resize(0,300)
.placeholder(R.drawable.load)
.error(android.R.drawable.stat_notify_error)
.into(holder.mCardImage);
holder.mCardDescription.setOnClickListener(new View.OnClickListener() {
boolean isClicked = false;
#Override
public void onClick(View v) {
if(isClicked){
//This will shrink textview to 2 lines if it is expanded.
holder.mCardDescription.setMaxLines(2);
holder.more.setVisibility(View.VISIBLE);
holder.mCardInvisible.setVisibility(View.GONE);
isClicked = false;
} else {
//This will expand the textview if it is of 2 lines
holder.mCardDescription.setMaxLines(Integer.MAX_VALUE);
holder.more.setVisibility(View.GONE);
holder.mCardInvisible.setVisibility(View.VISIBLE);
isClicked = true;
}
}
});
}
#Override
public int getItemCount() {
if (deals != null) {
return deals.size();
}else{
return 0;
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mCardTitle;
private ImageView mCardImage;
private TextView mCardLocation;
private TextView mCardDescription;
private TextView mCardContact;
private TextView mCardPrice;
private TextView mCardDiscount, more;
private LinearLayout mCardInvisible;
private ViewHolder(View itemView) {
super(itemView);
mCardTitle = (TextView) itemView.findViewById(R.id.mCardTitle);
mCardImage = (ImageView) itemView.findViewById(R.id.mCardImage);
mCardLocation = (TextView) itemView.findViewById(R.id.mCardLocation);
mCardDescription = (TextView) itemView.findViewById(R.id.mCardDescription);
mCardContact = (TextView) itemView.findViewById(R.id.mCardContact);
mCardPrice = (TextView) itemView.findViewById(R.id.mCardPrice);
mCardDiscount = (TextView) itemView.findViewById(R.id.mCardDiscount);
more = (TextView) itemView.findViewById(R.id.mCardMore);
mCardInvisible = (LinearLayout) itemView.findViewById(R.id.mCardInvisible);
}
}
}
Edited:: This is my OnRefresh Listener
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
firstRun(1);
}
}, 3000);
}
});
In your adapter add a new function that merges the data you have with the new ones:
public void addAll(List data){
deals.addAll(data);
notifyDataSetChanged();
}
Your onResponse in loadMore function should look like:
public void onResponse(String response) {
//Log.i("Responses", response);
ArrayList<Deal> deals = new JsonConverter<Deal>().toArrayList(response, Deal.class);
adapter.addAll(deals);
stopAnim();
}