add data to listview from another activity - java

I'm really confused on how to add from another activity I keep getting an error in this part of the code:
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
So the error says "actual and formal argument lists differ in length". if anyone could help me out it would be such a huge help thank you :)
this my code:
main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button newEmail;
private ListView listView;
private EmailAdapter emailAdapter;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
emailAdapter = new EmailAdapter(this, emailsArrayList);
listView.setAdapter(emailAdapter);
updateList();
newEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendActivity.class);
startActivity(intent);
}
});
}
private void init(){
newEmail = (Button) findViewById(R.id.newBtn);
listView = (ListView) findViewById(R.id.list);
emailsArrayList = new ArrayList<>();
Emails emails = new Emails ();
emails.setEmails("josemari#yahey.com");
emails.setSubject("Sample Data");
emails.setBody("this is the sample data");
emailsArrayList.add(emails);
}
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d("MainActivity","onStart invoked");
}
#Override
protected void onResume() {
super.onResume();
Log.d("MainActivity","onResume invoked");
}
#Override
protected void onPause() {
super.onPause();
Log.d("MainActivity","onPause invoked");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is the add item activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class SendActivity extends AppCompatActivity {
private Button send;
private Button discard;
private EditText email;
private EditText subject;
private EditText body;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
send = (Button) findViewById(R.id.sendBtn);
discard = (Button) findViewById(R.id.discardBtn);
email = (EditText) findViewById(R.id.inputEmail);
subject = (EditText) findViewById(R.id.inputSubject);
body = (EditText) findViewById(R.id.inputBody);
discard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SendActivity.this, MainActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputEmail = email.getText().toString();
String inputSubject = subject.getText().toString();
String inputBody = body.getText().toString();
if (inputBody.isEmpty() || inputEmail.isEmpty() || inputEmail.isEmpty()){
Toast.makeText(SendActivity.this, "Please enter the following data", Toast.LENGTH_SHORT).show();
}
else {
emailsArrayList = new ArrayList<>();
Emails newEmails = new Emails ();
newEmails.setEmails(inputEmail);
newEmails.setSubject(inputSubject);
newEmails.setBody(inputBody);
emailsArrayList.add(newEmails);
Intent intent = new Intent();
getIntent().putExtra("inputEmail", inputEmail);
getIntent().putExtra("inputSubject", inputSubject);
getIntent().putExtra("inputBody", inputBody);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}

I would also change the following as well:
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
to
private void updateList()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
{
Emails a = new Emails(String)bundle.get("inputEmail"), (String)bundle.get("inputBody"), (String)bundle.get("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
I would try this absolutley first: You may beable to use what you have and just change the Bundle bundle and Intent intent lines around in your updateList(). Again no expert but try that first and then above that second. I hope it works for you.

Related

ClassCastException: com.nambimobile.widgets.efab.ExpandableFabLayout cannot be cast to Activity onCreate

So I'm adding an expandable fab, but I'm having this error and I don't understand why...
this is the exact error in log:
ava.lang.ClassCastException: com.nambimobile.widgets.efab.ExpandableFabLayout cannot be cast to com.nambimobile.widgets.efab.ExpandableFab
at CategoryActivity.onCreate(CategoryActivity.java:56)
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class CategoryActivity extends AppCompatActivity implements CategoryAdapter.onCategoryClickListener {
public static final String CATEGORY_NAME = "category_name";
private NoteViewModel noteViewModel;
private CategoryAdapter adapter;
private RecyclerView recyclerView;
private List<FolderWithNotes> folderWithNotes;
private Note note;
private Folder folder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(this.getApplication()).create(NoteViewModel.class);
recyclerView = findViewById(R.id.category_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
});
ExpandableFab exFab = findViewById(R.id.exFab);
exFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case (R.id.exfab_add_category):
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
startActivity(intent);
case (R.id.exfab_delete_category):
default:
break;
}
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
String category = data.getStringExtra(AddCategoryActivity.CATEGORY_REPLY);
String notes = data.getStringExtra(AddNoteActivity.NOTE_REPLY);
Folder folder = new Folder(note.getFolder_name());
noteViewModel.insert(folder, note);
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new CategoryAdapter(folderWithNotes, this, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCategoryClick(int position) {
// code to transfer to AddNoteActivity (where the note list is) by clicking the category folder
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
Intent intent = new Intent(CategoryActivity.this, NotesActivity.class);
intent.putExtra(CATEGORY_NAME, folderWithNotes.get(position).getFolder().getFolderName());
});
}
public void addCategoryClicked(View view) {
EditText editCategory = findViewById(R.id.et_add_category);
String categoryTitle = editCategory.getText().toString().trim();
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
}
public void deleteCategoryClicked(View view) {
}
// #Override
// public void addCategoryClicked(int position) {
//
// }
//
}

How to put if in OnCreate()

Hi there i have a problem error that from NextActivity cannot go to the MainActivity3. Here is the Code NextActivity
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class NextActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView= findViewById(R.id.textView);
textView.setText(message);
}
public void onBtnClick(View view){
Intent intent = getIntent();
Intent intent1= new Intent(this,MainActivity3.class);
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String message1 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE1);
TextView textView= findViewById(R.id.textView);
TextView plain1= findViewById(R.id.plain1);
TextView plain2= findViewById(R.id.plain2);
String b=plain1.getText().toString();
if(b.equals(message.toString())&&plain2.getText().toString().equals(message1.toString())){
startActivity(intent1);
}
else{
textView.setText("Password or Username is Wrong");
}
}
}
and here is the code of MainActivity3 that cannot be open through NextActivity
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.ActionProvider;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity3 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent= getIntent();
String number = intent.getStringExtra(MainActivity2.extraint);
FrameLayout lay= (FrameLayout) findViewById(R.id.frames);
if(number.equals("1")) {
lay.setVisibility(View.INVISIBLE);
}
else{
}
}
public void onBtnClick (View view){
Intent intent = new Intent(this,MainActivity2.class);
startActivity(intent);
}
}
The Problem is that through the NextActivity button click the apps will restart in it's own that supposed to go to the page of MainActivity3
I have fixed it by
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent = getIntent();
String number = intent.getStringExtra(MainActivity2.extraint);
if(number != null) {
FrameLayout lay = (FrameLayout) findViewById(R.id.frames);
if (number.equals("1")) {
lay.setVisibility(View.INVISIBLE);
} else {
}
}
else{}
}
Maybe any others that have a better ways?

