Stay login with using PhoneNumber [duplicate] - firebase

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
}`

Related

Using FirestoreRecyclerAdapter but phone's screen looks separately

I'm using FirestoreRecyclerAdapter and faced with the problem.
My challenge is that I can add documents and retrieve them the recyclerview but for some reason, thw phone's screen looks separately as attached phone's schreenshot.
how can I do?
Thank You.
This is Adapter;
public MyFriendsAdapter(#NonNull FirestoreRecyclerOptions<ProfileModelClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyFriendsViewholder holder, int position, #NonNull ProfileModelClass model)
{
holder.myNickname.setText(model.getNickname());
holder.myAge.setText(model.getAge());
holder.myGender.setText(model.getGender());
holder.myDistance.setText(model.getDistance());
holder.myUserDescription.setText(model.getUserDescription());
holder.myMarriage.setText(model.getMarriage());
holder.myAddress.setText(model.getAddress());
// String visit_user_id = getSnapshots().getSnapshot(position).getId();
// Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
// chatIntent.putExtra("visit_user_id", visit_user_id);
// startActivity(chatIntent);
Glide.with(holder.myProfileImageView.getContext()).load(model.getProfileImage()).into(holder.myProfileImageView);
Glide.with(holder.myPictureOne.getContext()).load(model.getPictureOne()).into(holder.myPictureOne);
Glide.with(holder.myPictureTwo.getContext()).load(model.getPictureTwo()).into(holder.myPictureTwo);
}
#NonNull
#Override
public MyFriendsViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_friends_list_layout,
parent, false);
return new MyFriendsViewholder(view);
}
class MyFriendsViewholder extends RecyclerView.ViewHolder
{
CircleImageView myProfileImageView;
TextView myNickname,myAge, myGender, myDistance, myUserDescription, myMarriage, myAddress,
myFriendsProfile, SendMessageButton;
ImageView myPictureOne, myPictureTwo;
public MyFriendsViewholder(#NonNull View itemView)
{
super(itemView);
myProfileImageView = itemView.findViewById(R.id.all_friends_profile_image_layout);
myNickname = itemView.findViewById(R.id.all_friends_nickname_layout);
myGender = itemView.findViewById(R.id.all_friends_gender_layout);
myAge = itemView.findViewById(R.id.all_friends_age_layout);
myDistance = itemView.findViewById(R.id.all_friends_distance_layout);
myUserDescription = itemView.findViewById(R.id.all_friends_description_layout);
myMarriage = itemView.findViewById(R.id.all_friends_marriage_layout);
myAddress = itemView.findViewById(R.id.all_friends_address_layout);
myPictureOne = itemView.findViewById(R.id.all_friends_post_image_first);
myPictureTwo = itemView.findViewById(R.id.all_friends_post_image_second);
myFriendsProfile = itemView.findViewById(R.id.all_friends_information_layout);
SendMessageButton = itemView.findViewById(R.id.all_friends_call_layout);
myFriendsProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ProfileActivity.class));
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ChatActivity.class));
}
});
}
This is MainActivity;
private DatabaseReference UsersRef;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firstUsersProfilesColRef = db.collection("usersProfiles");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestoreList = findViewById(R.id.all_users_list);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("allUsers");
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("홈");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ToolbarProfileBtn = (ImageButton) findViewById(R.id.toolbar_profile_button);
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ToolbarProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SendUserToSetupActivity();
}
});
DisplayAllUsersList();
}
private void DisplayAllUsersList()
{
Query salaryQuery = firstUsersProfilesColRef;
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(salaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
protected void onStart()
{
super.onStart();
adapter.startListening();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
This is phone's screenshot;
enter image description here
In your layout file all_friends_list_layout. I think you have used android:layout_height="match_parent"
so there you need to use
android:layout_height="wrap_content"
Or instead of wrap_content you can also use any value like 150dp or whatever you feel appropriate for your need.

How do you delete a specific table in sqlite in android studio?

Ive got an app that im creating where i want to be able to type in the users username and click delete then it will delete all of the data for that specific user, Eg-address, phone, birthdate. But for some reason when on the manage user activity when i click the remove button which should take me to the remove activity it takes me back to the main activity instead! Can anyone see what ive done wrong please!!!
Remove class:
public class Remove extends AppCompatActivity {
DatabaseHelperUser myDb;
Button btRemove = findViewById(R.id.buttonRemove);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove);
final EditText etUser = findViewById(R.id.editTextUser);
myDb = new DatabaseHelperUser(this);
btRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Integer deletedRows = myDb.deleteData(etUser.getText().toString());
if(deletedRows > 0){
Toast.makeText(getApplicationContext(), "Data Deleted", Toast.LENGTH_LONG).show();}
else{
Toast.makeText(getApplicationContext(), "Data has not been Deleted", Toast.LENGTH_LONG).show();}
}
});
}
}
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "UserNum";
public static final String COL2 = "UserName";
public static final String COL3 = "Password";
public static final String COL4 = "BirthDate";
public static final String COL5 = "Phone";
public static final String COL6 = "Address";
public DatabaseHelperUser(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Integer deleteData(String UserName){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName});
}
}
Manage user class:
public class ManagingUsers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managing_users);
final Button btadd = findViewById(R.id.buttonAdd);
final Button btInventory = findViewById(R.id.buttonInventory2);
final Button btView = findViewById(R.id.buttonView);
final Button btRemove = findViewById(R.id.buttonRemove);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Add.class);
startActivity(i);
}
});
btInventory.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Inventory.class);
startActivity(i);
}
});
btView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), com.example.assignment3.View.class);
startActivity(i);
}
});
btRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), com.example.assignment3.Remove.class);
startActivity(i);
}
});
}
}

How to get data from RecyclerView item position

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){
....
}
}
}
`

