How do I set text on spinner (get input from firebase)? - firebase

I want to set text on spinner by user input by using DatabaseReference, but I'm lost with all the guides I read on here
Here is my code
public class EditFragment extends Fragment {
TextInputEditText etusername, etname, etage, height, weight, phone;
Spinner gender;
Button confirm;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getInstance().getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_edit, container, false);
etusername = view.findViewById(R.id.userName);
etname = view.findViewById(R.id.name);
etage = view.findViewById(R.id.age);
height = view.findViewById(R.id.height);
weight = view.findViewById(R.id.etweight);
phone = view.findViewById(R.id.phone);
confirm = view.findViewById(R.id.confirmBtn);
Spinner dropdown = view.findViewById(R.id.gender);
String[] items = new String[]{"Male", "Female"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
DatabaseReference dbuser = FirebaseDatabase
.getInstance()
.getReference("User").child(firebaseAuth.getUid());
dbuser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
etusername.setText(userProfile.getUsername());
etname.setText(userProfile.getName());
etage.setText(userProfile.getAge() + "");
phone.setText(userProfile.getPhoneNumber());
weight.setText((int) userProfile.getWeight() + "");
height.setText((int) userProfile.getHeight() + "");
**--> dropdown.setSelection**
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.w("TAG", "Failed to read value.", error.toException());
}
});
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (etusername.getText().toString().isEmpty() || etname.getText().toString().isEmpty() ||
etage.getText().toString().isEmpty() || phone.getText().toString().isEmpty()) {
Toast.makeText(requireContext(), "Please fill in the text fields", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(requireContext(), "Saved successfully", Toast.LENGTH_SHORT).show();
String username = etusername.getText().toString();
String name = etname.getText().toString();
int age = Integer.parseInt(etage.getText().toString());
double high = Double.parseDouble(Objects.requireNonNull(height.getText()).toString());
double wigh = Double.parseDouble(Objects.requireNonNull(weight.getText()).toString());
String nump = phone.getText().toString();
String gender = dropdown.getSelectedItem().toString();
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("username", username);
userMap.put("name", name);
userMap.put("age", age);
userMap.put("height", high);
userMap.put("weight", wigh);
userMap.put("phoneNumber", nump);
userMap.put("gender", gender);
root.child("User").child(Objects.requireNonNull(firebaseAuth.getUid())).updateChildren(userMap);
Navigation.findNavController(view).navigate(R.id.DestInfo);
}
}
});
return view;
}
}
I don't know how to make it work for dropdown to be set from user input, is there anything I can simply do? or do I need to do the for loop? but how do I get the UserProfile.getGender index? I'm sorry I'm kinda new to this android studio, but I'm trying to learn

Related

go back to previous fragment from another fragment that was started from recyclerview adapter (xamarin.android)

