I recently set up my RecyclerView and want to slide in all new items that are added. Specifically, I have a comment screen and every time a new comment is added, I want it to slide in from the left with an animation effect.
Note that I add all new items to my mCommentArrayList at index 0 so that they appear at the top of the view.
I have read about using third-party libraries, but from what I understand that is not necessary. Here is my code:
Where I first call to Firebase to find data to populate the RecyclerView:
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
setImage(dataSnapshot);
setQuestion(dataSnapshot);
createInitialCommentIDArray(dataSnapshot);
mNumberOfCommentsAtPoll = (int) dataSnapshot.child(COMMENTS_LABEL).getChildrenCount();
for (int i = 0; i < mNumberOfCommentsAtPoll; i++) {
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("COMMENT").getValue();
Log.v("COMMENT_ID", "The comment ID is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("USER_ID").getValue();
Log.v("USER_ID", "The user ID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Subsequent Calls to Firebase on Data Change:
#Override
protected void onStart() {
super.onStart();
mUpdateComments = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mNumberOfCommentsAtPoll = (int) dataSnapshot.getChildrenCount();
for (DataSnapshot x : dataSnapshot.child(COMMENTS_LABEL).getChildren()) {
Log.v("DATA_SNAPSHOT", x.toString());
if (mCommentIDArrayList.contains(x.getKey())) {
Log.v("Comment_Already_Added", x.getKey());
} else {
Log.v("Child_Added_Called", "Child Added Called");
mCommentIDArrayList.add(x.getKey());
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(x.getKey()).child("COMMENT").getValue();
Log.v("New_Comment", "The new comment is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(x.getKey()).child("USER_ID").getValue();
Log.v("New_User_ID", "The new userID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
}
My RecyclerView Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Comments> mDataSet;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected ImageView userAvatar;
protected TextView userID;
protected TextView userComment;
public ViewHolder(View v) {
super(v);
userAvatar = (ImageView) v.findViewById(R.id.profile_image);
userID = (TextView) v.findViewById(R.id.user_ID);
userComment = (TextView) v.findViewById(R.id.user_comment_textview);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Comments> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_comment, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Comments comment = mDataSet.get(position);
holder.userComment.setText(comment.getUserComment());
holder.userID.setText("User " + position);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.size();
}
}
Related
I want to retrieve my firebase data into a card list, but not showing anything.
public class GroupAdp extends RecyclerView.Adapter<GroupAdp.ViewHolder> {
//Initialize activities and array list
private Activity activity;
ArrayList<String> arrayListGroup;
//Create constructor
GroupAdp(Activity activity,ArrayList<String> arrayListGroup){
this.activity = activity;
this.arrayListGroup = arrayListGroup;
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row_group,parent,false);
return new GroupAdp.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set group name on TextView
holder.tvName.setText(arrayListGroup.get(position));
//Initialize member ArrayList
ArrayList<String> arrayListMember = new ArrayList<>();
//Using for loop to add multiple members
for (int i=1; i<=6; i++){
arrayListMember.add("Member " + i);
}
//Initialize member adapter
MemberAdp adapterMember = new MemberAdp(arrayListMember);
//Initialize layout manager
LinearLayoutManager layoutManagerMember = new LinearLayoutManager(activity);
//Set layout manager
holder.rvMember.setLayoutManager(layoutManagerMember);
//Set adapter
holder.rvMember.setAdapter(adapterMember);
}
#Override
public int getItemCount() {
return arrayListGroup.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
TextView tvName;
RecyclerView rvMember;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
tvName = itemView.findViewById(R.id.tv_name);
rvMember = itemView.findViewById(R.id.rv_member);
}
}
}
public class MemberAdp extends RecyclerView.Adapter<MemberAdp.ViewHolder> {
//Initialize ArrayList
ArrayList<String> arrayListMember;
//Create constructor
public MemberAdp(ArrayList<String> arrayListMember) {
this.arrayListMember = arrayListMember;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Initialize view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row_member,parent,false);
return new MemberAdp.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set member name on TextView
holder.tvName.setText(arrayListMember.get(position));
}
#Override
public int getItemCount() {
return arrayListMember.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
TextView tvName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
tvName = itemView.findViewById(R.id.tv_name);
}
}
}
public class HealthAlertActivity2 extends Fragment {
//Initialize variable
RecyclerView rvGroup;
ArrayList<String> arrayListGroup;
LinearLayoutManager layoutManagerGroup;
GroupAdp adapterGroup;
//#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View healthAlertFragment = inflater.inflate(R.layout.healthalert_activity2, container, false);
//Assign variable
rvGroup = healthAlertFragment.findViewById(R.id.rv_group);
//Using for loop to add multiple group
//Used for dummy display for now
arrayListGroup = new ArrayList<>();
// for (int i= 1; i<=6; i++){
// arrayListGroup.add("Group " + i);
// }
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Course_ID_Section");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Map<String, Object> map = (Map<String, Object>) snapshot.getValue();
Log.e("LOG_TAG", "Value is:" + map);
assert map != null;
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.e("The Result", entry.getKey() + "/" + entry.getValue());
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String UID = user.getUid();
if (UID.equals(entry.getValue())) {
arrayListGroup.add("Class" + entry.getValue());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e("LOG_TAG", "Failed to read value.", error.toException());
}
});
//Initialize group adapter
adapterGroup = new GroupAdp(getActivity(),arrayListGroup);
//Initialize layout manager
layoutManagerGroup = new LinearLayoutManager(getActivity());
//Set layout manager
rvGroup.setLayoutManager(layoutManagerGroup);
//Set adapter
rvGroup.setAdapter(adapterGroup);
return healthAlertFragment;
}
}
I want the Group name to be the Course_ID_Section, for example, CSCI-110-MO1. Only if the value inside of this key(CSCI-110-MO1) is the same as the firebase UID. Otherwise, perform no action.
Currently, I am dealing with this kind output:
E/LOG_TAG: Value is:{CSCI-110-M01={BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}, CSCI-415-M01={BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}, CSCI-455-M03={BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}, CSCI-300-M02={BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}, CSCI-318-M01={BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}}
E/The Result: CSCI-110-M01/{BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}
E/The Result: CSCI-415-M01/{BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}
CSCI-455-M03/{BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}
CSCI-300-M02/{BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}
CSCI-318-M01/{BiazGfcXiBYKUUGk4NGwXjJ5C7k2=***********, nGrAfIS6NgbBlkmSPUA0zm4qwQb2=***********}
Not sure if it is the "=" causing me the problem. Only want to compare firebase UID in this case.
You're loading data from:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Course_ID_Section");
This means the snapshot you get has two nested, levels of dynamic nodes under it: the CSCI-110-M01 level, and then the level with the UIDs. So in your onDataChange you'll need two nested loops to iterate over both levels.
I'd also recommend iterating over the getChildren() of the snapshot, and only getting the values out of the snapshot at the lowest level.
Combined, that becomes:
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String UID = user.getUid();
for (DataSnapshot courseSnapshot: snapshot.getChildren()) {
for (DataSnapshot userSnapshot: courseSnapshot.getChildren()) {
if (UID.equals(userSnapshot.getKey())) {
arrayListGroup.add("Class" + userSnapshot.getValue(String.class));
}
}
}
}
...
I currently encounter an issue that everything returns to the same list. I know it is because I add everything into the same array. But how to add them to specific location like the one in my firebase.
public class GroupAdp extends RecyclerView.Adapter<GroupAdp.ViewHolder> {
//Initialize activities and array list
private Activity activity;
ArrayList<String> arrayListGroup;
MemberAdp adapterMember;
//Create constructor
GroupAdp(Activity activity,ArrayList<String> arrayListGroup){
this.activity = activity;
this.arrayListGroup = arrayListGroup;
// notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row_group,parent,false);
return new GroupAdp.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set group name on TextView
holder.tvName.setText(arrayListGroup.get(position));
//Initialize member ArrayList
ArrayList<String> arrayListMember = new ArrayList<>();
//Using for loop to add multiple members
// for (int i=1; i<=6; i++){
// arrayListMember.add("Member " + i);
// }
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Course_ID_Section");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String UID = user.getUid();
for (DataSnapshot courseSnapshot: snapshot.getChildren()) {
for (DataSnapshot userSnapshot: courseSnapshot.getChildren()) {
// arrayListMember.add(userSnapshot.getValue(String.class));
if(UID.equals(userSnapshot.getKey())) {
arrayListMember.add(userSnapshot.getValue(String.class));
}
}
}
adapterMember.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//Initialize member adapter
adapterMember = new MemberAdp(arrayListMember);
//Initialize layout manager
LinearLayoutManager layoutManagerMember = new LinearLayoutManager(activity);
//Set layout manager
holder.rvMember.setLayoutManager(layoutManagerMember);
//Set adapter
holder.rvMember.setAdapter(adapterMember);
}
#Override
public int getItemCount() {
return arrayListGroup.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
TextView tvName;
RecyclerView rvMember;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
tvName = itemView.findViewById(R.id.tv_name);
rvMember = itemView.findViewById(R.id.rv_member);
}
}
}
public class HealthAlertActivity2 extends Fragment {
//Initialize variable
RecyclerView rvGroup;
ArrayList<String> arrayListGroup;
LinearLayoutManager layoutManagerGroup;
GroupAdp adapterGroup;
//#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View healthAlertFragment = inflater.inflate(R.layout.healthalert_activity2, container, false);
//Assign variable
rvGroup = healthAlertFragment.findViewById(R.id.rv_group);
//Using for loop to add multiple group
//Used for dummy display for now
// for (int i= 1; i<=6; i++){
// arrayListGroup.add("Group " + i);
// }
ArrayList<String> arrayListGroup = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Course_ID_Section");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String UID = user.getUid();
Map<String, Object> map = (Map<String, Object>) snapshot.getValue();
Log.e("LOG_TAG", "Value:" + map);
assert map != null;
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.e("The Result", entry.getKey());
arrayListGroup.add(entry.getKey());
}
adapterGroup.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e("LOG_TAG", "Failed to read value.", error.toException());
}
});
//Initialize group adapter
adapterGroup = new GroupAdp(getActivity(), arrayListGroup);
//Initialize layout manager
layoutManagerGroup = new LinearLayoutManager(getActivity());
//Set layout manager
rvGroup.setLayoutManager(layoutManagerGroup);
//Set adapter
rvGroup.setAdapter(adapterGroup);
return healthAlertFragment;
}
}
public class MemberAdp extends RecyclerView.Adapter<MemberAdp.ViewHolder> {
//Initialize ArrayList
ArrayList<String> arrayListMember;
//Create constructor
public MemberAdp(ArrayList<String> arrayListMember) {
this.arrayListMember = arrayListMember;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Initialize view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row_member,parent,false);
return new MemberAdp.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set member name on TextView
holder.tvName.setText(arrayListMember.get(position));
}
#Override
public int getItemCount() {
return arrayListMember.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
TextView tvName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
tvName = itemView.findViewById(R.id.tv_name);
}
}
}
Ideally, I want to return all students who have the same class as the user in the firebase and return them to different list based on how they are stored in firebase.
The thing is that you subscribe to the root of your data Course_ID_Section, so you get all the data in the same way without respect to its Courses ids. There are a few ways how to handle it, but in your case, I would recommend the following:
Store students not in the same array arrayListMember, but in Hashtable (or another associative array implementation), or in a new Course class. Then, fill in your new data structure when you are looping through courses in your line arrayListMember.add(userSnapshot.getValue(String.class)), because at this point you have a data about a student, and courseSnapshot to get the name of a course
I Am working on project where users recognizes text(OCR) and then see all their text(OCR) history in another activity
App Link : https://play.google.com/store/apps/details?id=com.thetechroot.vision
I added shared preference and recycle view,
but i am only getting the first Text that was recognized
Working :-
Users Recognize Text(OCR) in Textactivity, then to view users history of scanned text(OCR) the history is shown in different activity
How Can I Saved Textview From One Activity to diff activity, and show it into recycleview using shared preference
TEXTACTIVTY.JAVA
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(final FirebaseVisionText firebaseVisionText) {
translatelan(firebaseVisionText);
cd_text_re.setVisibility(View.VISIBLE);
spinnerlan.setVisibility(View.VISIBLE);
txtrecog.setText(firebaseVisionText.getText());
String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,firebaseVisionText.getText());
//int i = SharedCommon.getPreferencesInt(getApplicationContext(), key1,50);
final SharedCommon scth = new SharedCommon();
if (txtrecog.equals("")){
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
scth.putSharedPreferencesString(getApplicationContext(), SharedCommon.texthistory, th);
}
/* SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", String.valueOf(txtrecog.getText()));
editor.putInt("idName", 1);
editor.apply();*/
drawtextvision(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> values;
ArrayList personNames;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public TextView txtFooter;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
}
public MyAdapter(Context context, ArrayList personNames) {
this.context = context;
this.personNames = personNames;
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
/*final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
*/
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.layout_history_text, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
holder.txtFooter.setText("Footer: " + name);
}
});
//holder.txtFooter.setText("Footer: " + name);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
HISTORYACTIVITY.JAVA
public class AboutActivity extends AppCompatActivity {
/* WebView webView;*/
ProgressDialog mprogreeinternet;
String apppackagename = "com.thetechroot.vision";
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;
String appid = BuildConfig.APPLICATION_ID;
Button btnlimit;
WebView webview;
/* private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;*/
private RecyclerView recyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
LinearLayout layouthide,layoutcredit;
int[] photos={R.drawable.logoam, R.drawable.iconshandwrit52,R.drawable.productsearch52,R.drawable.iconsqrcode52};
ImageButton arrdown,arrup,arrcre,arrcreup;
TextView txthistory;
TextView mItemDescription;
ImageButton mDescriptionImg,mupImg;
CardView cdhistory;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
/* btnlimit = (Button) findViewById(R.id.btnlimit);*/
final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
// Toast.makeText(this, ""+th, Toast.LENGTH_SHORT).show();
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// Use the default animator
// recyclerView.setItemAnimator(new DefaultItemAnimator());
// you could add item decorators
// RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
// recyclerView.addItemDecoration(itemDecoration);
ArrayList<String> values = new ArrayList<String>();
/*for (int i = 0; i < 100; i++) {
values.add("Test" + i);
}*/
Toast.makeText(this, ""+String.valueOf(th), Toast.LENGTH_SHORT).show();
values.add(""+String.valueOf(th));
// specify an adapter (see also next example)
mAdapter = new MyAdapter(values);
recyclerView.setAdapter(mAdapter);
ItemTouchHelper.SimpleCallback simpleItemTouchCallback =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder
target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
// input.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startIntent = new Intent(AboutActivity.this, TextActivity.class);
startActivity(startIntent);
finish();
}
}
It's a position issue, you have to use setTag() and getTag(), check this
final String name = values.get(position);
**holder.txtFooter.setTag(name);**
holder.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
**holder.txtFooter.setText("Footer: " + v.getTag());**
}
});
Here TEXTACTIVTY.JAVA you are using single string, so instead of appending it to previous strings in shared preference you are replacing the history. Ideally you should save Strings array and retrieve the same. Currently values have size one because it has only one string.
First use Sting Array. To save String Array in shared preferences do the following
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
Refer Put and get String array from shared preferences
And https://blog.fossasia.org/storing-a-data-list-in-phimpme-android/ for more.
I just started learning android studio for about a month. Sorry if I have posted this in wrong format or asked the wrong question. I have a GridView at my OverviewPage which has a custom adapter that extends ArrayAdapter. I have a GridItem class that contains the objects that I wish to display in the each grid. What I would like to do is to update my GridView to have a new grid every time a new child is created in the Databse.
This is my GridItem class.
package com.example.android.testlogin;
import java.io.Serializable;
public class GridItem implements Serializable {
int mImageView;
String mTitleHere;
String mPriceHere;
public GridItem(int ImageView, String titleHere, String priceHere) {
mImageView = ImageView;
mTitleHere = titleHere;
mPriceHere = priceHere;
}
public int getmImageView() {
return mImageView;
}
public void setmImageView(int ImageView) {
mImageView = ImageView;
}
public String getmTitleHere() {
return mTitleHere;
}
public void setmTitleHere(String TitleHere) {
mTitleHere = TitleHere;
}
public String getmPriceHere() {
return mPriceHere;
}
public void setmPriceHere(String PriceHere) {
mPriceHere = PriceHere;
}
}
This is my custom Adapter.
package com.example.android.testlogin;
public class GridAdapter extends ArrayAdapter<GridItem> {
public GridAdapter(Activity context, ArrayList<GridItem> packageName){
super(context ,0, packageName);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false);
}
GridItem currentItem = getItem(position);
ImageView putPic = (ImageView) listItemView.findViewById(R.id.imageHere);
TextView putTitle = (TextView) listItemView.findViewById(R.id.titleHere);
TextView putPrice = (TextView)listItemView.findViewById(R.id.per_price);
//Set Text for TextView and ImageResources for ImageView.
putPic.setImageResource(currentItem.getmImageView());
putTitle.setText(String.valueOf(currentItem.getmTitleHere()));
putPrice.setText(String.valueOf("$: " + currentItem.getmPriceHere()));
// Return the whole list item layout (containing 2 TextViews and an ImageView)
// so that it can be shown in the ListView
return listItemView;
}
}
This is my OverviewPage which acts as the main page when user login. Users should be able to see all the grid created.
package com.example.android.testlogin;
public class OverviewPage extends AppCompatActivity {
private GridView lvPackage;
private GridAdapter adapter;
private FirebaseAuth mAuth1;
private FirebaseAuth.AuthStateListener mAuthListener1;
private DatabaseReference mDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview_page);
lvPackage = (GridView) findViewById(R.id.grid);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("comPostsCopy");
mAuth1 = FirebaseAuth.getInstance();
mAuthListener1 = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(OverviewPage.this , MainActivity.class));
}
}
};
//Add sample data for grid;
final ArrayList<GridItem> elements = new ArrayList<GridItem>();
elements.add(new GridItem(R.mipmap.ic_launcher_round, "Hello there", "120"));
elements.add(new GridItem(R.mipmap.ic_launcher_round, "Bare Bears", "50"));
elements.add(new GridItem(R.mipmap.ic_launcher_round, "Not Fun", "50"));
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Loop Through Children
for(DataSnapshot ds : dataSnapshot.getChildren());
*//Read Data from Firebase Database and get required data to be shown on new grid.*
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Initialize Adapter
adapter = new GridAdapter(this, elements );
lvPackage.setAdapter(adapter);
lvPackage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something
Toast.makeText(OverviewPage.this, "Not yet", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth1.addAuthStateListener(mAuthListener1);
}
}
This is my Firebase Database
Firebase Database
I would only like to get for example the child key "title" and "pricePerGuest" shown on my new grid.
I know I would have to loop through each child in my comPostsCopy child. However, I have no idea how to get some paticular data from the added child in the addValueEventListener method.
I'm trying to load thumbnail images in a ImageView contained in a RecyclerAdapter Picasso.with(context).load(stringUrl).into(imageView); but this requires a Context. From the RecyclerAdapter is it possible to get the Context of my app's MainActivity? Do I want to do this, or should I be loading the image elsewhere?
These are my classes. The RecyclerAdapater doesn't compile, of course, but it represents what I'm trying to do.
MainActivity:
public class MainActivity extends AppCompatActivity implements MainScreenContract.View {
ArrayList<String> list;
// Objects for RecyclerView
private RecyclerView recyclerView;
private RecyclerView.Adapter recyclerAdapter;
private RecyclerView.LayoutManager recyclerLayoutManager;
#Inject
MainScreenPresenter mainPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timber.plant(new Timber.DebugTree() {
// Add the line number to the tag
#Override
protected String createStackElementTag(StackTraceElement element) {
return super.createStackElementTag(element) + ':' + element.getLineNumber();
}
});
// RecyclerView implementation
recyclerView = (RecyclerView) findViewById(R.id.my_list);
// set to true because all images will be the same size
recyclerView.setHasFixedSize(true);
recyclerLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerLayoutManager);
DaggerMainScreenComponent.builder()
.netComponent(((App) getApplicationContext()).getNetComponent())
.mainScreenModule(new MainScreenModule(this))
.build().inject(this);
//Call the method in MainPresenter to make Network Request
mainPresenter.loadVideo();
}
#Override
public void showVideos(Video video){
// Loop through the posts, get the title of the post, and add it to our list object
// TODO: Simplify these references with a variable?
for(int i = 0; i < video.getResults().size(); i++){
// TODO: add second for loop, or simplyfy and get rid of Video object
list.add(video.getResults().get(i).getSiteDetailUrl());
//list.add(video.get(i).getSiteDetailUrl());
Timber.d("List item " + i + " = " + list.get(i));
}
// RecyclerView implementation
recyclerAdapter = new MainScreenRecyclerAdapter(list);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public void showError(String message){
// Show error message text as a Toast message
Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_SHORT).show();
Timber.e("Error: " + message);
}
#Override
public void showComplete(){
// Show completed Toast message
Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_SHORT).show();
}
}
RecyclerAdapter:
public class MainScreenRecyclerAdapter extends RecyclerView.Adapter<MainScreenRecyclerAdapter.ViewHolder> {
private List<String> dataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(ImageView v) {
super(v);
imageView = v;
}
}
// TODO: Should I make the list contain Video/Result objects and pull the data from that?
public MainScreenRecyclerAdapter(List<String> dataset) {
dataset = dataset;
}
// Create new views
#Override
public MainScreenRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
ImageView v = (ImageView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.thumbnail_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from dataset at this position
// - replace the contents of hte view with that element
// TODO: Call to picasso to load image into holder.imageView
String imageUrl = dataset.get(position);
Timber.d("Image URL: " + imageUrl);
ImageView view = holder.imageView;
Picasso.with(MainActivity.context).load(imageUrl).into(view);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return dataset.size();
}
}
Thanks!
you need to pass the context as a constructor argument and then use this context
private Context mContext;
public MainScreenRecyclerAdapter (Context context) {
mContext = context;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String imageUrl = dataset.get(position);
Timber.d("Image URL: " + imageUrl);
ImageView view = holder.imageView;
Picasso.with(MainActivity.context).load(imageUrl).into(view);
}