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) {}
});
Related
I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here
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;
}
In my activity i am receiving a game id from previous activity and using this id i am getting list of data from api. The method ("ApiCheats") in activity is used to get lis t of data.
I want to pass this list to my fragment in view pager, for this i used bundle but in fragment the bundle is null.
How should i pass bundle list to fragment , this data i am receiving through retrofit.
This is the Activity
public class GameListCheatsActivity extends AppCompatActivity {
private final String TAG = GameListCheatsActivity.class.getSimpleName();
public List<Cheats> Cheats;
ArrayList cheats = new ArrayList<Cheats>();
// public RecyclerView recyclerView;
String Gameid;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list_cheats);
// recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setHasFixedSize(true);
Gameid = getIntent().getStringExtra("GameID");
tabLayout = (TabLayout) findViewById(R.id.tab_layout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter( getSupportFragmentManager());
ApiCheats();
adapter.AddFragment(new Fragment_Cheats(),"GameCheats");
adapter.AddFragment(new Fragment_Favourites(),"Favourites");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == 0){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
if(state == 1){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
}
});
}
public void ApiCheats()
{
ApiUtil.getServiceClass().getAllCheats(Gameid).enqueue(new Callback<List<Cheats>>() {
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("cheatslist", (ArrayList<? extends Parcelable>) Cheats);
Fragment_Cheats fragment_cheats = new Fragment_Cheats();
fragment_cheats.setArguments(bundle);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
#Override
public void onFailure(Call<List<Cheats>> call, Throwable t) {
Log.d(TAG, "error loading from API");
}
});
}
}
this is one of the fragments class
public class Fragment_Cheats extends Fragment {
View v;
private RecyclerView mrecyclerview;
private List<Cheats> lstGameCheats;
public Fragment_Cheats()
{
}
// #Override
// public void onCreate(#Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// lstGameCheats = bundle.getParcelable("cheatslist");
// }
//
// }
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_fragment__cheats, container, false);
mrecyclerview = (RecyclerView)v.findViewById(R.id.recyclerview_cheats);
Bundle bundle = this.getArguments();
if (bundle != null) {
lstGameCheats = bundle.getParcelable("cheatslist");
}
CheatsAdapter recyclerAdapter = new CheatsAdapter(getContext(),lstGameCheats);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerview.setAdapter(recyclerAdapter);
return v;
}
}
this is view pager adapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
//return null;
}
#Override
public int getCount() {
return lstTitles.size();
//return 0;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment,String title){
lstFragment.add(fragment);
lstTitles.add(title);
}
}
You should set the Cheats to the Fragment which have added to your ViewPagerAdater, but according to your code you just set the data to a new fragment instance.
According to the Fragment_Cheats code, if you want to invoke getArgument() in onCreate() method, you should invoke fragment.setArgument() before the fragment add to the ViewPagerAdapter.
But in your situation it is not possible, because the data get from the network.
So, two step
Set data to the correct Fragment_Cheats instance
Notify Fragment_Cheats data changed, refresh the View state in the fragment
Replace your onResponse()
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Fragment_Cheats fragment_cheats = adapter.getCheatFragment()
fragment_cheats.setDatas(Cheats);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
Fragment_Cheats add setDatas() method
public void setDatas(List<Cheats> datas) {
this.lstGameCheats = datas;
// and set the datas to the RecylerView adapter
recyclerviewAdapter.notifyDataSetChanged();
}
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){
....
}
}
}
`
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)
}