How to call information from radiobutton in separate activity in Android Studio

In my app, I have music playing when the app starts. If the user goes to settings they can change the volume or turn the music on and off, however I do not know how to recall the information from the radio buttons to turn the music on or off in other activities. I know if I turn the music off in the main activity under onCreate it will listen to the radio buttons, but I want music playing when the app starts and when you resume the activity it inputs the info from the radio buttons.
This is the code of my main activity
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc = new Intent(this, music.class
);
startService(svc);
}
public void onPlayPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), Game.class);
startActivity(myIntent);
}
public void onSettingsPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), Settings.class);
startActivity(myIntent);
}
public void onHowtoPressed(View view) {
Intent myIntent = new Intent(getBaseContext(), HowtoPlay.class);
startActivity(myIntent);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
Intent svc = new Intent(this, music.class);
stopService(svc);
}
}
and this is the code of my Settings activity
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;
public class Settings extends AppCompatActivity {
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Intent svc = new Intent(this, music.class
);
RadioButton rdb = (RadioButton) findViewById(R.id.on);
rdb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
startService(svc);
}
else{
stopService(svc);
}
}
});
RadioButton rdb2 = (RadioButton) findViewById(R.id.off);
rdb2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
stopService(svc);
}
else{
startService(svc);
}
}
});
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.seekBar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
}
public void onMainMenuPressed(View view){
Intent myIntent=new Intent(getBaseContext(),MainActivity.class);
startActivity(myIntent);
}
public void onResumePressed (View view){
Intent myIntent=new Intent(getBaseContext(),Game.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(myIntent);
finish();
}
} ```
Use SharedPreferences with simple boolean flag.
You should use onCheckedChangeListener on the radio group rather than onClickListener on individual radio button, like so:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(...) {
getSharedPreferences("prefs", 0).edit().putBoolean("music", rdb.isChecked()).apply();
}
});
Then inside other activity:
boolean music = getSharedPreferences("prefs", 0).getBoolean("music", true);
Then check value of the flag to determine whether or not to start the music service.

Can't identify int in startActivityForResult?

package com.example.feelhut;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class editprofile extends AppCompatActivity {
ImageButton proileimagebutton;
private static final int ImageRequest=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("imageeeeeee/");
There ImageRequest showing Error in startActivityForResult. Means I am not able to identify image request here.
startActivityForResult(intent.ImageRequest);
}
});
}
}
public class editprofile extends AppCompatActivity {
ImageButton proileimagebutton;
private static final int ImageRequest=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//no content view? add like this setContentView(R.layout.yourViewLayout);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,ImageRequest);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ImageRequest&& resultCode == RESULT_OK) {
// your ImageView.setUri(data.getData();
}
}
}
You need to declare int above "public class editprofile extends AppCompatActivity".
The code should be
private ImageButton proileimagebutton;
private static final int ImageRequest=1;
public class editprofile extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
proileimagebutton= findViewById(R.id.edit_profile);
proileimagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("imageeeeeee/");

Unable to save the firebase activity state

The Main Dashboard File of the App
Dashboard.java
package com.abc.farmersconsult;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class RegisterActivity extends AppCompatActivity {
private EditText editText;
private Spinner spinner;
FirebaseAuth mAuth;
DatabaseReference userRef;
FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
spinner = findViewById(R.id.spinner_countries);
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
CountryData.countrynames));
editText = findViewById(R.id.Phone);
findViewById(R.id.Continue).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String code =
CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
Intent intent = new Intent(RegisterActivity.this,
VerifyPhone.class);
intent.putExtra("phonenumbers", phoneNumber);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser=FirebaseAuth.getInstance().getCurrentUser();
UpdateUI(currentUser);
/*
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Intent intent = new Intent(this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} */
}
private void UpdateUI(FirebaseUser currentUser) {
if(currentUser!=null){
Intent intent=new Intent(RegisterActivity.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
This File is The Profile Setup Activity
SetupProfile.java
public class SetupProfile extends AppCompatActivity {
EditText editText;
Button button;
private FirebaseAuth mAuth;
DatabaseReference mUserRef;
String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup_profile);
mAuth=FirebaseAuth.getInstance();
CurrentUserID=mAuth.getCurrentUser().getUid();
mUserRef=FirebaseDatabase.getInstance().getReference().
child("Users").child(CurrentUserID);
button=(Button)findViewById(R.id.save);
editText=(EditText)findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAccount();
}
});
}
private void saveAccount() {
String username=editText.getText().toString().trim();
if(username.isEmpty()){
Toast.makeText(this,"Enter valid name", Toast.LENGTH_LONG).show();
}
else{
HashMap userMap= new HashMap();
userMap.put("username",username);
mUserRef.updateChildren(userMap).addOnCompleteListener(new
OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Toast.makeText(SetupProfile.this,"Account
create",Toast.LENGTH_LONG).show();
sendHome();
}
}
});
}
}
private void sendHome() {
Intent intent=new Intent(SetupProfile.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
This File Contains Verification of the OTP file
VerifyPhone.java
public class VerifyPhone extends AppCompatActivity {
private String verificationId;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
private EditText editText;
DatabaseReference userRef;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
editText = findViewById(R.id.verify_otp);
String phonenumber = getIntent().getStringExtra("phonenumbers");
sendVerificationCode(phonenumber);
findViewById(R.id.Sign).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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 checkExistence() {
}
private void SendUserToSetup() {
Intent intent=new Intent(VerifyPhone.this, SetupProfile.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final String current_userid=mAuth.getCurrentUser().getUid();
userRef= FirebaseDatabase.getInstance().getReference().child("Users");
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(current_userid)){
SendUserToSetup();
}
else {
Intent intent = new Intent(VerifyPhone.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(VerifyPhone.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken
forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
String code = credential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
signInWithCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhone.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
RegisterPhone.java
package com.abc.farmersconsult;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class RegisterActivity extends AppCompatActivity {
private EditText editText;
private Spinner spinner;
FirebaseAuth mAuth;
DatabaseReference userRef;
FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
spinner = findViewById(R.id.spinner_countries);
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
CountryData.countrynames));
editText = findViewById(R.id.Phone);
findViewById(R.id.Continue).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String code =
CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
Intent intent = new Intent(RegisterActivity.this,
VerifyPhone.class);
intent.putExtra("phonenumbers", phoneNumber);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser=FirebaseAuth.getInstance().getCurrentUser();
UpdateUI(currentUser);
/*
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Intent intent = new Intent(this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} */
}
private void UpdateUI(FirebaseUser currentUser) {
if(currentUser!=null){
Intent intent=new Intent(RegisterActivity.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
There are Four Files Namely Dashboard.java, VerifyPhone.java, RegisterPhone.java and SetupProfile.java, I am able to perform OTP Authentication Successfully and Move to Setup Profile Activity and then the app moves to the Dashboard.java
The Problem is if I exit the app it starts with Dashboard.java,it doesnot resume the profile setup activity.
It directly logs into the Dashboard everytime i perform sign in, I want the app to resume the incomplete account setup upon opening the application please help
After trying to understand your code (which you need to improve on how to write it in StackOverflow), I think the problem is because you just forget to sign-out when the app exit.
Firebase will keep your user signed-in, even after you exit your app. So that's why in your RegisterActivity, the result will always come true, as there is always a FirebaseUser in FirebaseAuth. Solution is: You have to make sure they signed-out when they re-enter the app.
Suggestions
You can signout every time your Activity is destroyed (or everytime user opens the app). Making sure they always start fresh.

Categories