so I have an application that is as follows:
login page where the user enters his credentials and can access the main app if his credentials are correct. and if he checks the remember me checkbox, his username and password will be saved in shared preferences so that he can directly go to the main app in the second time.
the main app has a tabbed layout with a viewpager. in one of the tabs, which is a fragment, I use a recyclerview to display data, that I get from a database, in rows.
now in each row there is a reply button that will show details corresponding to each row when clicked. the details will be shown in a new fragment.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter:
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
List <summary_request> summary_Requests=new List<summary_request>();
//Context context;
public readonly stores_fragment context;
public recyclerviewAdapter(stores_fragment context, List<summary_request> sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.by_user.Text = summary_Requests[position].By;
vh.warehousename.Text = summary_Requests[position].warehousename;
vh.project.Text = summary_Requests[position].project;
vh.operations_note.Text = summary_Requests[position].destination_Note;
vh.source_Note.Text = summary_Requests[position].source_Note;
vh.stockType.Text = summary_Requests[position].stockType;
vh.requestStatus.Text = summary_Requests[position].requestStatus;
vh.reply.Click += delegate
{
summary_detail_req fragment = new summary_detail_req();
var fm = context.FragmentManager.BeginTransaction();
fm.Replace(Resource.Id.frameLayout1, fragment);
fm.AddToBackStack(null);
fm.Commit();
int nb = context.FragmentManager.BackStackEntryCount;
Toast.MakeText(context.Context, nb.ToString(), ToastLength.Long).Show();
};
}
private void Reply_Click(object sender, EventArgs e)
{
Toast.MakeText(context.Context, "reply" , ToastLength.Long).Show();
}
public override int ItemCount
{
get { return summary_Requests.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
}
but my context.FragmentManager.BackStackEntryCount remain zero! I don't get it. in my main activity, I am using this code for the backpress function:
stores_fragment.recyclerviewAdapter adapter;
public override void OnBackPressed()
{
string userName = pref.GetString("Username", String.Empty);
string password = pref.GetString("Password", String.Empty);
if (userName != String.Empty || password != String.Empty && adapter.context.FragmentManager.BackStackEntryCount == 0)
{
this.FinishAffinity();
}
else
base.OnBackPressed();
}
but i'm not getting what i want. this function is getting me out of the whole app.the first part of the if statement is because without it, when the I press the back button from the main activity it takes me back to the login page and I don't want that.
my question is what should I do to manage my fragments and the backpress function?
thanks in advance.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter
According to your description, you want to open another fragment from recyclerview Button.click, if yes, please take a look the following code:
on OnBindViewHolder
int selectedindex;
// Fill in the contents of the photo card (invoked by the layout manager):
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
selectedindex =position;
PhotoViewHolder vh = holder as PhotoViewHolder;
// Set the ImageView and TextView in this ViewHolder's CardView
// from this position in the photo album:
vh.Image.SetImageResource(mPhotoAlbum[position].PhotoID);
vh.Caption.Text = mPhotoAlbum[position].Caption;
vh.btnreply.Click += Btnreply_Click;
}
To show detailed activity. MainActivity is the current activity for recyclerview.
private void Btnreply_Click(object sender, EventArgs e)
{
Showdetailed(selectedindex);
}
private void Showdetailed(int position)
{
var intent = new Intent();
intent.SetClass(MainActivity.mac, typeof(DetailsActivity));
intent.PutExtra("selectedid", position);
MainActivity.mac.StartActivity(intent);
}
The detailedactivity.cs:
public class DetailsActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
var index = Intent.Extras.GetInt("selectedid", 0);
var details = DetailsFragment.NewInstance(index); // Details
var fragmentTransaction = FragmentManager.BeginTransaction();
fragmentTransaction.Add(Android.Resource.Id.Content, details);
fragmentTransaction.Commit();
}
}
The DetailsFragment.cs:
public class DetailsFragment : Fragment
{
public int ShownPlayId => Arguments.GetInt("selectedid", 0);
public static DetailsFragment NewInstance(int index)
{
var detailsFrag = new DetailsFragment { Arguments = new Bundle() };
detailsFrag.Arguments.PutInt("selectedid", index);
return detailsFrag;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
if (container == null)
{
// Currently in a layout without a container, so no reason to create our view.
return null;
}
var scroller = new ScrollView(Activity);
var text = new TextView(Activity);
var padding = Convert.ToInt32(TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, Activity.Resources.DisplayMetrics));
text.SetPadding(padding, padding, padding, padding);
text.TextSize = 24;
Photo photo =PhotoAlbum.mBuiltInPhotos[ShownPlayId];
text.Text = photo.Caption;
scroller.AddView(text);
return scroller;
}
}
About implementing fragment, you can take a look:
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/fragmentswalkthrough/

Firebase Cannot resolve method 'getEditText' in 'EditText'

I was trying to make a app where you can store information into the Firebase Real Time Database. But when I watched a tutorial there was a error whit mine.
public class CreateActivity extends AppCompatActivity {
Button btnTerug, btnGo;
EditText codeIdt, codeItt;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
btnTerug = (Button) findViewById(R.id.btnTerug);
codeIdt = findViewById(R.id.codeId);
codeItt = findViewById(R.id.codeIt);
btnGo = (Button) findViewById(R.id.btnGo);
//Save data in Database
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Bungalows");
//Get all the values
String codeId = codeIdt.getEditText().getText().toString();
String codeIt = codeItt.getEditText().getText().toString();
DataSaver helperClass = new DataSaver(codeId,codeIt);
reference.setValue(helperClass);
}
});
Both the .getEditText() gives a error: Cannot resolve method 'getEditText' in 'EditText'
Does someone know what I am doing wrong?
Try this!
String codeId = codeIdt.getText().toString();
String codeIt = codeItt.getText().toString();

Nested FirestoreRecyclerAdapter Shows Nothing

I'm trying to achieve an Instagram style comment section. I have a collection group query /comments and can display comments just fine with RecyclerView.
Inside of the parent FirestoreRecyclerAdapter onBindViewHolder I have this.
DocumentSnapshot snapshot = getSnapshots().getSnapshot(holder.getAdapterPosition());
String commentId = snapshot.getId();
System.out.println("[CommentID: ]" + commentId);
Query rQuery = mFirestore.collectionGroup("comments")
.whereEqualTo("postId", commentId)
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<SubCommentModel> options = new FirestoreRecyclerOptions.Builder<SubCommentModel>()
.setQuery(rQuery, SubCommentModel.class).build();
RecyclerView replyRecycler = holder.reply_recycler;
rAdapter = new FirestoreRecyclerAdapter<SubCommentModel, ReplyTypeViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ReplyTypeViewHolder holder, int position, #NonNull SubCommentModel model) {
final SimpleDateFormat FORMAT = new SimpleDateFormat(
"MM/dd/yyyy", Locale.US);
((ReplyTypeViewHolder) holder).author_name.setText(model.getAuthor());
((ReplyTypeViewHolder) holder).comment_text.setText(model.getComment());
((ReplyTypeViewHolder) holder).time_stamp.setText(FORMAT.format(model.getTimestamp()));
}
#NonNull
#Override
public ReplyTypeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item, parent, false);
return new ReplyTypeViewHolder(view);
}
Outside of this block, I set replyRecycler to the nested adapter; I set up Linear Layout Manager and start listening.
However this does nothing. In fact doing addSnapShotLinstener to cQuery returns nothing. No error and no data.

