Skip to content

Commit

Permalink
Dynamic loading of friends using a pull to load recycler view
Browse files Browse the repository at this point in the history
  • Loading branch information
icancode23 committed Jul 11, 2017
1 parent ab5d123 commit bd86bf1
Show file tree
Hide file tree
Showing 9 changed files with 256 additions and 42 deletions.
2 changes: 1 addition & 1 deletion kute-android-app/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions kute-android-app/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,15 @@
android:name=".PrivateVehicles.App.Activities.test"
android:label="@string/title_activity_test"
android:theme="@style/AppTheme">

</activity>
<activity android:name=".PrivateVehicles.App.Activities.ProfilePictureActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

</activity>
<activity android:name=".PrivateVehicles.App.Activities.ProfilePictureActivity">

</activity>
</application>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
import android.widget.ProgressBar;

import com.scorelab.kute.kute.PrivateVehicles.App.Adapters.FriendRecyclerAdapter;
import com.scorelab.kute.kute.PrivateVehicles.App.AsyncTasks.LoadFirebaseFriends;
import com.scorelab.kute.kute.PrivateVehicles.App.DataModels.Person;
import com.scorelab.kute.kute.PrivateVehicles.App.Interfaces.AsyncTaskListener;
import com.scorelab.kute.kute.PrivateVehicles.App.Interfaces.RecyclerItemClick;
import com.scorelab.kute.kute.R;
import java.util.ArrayList;