Google Play Games Login with Firebase notworking

Hello here is my code for my App, and I try to login via Google Play Games, but it doesn't work. I hope you can tell me some solutions. I have Google Login working, on another activity but Play Games Login won't work.
public class start extends AppCompatActivity implements
View.OnClickListener{
private static final String TAG = "StartActivity";
GoogleApiClient mGoogleApiClient;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private AdView mAdview;
private InterstitialAd interstitialAd;
private FirebaseAnalytics mFirebaseAnalytics;
private ProgressDialog loadingBar;
private Status statusTextView;
TextView LoginUserName, LoginUserEmail;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
private Button LogOutBtn;
private Button playgames;
private TextView mStatusTextView;
private TextView mDetailTextView;
private TextView mPlayername;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
private final static int RC_SIGN_IN = 9001;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseUser currentUser = mAuth.getCurrentUser();
signInSilently();
mGoogleApiClient.connect();
updateUI(currentUser);
}
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
LogOutBtn = findViewById(R.id.logout);
mAuth = FirebaseAuth.getInstance();
mStatusTextView = findViewById(R.id.status);
mDetailTextView = findViewById(R.id.detail);
mPlayername = findViewById(R.id.mPlayername);
playgames = findViewById(R.id.playgames);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
LogOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
playgames.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSignInIntent();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(XXXXXX)
.requestEmail()
.requestProfile()
.requestIdToken(XXXXXX)
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(start.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//End of Authentification
}
// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());
AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(start.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
firebaseAuthWithPlayGames(signedInAccount);
} else {
// Player will need to sign-in explicitly using via UI
Toast.makeText(start.this, "Cannot Connect", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
firebaseAuthWithPlayGames(signedInAccount);
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
Toast.makeText(start.this, "Cannot Connect 1", Toast.LENGTH_SHORT).show();
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
private void updateUI(FirebaseUser user) {
if (user != null) {
String playerName = user.getDisplayName();
mPlayername.setText(playerName);
// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.logout:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.playgames:
startSignInIntent();
break;
// ...
}
}
}
I really hope someone has a working example, or can help me here, cause I'm stuck at this code for a month now.

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) {}
});

Resources