Android viewPager onPageSelected can't get correct database id with respect to viewPager position

I have created the module for loading database record with id=1,2,3,4,5,... by getting the position of the viewPage Swiped as position index +1 . It has been implemented in OnPageChangeListener onPageSelected method. When it comes to the testing, it shows that the index shows zero at the beginning as 0,2,3,4 instead of index 1,2,3,4 ..to load the record. When I swipe right , it loads another same record instead of none, even setting setOffscreenPageLimit as zero. I don't want this to happen
Would you please tell me the alternative to read the position of the viewPager page ?
The below is my working :
mViewPager = (CustomViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setEnabled(true);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setOnPageChangeListener(viewPagerPageChangeListener);
mViewPager.setCurrentItem(0);
OnPageChangeListener viewPagerPageChangeListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
pageId = position + 1;
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
final Animation animationFadeIn = AnimationUtils.loadAnimation(FlightBankActivity.this, R.anim.fade_in);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageResource(R.drawable.dot_e);
}
dots[position].setAnimation(animationFadeIn);
dots[position].setImageResource(R.drawable.dot_s);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
ArrayList<FlightProfile> fpList = (ArrayList<FlightProfile>) DatabaseManager.getInstance().getAllFlightProfile();
System.out.println(fpList.size() + " : is the size of profile");
for(FlightProfile gfg : fpList){
System.out.println(gfg.getId()+ " is the profile id");
System.out.println(gfg.getName()+ " is the profile i]name");
}
System.out.println(pageId+ " : is the pageId");
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
Fragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle=getArguments();
final int type = bundle.getInt("type");
System.out.println("type :" + type);
fp = DatabaseManager.getInstance().getFlightProfile(pageId);
...

Android - How can add horizontal swipe gesture in vertical scroll view like pulse app has screen view

I am newbie to android please help me, is their any possibility to add swipe action in vertical scroll view of activity screen.I am trying hard, but not getting...
I just converted vertical scroll view to Listview, Its works like a charm... Thanks to omid nazifi and wwyt, for more u can see this link Gesture in listview android
public class MainActivity extends ListActivity {
private OnTouchListener gestureListener;
private GestureDetector gestureDetector;
private int REL_SWIPE_MIN_DISTANCE;
private int REL_SWIPE_MAX_OFF_PATH;
private int REL_SWIPE_THRESHOLD_VELOCITY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// As paiego pointed out, it's better to use density-aware measurements.
DisplayMetrics dm = getResources().getDisplayMetrics();
REL_SWIPE_MIN_DISTANCE = (int)(1.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_MAX_OFF_PATH = (int)(250.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_THRESHOLD_VELOCITY = (int)(200.0f * dm.densityDpi / 160.0f + 0.5);
ListView lv = getListView();
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
m_Starbucks));
final GestureDetector gestureDetector = new GestureDetector(new MyGestureDetector());
View.OnTouchListener gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}};
lv.setOnTouchListener(gestureListener);
// Long-click still works in the usual way.
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String str = MessageFormat.format("Item long clicked = {0,number}", position);
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
return true;
}
});
/*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String str = MessageFormat.format("Item #extra clicked = {0,number}", position);
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
});*/
}
// Do not use LitView.setOnItemClickListener(). Instead, I override
// SimpleOnGestureListener.onSingleTapUp() method, and it will call to this method when
// it detects a tap-up event.
private void myOnItemClick(int position, View v) {
String str = MessageFormat.format("Item clicked = {0,number}", position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
private void onLTRFling() {
Toast.makeText(this, "Left-to-right fling", Toast.LENGTH_SHORT).show();
}
private void onRTLFling() {
Toast.makeText(this, "Right-to-left fling", Toast.LENGTH_SHORT).show();
}
class MyGestureDetector extends SimpleOnGestureListener{
// Detect a single-click and call my own handler.
#Override
public boolean onSingleTapUp(MotionEvent e) {
View lv = (View)getListView();
int pos = ((AbsListView) lv).pointToPosition((int)e.getX(), (int)e.getY());
myOnItemClick(pos,lv);
return false;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)
return false;
if(e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
onRTLFling();
} else if (e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
onLTRFling();
}
return false;
}
}
private static final String[] m_Starbucks = {
"Latte", "Cappuccino", "Caramel Macchiato", "Americano", "Mocha", "White Mocha",
"Mocha Valencia", "Cinnamon Spice Mocha", "Toffee Nut Latte", "Espresso",
"Espresso Macchiato", "Espresso Con Panna"
};
}

Resources