public class CurrentFriendList extends AppCompatActivity implements RecyclerItemClick {
//We can optimize the loading of friends by restricting firebase content to return just two fields for each user and then retrieve detail only when specific persons detail activity is opened
public class CurrentFriendList extends AppCompatActivity implements RecyclerItemClick,AsyncTaskListener {
static String TAG = "CurrentFriendActivity";
ArrayList<String> person_list;
ArrayList<Person>person_detail_list;
Expand All @@ -29,15 +31,19 @@ public class CurrentFriendList extends AppCompatActivity implements RecyclerItem
final int[] pastVisiblesItems = new int[1];
final int[] visibleItemCount = new int[1];
final int[] totalItemCount = new int[1];
int start_index_async,last_index_async,range;
ProgressBar progressBar;
boolean is_async_task_running=false;// A boolean created to prevent a new asynctask being created everytime we scroll down
LoadFirebaseFriends load_friends_async;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_friends_activity);
person_list = new ArrayList<String>();
person_detail_list=(ArrayList<Person>) getIntent().getSerializableExtra("FriendList");
person_list = (ArrayList<String>)getIntent().getSerializableExtra("FriendList");
person_detail_list=(ArrayList<Person>) getIntent().getSerializableExtra("FriendDetailList");
/************** Initialise the views *********/
//TODO get friends from facebook and google and get their images
Log.d(TAG,"The length of the person list is:"+Integer.toString(person_list.size()));
progressBar=(ProgressBar)findViewById(R.id.progressBar);
back = (ImageButton) findViewById(R.id.backNav);
back.setOnClickListener(new View.OnClickListener() {
Expand All @@ -60,24 +66,18 @@ public void onScrolled(RecyclerView recyclerView,
visibleItemCount[0] = mLayoutManager.getChildCount();//Gives the number of children currently on the screen
totalItemCount[0] = mLayoutManager.getItemCount();//gives total items of recycler view
pastVisiblesItems[0] = mLayoutManager.findFirstVisibleItemPosition();//gives the index of item at the top of the screen

Log.d("Recycler",String.format("visible %d past visible %d total %d",visibleItemCount[0],pastVisiblesItems[0],totalItemCount[0]));
if ((visibleItemCount[0] + pastVisiblesItems[0]) >= totalItemCount[0]) {
Log.d("Check it",String.format("%d %d",mLayoutManager.findLastCompletelyVisibleItemPosition(),recycler_adapter.getItemCount()));
if ((visibleItemCount[0] + pastVisiblesItems[0]) >= totalItemCount[0]&& visibleItemCount[0]!=totalItemCount[0] ) {
if(mLayoutManager.findLastCompletelyVisibleItemPosition()==recycler_adapter.getItemCount()-1 /*&& recycleradapter.getItemCount()>5 You have your ofset values here*/){
//************************* Reached the End of recycler View ***********/
Log.d("Status","reached the Bottom");
//************** Set The visibility of progress bar as true *****/
progressBar.setVisibility(View.VISIBLE);
Log.d(TAG,"reached the Bottom");
//******************** Call The function to load more data *********//
loadRecyclerItems(recycler_adapter.getItemCount());


loadRecyclerItems(recycler_adapter.getItemCount()-1);
}

}
}
});

}

@Override
Expand All @@ -88,16 +88,61 @@ public void onRecyclerItemClick(int position) {
i.putExtra("isAFriend", true);
startActivity(i);
}
//Asynctask Interacting interface
@Override
public void onTaskStarted(Object...attachments) {
//toggle the boolean to show that asynctask is running
is_async_task_running=true;
//get the index from asynctask
start_index_async=(int)attachments[0];
last_index_async=(int)attachments[1];
range=last_index_async-last_index_async+1;

}

@Override
public void onTaskCompleted(Object attachment) {
Log.d(TAG,"The start indice is "+Integer.toString(start_index_async));
Person temp=(Person)attachment;
person_detail_list.add(temp);
Log.d(TAG,"Received in test Friend name: "+temp.name);
if(start_index_async>=last_index_async) {
recycler_adapter.notifyItemRangeInserted(recycler_adapter.getItemCount(),range);
is_async_task_running=false;
Log.d(TAG,"Current Length Of Recycler is"+Integer.toString(recycler_adapter.getItemCount()-1));
progressBar.setVisibility(View.GONE);
}
++start_index_async;

}

/***************** Custom Function ******/
private void loadRecyclerItems(Integer current_length)
{
Log.d(TAG,"Current size is "+Integer.toString(recycler_adapter.getItemCount()));
if(person_list.size()==current_length){
//When we have loaded all the items
Log.d("check","Yes");
}
else{

else {
//************** Set The visibility of progress bar as true *****/
progressBar.setVisibility(View.VISIBLE);
int difference = person_list.size() - current_length;
//we need to load more friends from facebook
if (!is_async_task_running) {
load_friends_async=new LoadFirebaseFriends(person_list,this);
if (difference < 9) {
load_friends_async.execute(current_length+1, (person_list.size()-1));
}else {
load_friends_async.execute(current_length+1,current_length+9);
}
}
}
}

@Override
protected void onStop() {
super.onStop();
load_friends_async.cancel(true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,51 @@

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.scorelab.kute.kute.PrivateVehicles.App.AsyncTasks.LoadFirebaseFriends;
import com.scorelab.kute.kute.PrivateVehicles.App.DataModels.Person;
import com.scorelab.kute.kute.PrivateVehicles.App.Fragments.HomeBaseFragment;
import com.scorelab.kute.kute.PrivateVehicles.App.Interfaces.AsyncTaskListener;
import com.scorelab.kute.kute.R;

import java.util.ArrayList;

public class test extends AppCompatActivity {
public class test extends AppCompatActivity implements AsyncTaskListener {
Button b;
ArrayList<Person>list;
LoadFirebaseFriends load_friends_async;
ArrayList<String> friend_list;
String TAG="Test";
int start_index_async,last_index_async;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
b=(Button)findViewById(R.id.testButton);
friend_list=new ArrayList<String>();
list=new ArrayList<Person>();
for (int i=0;i<10;++i)
{
Person temp=new Person("Nipun","10110101010110101");
list.add(temp);

}

b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),CurrentFriendList.class);
i.putExtra("FriendList",list);
startActivity(i);
//addTestFriends();
getFirebaseFriend();
}
});
setSupportActionBar(toolbar);
Expand All @@ -50,5 +60,75 @@ public void onClick(View view) {
});
}

private void addTestFriends(){
DatabaseReference ref= FirebaseDatabase.getInstance().getReference();
DatabaseReference friend_ref=ref.child("Friends/Nipun Arora");
DatabaseReference user_ref=ref.child("Users");
final String[]names={"Nipun","Harsh","Sukhad","Vishrut","jwalin","Shivam","Jatin","Archit","Shubham","Rajat"};
list=new ArrayList<Person>();
for (int i=0;i<10;++i)
{
String key=user_ref.push().getKey();
final Person temp=new Person(key,names[i]);
user_ref.child(key).setValue(temp).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.v("test","Failed as"+e.toString());
}
});
friend_ref.child(key).setValue("true");
Log.v("testit","Added "+names[i]);

}
}

