How to get data from RecyclerView item position - firebase

Good evening. I'm stuck on this problem. I'm populating a RecyclerView with data from Firebase Realtime Database. This part is ok, it's work well. My doubt is how I get the firebase id from the user on the click event. As the id not shows in the layout, I have no ideia how I can work with this data. Here the class:
Adapter
public class TecnicosAdapter extends RecyclerView.Adapter<TecnicosViewHolders>{
private List<TecnicosObject> tecnicosList;
private Context context;
public TecnicosAdapter (List<TecnicosObject> tecnicosList, Context context){
this.tecnicosList = tecnicosList;
this.context = context;
}
#NonNull
#Override
public TecnicosViewHolders onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tecnicos, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
TecnicosViewHolders rcv = new TecnicosViewHolders((layoutView));
return rcv;
}
#Override
public void onBindViewHolder(#NonNull TecnicosViewHolders holder, int position) {
// holder.mTecnicoId.setText(tecnicosList.get(position).getUsuarioId());
holder.mTecnicoNome.setText(tecnicosList.get(position).getNome());
holder.mTecnicoProfissao.setText(tecnicosList.get(position).getProfissao());
if (!tecnicosList.get(position).getImagemPerfilUrl().equals("default")){
Glide.with(context).load(tecnicosList.get(position).getImagemPerfilUrl()).into(holder.mTecnicoImagem);
}
}
public TecnicosObject getItem(int position){
return tecnicosList.get(position);
}
#Override
public int getItemCount() {
return this.tecnicosList.size();
}
}
Model
public class TecnicosObject {
private String usuarioId;
private String nome;
private String profissao;
private String imagemPerfilUrl;
public TecnicosObject(String usuarioId, String nome, String profissao, String imagemPerfilUrl) {
this.usuarioId = usuarioId;
this.nome = nome;
this.profissao = profissao;
this.imagemPerfilUrl = imagemPerfilUrl;
}
public String getUsuarioId() {
return usuarioId;
}
public void setUsuarioId(String usuarioId) {
this.usuarioId = usuarioId;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getImagemPerfilUrl() {
return imagemPerfilUrl;
}
public void setImagemPerfilUrl(String imagemPerfilUrl) {
this.imagemPerfilUrl = imagemPerfilUrl;
}
}
ViewHolder
public class TecnicosViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTecnicoNome, mTecnicoProfissao;
public ImageView mTecnicoImagem;
private Context context;
String clienteId;
private Bundle extras;
public TecnicosViewHolders(View itemView) {
super(itemView);
this.context = context;
mTecnicoNome = (TextView) itemView.findViewById(R.id.TecnicoNome);
mTecnicoProfissao = (TextView) itemView.findViewById(R.id.TecnicoProfissao);
mTecnicoImagem = (ImageView) itemView.findViewById(R.id.TecnicoImagem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos!=RecyclerView.NO_POSITION){
}
}
}
Main Activity
public class TelaTecnicos extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mTecnicosAdapter;
private RecyclerView.LayoutManager mTecnicosLayoutManager;
private String usuarioAtualID;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tela_tecnicos);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
usuarioAtualID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(true);
mTecnicosLayoutManager = new LinearLayoutManager(TelaTecnicos.this);
mRecyclerView.setLayoutManager(mTecnicosLayoutManager);
mTecnicosAdapter = new TecnicosAdapter(getDataSetTecnicos(), TelaTecnicos.this);
mRecyclerView.setAdapter(mTecnicosAdapter);
getUsuarioTecnicoId();
}
private void getUsuarioTecnicoId() {
DatabaseReference tecnicoDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Clientes").child(usuarioAtualID).child("conexoes").child("tecnicos");
tecnicoDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot tecnico: dataSnapshot.getChildren()){
FetchtecnicoInformation(tecnico.getKey());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void FetchtecnicoInformation(final String key) {
DatabaseReference usuarioDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Tecnicos").child(key);
usuarioDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String usuarioId = dataSnapshot.getKey();
String nome = "";
String profissao = "";
String imagemPerfilUrl = "";
if (dataSnapshot.child("nome").getValue()!=null){
nome = dataSnapshot.child("nome").getValue().toString();
}
if (dataSnapshot.child("profissao").getValue()!=null){
profissao = dataSnapshot.child("profissao").getValue().toString();
}
if (dataSnapshot.child("imagemPerfilUrl").getValue()!=null){
imagemPerfilUrl = dataSnapshot.child("imagemPerfilUrl").getValue().toString();
}
TecnicosObject obj = new TecnicosObject(usuarioId, nome, profissao, imagemPerfilUrl);
resultmTecnicos.add(obj);
mTecnicosAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private ArrayList<TecnicosObject> resultmTecnicos = new ArrayList<TecnicosObject>();
private List<TecnicosObject> getDataSetTecnicos() {
return resultmTecnicos;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
Someone have a tip? Thanks.

Put this in your ViewHolder onclick() method technicoId = technicolist.get(pos.getId())
The implementation should look like this ->>
`
String technicoId = "";
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos!=RecyclerView.NO_POSITION){
technicoId = technicolist.get(pos).getId();
}
}
`
Edit:
if your view holder is in a separate file it is better you implement viewholder class in the adapter class(that's what I do) so you can easily reference technicolist in viewholder. it will look like this
`
public class TecnicosAdapter extends RecyclerView.Adapter<TecnicosViewHolders>{
private List<TecnicosObject> tecnicosList;
....other methods
class TecnicosViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
//you can use tecnicolist here
#Override
public void onClick(View v){
....
}
}
}
`

Related

Search in Fragments that hold Recyclerview

I have 3 Fragments and they all are holding a recyclerView. But I don't know how I should call adapter.getFilter().filter(newText); in onQueryTextChange. Any ideas?
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
private BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDB = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----Start Bottom Navigation Bar
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new PasswortFragment()).commit();
String id = getResources().getResourceEntryName(bottomNavigationView.getId());
//----End Bottom Navigation Bar
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch(item.getItemId()){
case R.id.passwoerter:
fragment = new PasswortFragment();
break;
case R.id.bankdaten:
fragment = new BankdatenFragment();
break;
case R.id.kreditkarten:
fragment = new KreditkartenFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment f = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.container);
if(f instanceof PasswortFragment)
recyclerView = findViewById(R.id.recyclerViewPasswoerter);
if(f instanceof KreditkartenFragment)
recyclerView = findViewById(R.id.recyclerViewKreditkarten);
if(f instanceof BankdatenFragment)
recyclerView = findViewById(R.id.recyclerViewBankdaten);
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerView.getAdapter().getFilter().filter(newText); //<--This is not working
return false;
}
});
return true;
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable{
String type;
List<String> dataAll, data1;
Context context;
public Adapter(Context ct, List<String> s1, String typ){
context = ct;
data1 = s1;
type = typ;
dataAll = new ArrayList<>(data1);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.reihen, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.mytext1.setText(data1.get(position));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(type.equals("Passwoerter")){
Intent intent = new Intent(context, DetailsP.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Kreditkarten")){
Intent intent = new Intent(context, DetailsK.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Bankdaten")){
Intent intent = new Intent(context, DetailsB.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data1.size();
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(dataAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(String item: dataAll){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data1.clear();
data1.addAll( (List) results.values);
notifyDataSetChanged();
}
};
;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView mytext1;
ConstraintLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.title);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
PasswortFragment (the other two fragments are pretty much the same):
public class PasswortFragment extends Fragment {
public PasswortFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
String tabelle = "Passwort";
List<String> titel;
DatabaseHelper myDB;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_passwort, container, false);
myDB = new DatabaseHelper(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPasswoerter);
titel = Arrays.asList(myDB.getItems(tabelle));
final LinearLayoutManager layoutManager = new LinearLayoutManager((getActivity()));
layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(getActivity(), titel, "Passwoerter");
recyclerView.setAdapter(adapter);
setHasOptionsMenu(true);
return view;
}

Stay login with using PhoneNumber [duplicate]

This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 4 years ago.
After I sign in with PhoneNumber Auth it's will take me into Profile activity, I want that stay log in into the application if I go out and close it from used apps and come back again to the application that I won't be still log in.
the following the Java Code of PhoneNumber Auth and the Profile
VerifyPhoneActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
String phonenumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length()<6){
editText.setError("enter Code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, List.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String phonenumber){
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber,
10,
TimeUnit.SECONDS,
this,
mCallbacks
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null){
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
Child_Profile.Java
public class Child_Profile extends AppCompatActivity {
private TextView name;
private TextView gender;
private TextView birth;
private TextView bload;
private TextView Text_Dates;
private TextView Text_Time;
private Button Button_record;
private TextView Text_record;
private TextView Text_hospial;
private TextView Text_Plan;
private TextView Text_Satus;
private TextView Text_Price;
private ImageView ImageView_choose_image;
private Button button_choose_image;
private Uri mUri;
private static final int GALLERY_INTENT = 1;
private StorageReference mStorage;
private DatabaseReference mData;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_sign_out)
signOut();
return true;
}
private void signOut() {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Child_Profile.this, User.class));
finish();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child__profile);
name = findViewById(R.id.text_view_Namee);
gender = findViewById(R.id.text_view_Gender);
birth = findViewById(R.id.text_view_Birth);
bload = findViewById(R.id.text_view_Blood);
Text_Dates = findViewById(R.id.Text_Dates);
Text_Time = findViewById(R.id.Text_Time);
Text_record = findViewById(R.id.Text_record);
Text_hospial = findViewById(R.id.Text_hospial);
Text_Plan = findViewById(R.id.Text_Plan);
Text_Satus = findViewById(R.id.Text_Satus);
Button_record = findViewById(R.id.Button_record);
Text_Price = findViewById(R.id.Text_Price);
button_choose_image = findViewById(R.id.button_choose_image);
ImageView_choose_image = findViewById(R.id.ImageView_choose_image);
mStorage = FirebaseStorage.getInstance().getReference("Photo");
mData = FirebaseDatabase.getInstance().getReference("Photo");
button_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openFileChooser();
}
});
Intent in = getIntent();
final Bundle b = in.getExtras();
if (b != null) {
String n = (String) b.get("id");
db.collection("Child Profile").document(n).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String pName = documentSnapshot.getString("name");
String pgender = documentSnapshot.getString("gender");
String pbirth = documentSnapshot.getString("birth");
String pbload = documentSnapshot.getString("bload");
String pDates = documentSnapshot.getString("dates");
String pTime = documentSnapshot.getString("time");
String pHospital = documentSnapshot.getString("hospital");
String pPlan = documentSnapshot.getString("typeOfPlan");
String pSatus = documentSnapshot.getString("satus");
String pPrice = documentSnapshot.getString("price");
name.setText(pName);
gender.setText(pgender);
birth.setText(pbirth);
bload.setText(pbload);
Text_Dates.setText(pDates);
Text_Time.setText(pTime);
Text_hospial.setText(pHospital);
Text_Plan.setText(pPlan);
Text_Satus.setText(pSatus);
Text_Price.setText(pPrice);
}
});
}
}
List.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_List);
mAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
FloatingActionButton aaa = findViewById(R.id.button_add_profile);
aaa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), NewChild.class);
startActivity(i);
}
});
}
private void setUpRecyclerView() {
Query query = profileRef.whereEqualTo("user_id", FirebaseAuth.getInstance().getCurrentUser().getUid());
FirestoreRecyclerOptions<addp> options = new FirestoreRecyclerOptions.Builder<addp>()
.setQuery(query, addp.class)
.build();
adapter = new padapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_View);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new padapter.OnItemClickListener()
{
#Override
public void onItemClick (DocumentSnapshot documentSnapshot,int position){
String id = documentSnapshot.getId();
Toast.makeText(Profile.this, "Position: " + position + "ID" + id, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Child_Profile.class);
i.putExtra("id", id);
startActivity(i);
}
});
ProfileActivity set as launcher activity and
add line of code at onCreate of ProfileAtivity
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null){
Intent intent=new Intent(ProfileActivity,this,LoginActivity.class);
startActivity(intent);
finish()
}
else{
//stay here
}`

onClick button in adapter

I have a button in the recyclerview, and I want when I click the button then it will go to the next page. I try like this in my adapter but my app currently force close and in logcat nothing happens..
CustomerAdapter.java
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.CustomerViewHolder> {
ArrayList<Customer> datasSet;
public CustomerAdapter(ArrayList<Customer> tempData) {
this.datasSet = tempData;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_customer_index_row, parent, false);
return new CustomerViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomerAdapter.CustomerViewHolder holder, int position) {
Customer csModel = datasSet.get(position);
holder.name.setText(csModel.getCustNama());
holder.button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i("ratri2", "onClick: sukses ");
Intent intent = new Intent(context, GenerateSpkActivity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return datasSet.size();
}
public class CustomerViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public Button button;
public CustomerViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.customer_name);
button= itemView.findViewById(R.id.btnGenerate);
}
}
}

ViewPager returning empty array

When I start my app I want my customSwipeAdapter.java to wait until my savedImages ArrayList has received and been populated with the data from firebase. But instead my class is being ran and my whole page is empty because getCount() method is returning savedImages.size() as 0 because my arraylist hasn't been populated in time. Any help on maybe running my class when my array list is populated. Not sure what to do here :)
customSwipeAdapter.java
public class customSwipeAdapter extends PagerAdapter {
private Firebase mRef;
private Context ctx;
private LayoutInflater layoutInflator;
public customSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
private int[] frontImages = {R.drawable.amen_parham, R.drawable.janel_parham, R.drawable.kevin_parham};
// Populate ArrayList with firebase data
List<String> savedImages = new ArrayList<String>();
Boolean goingToCallOnce = false;
Boolean finishedLoadingData = false;
#Override
public int getCount() {
return savedImages.size();
}
#Override
public boolean isViewFromObject(View view, Object o) {
return (view == o);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
getSavedImages_FromDB();
layoutInflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view = layoutInflator.inflate(R.layout.swipe_layout, container, false);
final EasyFlipView mYourFlipView = (EasyFlipView) item_view.findViewById(R.id.flipView);
ImageView imageView_Front = (ImageView) item_view.findViewById(R.id.imageView_Front);
imageView_Front.setImageResource(frontImages[position]);
container.addView(item_view);
System.out.println(savedImages);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout)object);
}
public void getSavedImages_FromDB() {
mRef = new Firebase("");
if (goingToCallOnce == false) {
goingToCallOnce = true;
mRef.child("Q6i3fI6lNdYYS0z5Jty4WUYE9g13").child("SavedImages").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String savedImage = (String) dataSnapshot.child("Image").getValue();
savedImages.add(0, savedImage);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
finishedLoadingData = true;
System.out.println("finishedLoadingData");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
savedCardsViewController.java
public class savedCardsViewController extends AppCompatActivity {
private Swipe swipe;
ViewPager viewPager;
customSwipeAdapter adapter;
private Firebase mRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_cards_view_controller);
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new customSwipeAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(false, new DefaultTransformer());
}
}
'Context' to 'ValueEventListener'
2'nd 'Context' to 'ValueEventListener'
I suggest you load the data from Firebase on your Activity first and then pass it as a parameter to the adapter's constructor. This way your CustomSwipeAdapter would look similar to this:
public class customSwipeAdapter extends PagerAdapter {
private Firebase mRef;
private Context ctx;
private LayoutInflater layoutInflator;
List<String> savedImages = new ArrayList<String>();
public customSwipeAdapter(Context ctx, List<String> savedImages){
this.ctx = ctx;
this.savedImages = savedImages
}
...
}
Another note on Loading data from firebase on the Activity: use A SingleValueListener with an iterator instead of onChildAdded:
mRef.child("Q6i3fI6lNdYYS0z5Jty4WUYE9g13").child("SavedImages").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> data = dataSnapshot.getChildren().iterator();
while(data.hasNext())
{
String savedImage = (String) data.next().child("Image").getValue();
savedImages.add(0, savedImage);
}
//Data has finished loading. Load your adapter
adapter = new customSwipeAdapter(this, savedImages);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(false, new DefaultTransformer());
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

Retrieving list of images from Firebase, using GenericTypeIndicator<Map<String, String>>() { }

I need help with this, I've been trying to show a list of images into a recycler view but seriously I can't.
This is my database in firebase, shows the images from different events with randoms ids
This is my class:
public class Imagenes {
GenericTypeIndicator<Map<String,String>> images = new GenericTypeIndicator<Map<String, String>>(){};
public Imagenes(GenericTypeIndicator<Map<String, String>> images) {
this.images = images;
}
public GenericTypeIndicator<Map<String, String>> getImages() {
return images;
}
public void setImages(GenericTypeIndicator<Map<String, String>> images) {
this.images = images;
}
}
And yes its seems very bad but I don't know how to do it, since its not like a normal class with
name
phone
images
I mean i don't know their names, it's just random. I been reading that I have to use this kind of map, but I don't know how to use it in a class
This is my code in EventSingle:
public class EventoSingleActivity extends AppCompatActivity {
DatabaseReference mDatabaseEvento;
TextView TituloEvento;
RecyclerView mListaImagenes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_evento_single);
mListaImagenes = (RecyclerView) findViewById(R.id.listaImagenes);
mListaImagenes.setHasFixedSize(true);
mListaImagenes.setLayoutManager(new LinearLayoutManager(this));
String Evento_key = getIntent().getExtras().getString("Evento_id");
Toast.makeText(this, Evento_key, Toast.LENGTH_SHORT).show();
mDatabaseEvento = FirebaseDatabase.getInstance().getReference().child("Evento").child(Evento_key).child("Imagenes");
System.out.println(mDatabaseEvento);
TituloEvento = (TextView) findViewById(R.id.tituloEventoField);
mDatabaseEvento.keepSynced(true);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Imagenes, ImagenesEventoViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Imagenes, ImagenesEventoViewHolder>(
Imagenes.class,
R.layout.cardview_imagen,
ImagenesEventoViewHolder.class,
mDatabaseEvento
) {
#Override
protected void populateViewHolder(final ImagenesEventoViewHolder viewHolder, Imagenes model, int position) {
mDatabaseEvento.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("Estoy entrando aqui");
Log.i("gguwu", "Ayudaaaa");
GenericTypeIndicator<Map<String,String>> ImagenesType = new GenericTypeIndicator<Map<String, String>>() { };
Map<String,String> Imagenes = dataSnapshot.getValue(ImagenesType);
if (Imagenes!=null ) {
for (String imagen: Imagenes.values()) {
System.out.println(imagen);
viewHolder.setImagen(getApplicationContext(), imagen);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mListaImagenes.setAdapter(firebaseRecyclerAdapter);
}
public static class ImagenesEventoViewHolder extends RecyclerView.ViewHolder{
View view;
public ImagenesEventoViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setImagen(Context ctx, String imagen){
ImageView imagencita = (ImageView) view.findViewById(R.id.imagen_item);
Picasso.with(ctx).load(imagen).into(imagencita);
}
}
}
I don't know how to make this works.
I tried everything, but I just cant. Help me please. Thanks!.
try ChildEventLister class for this task.
mDatabaseEvento =
mDatabaseEvento.addChildEventListener(new ChildEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("Estoy entrando aqui");
Log.i("gguwu", "Ayudaaaa");
GenericTypeIndicator<Map<String,String>> ImagenesType = new GenericTypeIndicator<Map<String, String>>() { };
Map<String,String> Imagenes = dataSnapshot.getValue(ImagenesType);
if (Imagenes!=null ) {
for (String imagen: Imagenes.values()) {
System.out.println(imagen);
viewHolder.setImagen(getApplicationContext(), imagen);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError)
}

Resources