//Asynctask Interacting interface
@Override
public void onTaskStarted(Object...attachments) {
//get the index from asynctask
start_index_async=(int)attachments[0];
last_index_async=(int)attachments[1];
}

@Override
public void onTaskCompleted(Object attachment) {
Log.d(TAG,"The start indice is "+Integer.toString(start_index_async));
Person temp=(Person)attachment;
list.add(temp);
Log.d(TAG,"Received in test Friend name: "+temp.name);
if(start_index_async>=last_index_async) {
Log.d(TAG,"called");
Intent i = new Intent(test.this, CurrentFriendList.class);
i.putExtra("FriendList", friend_list);
i.putExtra("FriendDetailList", list);
startActivity(i);
}
++start_index_async;

}

public void getFirebaseFriend() {
/******************** Getting Friends From Firebase *************/
String ref = "Friends/" +"Nipun Arora";
Log.d(TAG, "Firebase Reference :" + ref);
DatabaseReference friends = FirebaseDatabase.getInstance().getReference(ref);
friends.keepSynced(true);
friends.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot k : dataSnapshot.getChildren()) {
friend_list.add(k.getKey());
Log.d(TAG, "Debug Firebase data query" + k.getValue().toString());
}

Log.d(TAG, String.format("The Friend List Size is %d",friend_list.size()));
load_friends_async=new LoadFirebaseFriends(friend_list,test.this);
load_friends_async.execute(0,8);
}

@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.scorelab.kute.kute.PrivateVehicles.App.AsyncTasks;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.scorelab.kute.kute.PrivateVehicles.App.DataModels.Person;
import com.scorelab.kute.kute.PrivateVehicles.App.Interfaces.AsyncTaskListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
* Created by nipunarora on 10/07/17.
*/

public class LoadFirebaseFriends extends AsyncTask<Integer,Void,Void> {
ArrayList<String>friend_list;
WeakReference<AsyncTaskListener> async_task_listener;
String TAG="LoadFirebaseFriend";

public LoadFirebaseFriends(ArrayList<String>friend_list, AsyncTaskListener asyncTaskListener) {
this.friend_list=friend_list;
this.async_task_listener=new WeakReference<AsyncTaskListener>(asyncTaskListener);

}

@Override
protected Void doInBackground(Integer... params) {
//Through params we can pass the indices for which data is required
Log.v(TAG,"The indices received here are "+Integer.toString(params[0])+"and "+Integer.toString(params[1]));
final ArrayList<Person>person_detail_list=new ArrayList<Person>();
DatabaseReference users= FirebaseDatabase.getInstance().getReference("Users");
final AsyncTaskListener taskListener=async_task_listener.get();
taskListener.onTaskStarted(params[0],params[1]);
for(int i=params[0];i<=params[1];++i) {
Log.v(TAG,"The size in asynctask is"+Integer.toString(friend_list.size()));
if (i<friend_list.size()) {
Log.v(TAG,"Status:entered");
String first_friend_key = friend_list.get(i);
Query get_friend = users.orderByKey().equalTo(first_friend_key);
get_friend.keepSynced(true);
get_friend.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Person p = dataSnapshot.getChildren().iterator().next().getValue(Person.class);
if(async_task_listener!=null){
//Check if the weak reference still exists
Log.v(TAG,"Retrieved Friend "+p.name);
taskListener.onTaskCompleted(p);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else {
Log.v(TAG,"All Friends Already Downloaded");
break;
}
}
return null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,5 @@ public Person(String id, String name) {
this.other_details="--";
this.route_list=null;*/
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,14 @@ public void onDetach() {
}
/********************* Custom Functions *************/
//Receive Message from Activity and other fragments
public void receiveMessage(String Action,Object friend_list,Object person_detail_list )
public void receiveMessage(String Action,Object...attachment )
{
Log.d(TAG,"Message Received : "+Action);
switch (Action)
{
case "Friends_Ready":
friendslist=(ArrayList<String>)friend_list;
friend_detail_list=(ArrayList<Person>) person_detail_list;
friendslist=(ArrayList<String>)attachment[0];
friend_detail_list=(ArrayList<Person>)attachment[1];
if(friendslist.size()>0) {
setupCurrentFriends();
}
Expand Down
Loading

0 comments on commit bd86bf1

Please sign in to comment.