How to get my TextView clickable to display the alert diaglog box? - android-studio

I have the following code but the word "reset password" is not clickable. Even after I add some attributes to my xml, I still can't get it to be clicked. I thought that we should be using a button instead of a textview for clicking on? I have linked the variables to my xml file and set the relevant TextView for it.
public class LoginActivity extends AppCompatActivity {
private EditText email;
private EditText password;
private TextView reset_password;
private Button login;
private Button register;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
register = findViewById(R.id.register);
reset_password = findViewById(R.id.reset_password);
auth = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
loginUser(txt_email, txt_password);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
private void loginUser(String email, String password) {
auth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
});
reset_password.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter Your Email To Received Reset Link");
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString().trim();
auth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(LoginActivity.this, "Reset Link Sent To Your Email", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "Error! Reset Link is Not Sent" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
This is my xml code:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Forgot Password"
android:layout_below="#id/password"
android:id="#+id/reset_password"/>

Related

Android Studio: How to send data from Activity to Fragment | Method invocation 'getString' may produce 'NullPointerException'

I am having a problem where in the Fragment the "getString()" says "Method invocation 'getString' may produce 'NullPointerException'" that's the only problem. The Fragment is stored in MainActivity in Navigation Window.
LoginActivity (Where MainActivity is getting the Data):
private void LoginMethod(String email, String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (result.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String username = object.getString("Username").trim();
String email = object.getString("Email").trim();
Toast.makeText(Login.this, "Login Success: " + username, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
}
}
else if (result.equals("0")) {
Toast.makeText(Login.this, "Login Failed" + result + response, Toast.LENGTH_LONG).show(); Log.e("JSON Error", response);
Log.e("Login Error", result);
}
}
catch (JSONException e){
Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("JSON Error", response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", email);
params.put("Password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
**MainActivity:**
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
TextView getemail, getusername;
DrawerLayout drawerLayout;
NavigationView navigationView;
View navheader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("State","onCreate");
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navheader = navigationView.getHeaderView(0);
String getUsername = getIntent().getStringExtra("username");
String getEmail = getIntent().getStringExtra("email");
getusername = navheader.findViewById(R.id.getusername);
getemail = navheader.findViewById(R.id.getemail);
toolbar.setTitle(getUsername);
getusername.setText(getUsername);
getemail.setText(getEmail);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.nav_drawer_open, R.string.nav_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
navigationView.setCheckedItem(R.id.home);
}
}
public void getAccountFragmentData(){
String test = "akshdasjkdhsajkdasdas";
String test2 = "wadahawawaawaww";
Bundle bundle = new Bundle();
bundle.putString("username", test);
bundle.putString("email", test2);
Account account = new Account();
account.setArguments(bundle);
Toast.makeText(this, "Account", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
break;
case R.id.orderfood:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FoodOrder()).commit();
break;
case R.id.account:
getAccountFragmentData();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Account()).commit();
break;
case R.id.settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Settings()).commit();
break;
case R.id.email:
Toast.makeText(this, "Email", Toast.LENGTH_SHORT).show();
break;
case R.id.share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
Log.i("State","onStart");
}
#Override
protected void onResume() {
super.onResume();
Log.i("State","onResume");
}
#Override
protected void onPause() {
super.onPause();
Log.i("State","onPause");
}
#Override
protected void onStop() {
super.onStop();
Log.i("State","onStop");
}
#Override
protected void onRestart() {
super.onRestart();
Log.i("State","onRestart");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i("State","onDestroy");
}
}
**Fragment:
**
public class Account extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
TextView getUsername = v.findViewById(R.id.username);
TextView getEmail = v.findViewById(R.id.email);
Bundle bundle = this.getArguments();
String setUsername = bundle.getString("username");
String setEmail = bundle.getString("email");
getUsername.setText(setUsername);
getEmail.setText(setEmail);
Log.i("Data Sent", "Sent");
return v;
}
I want the Fragment to get the data from MainActivity.

I want to know how to randomly display images in gridview through SwipeRefreshLayout

SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
I want to know how to randomly display images in gridview through SwipeRefreshLayout
I want a UI like the site https://www.pinterest.com
I want to show random images on refresh to show a lot of images, can you tell me how?
thank you in advance
Below is the full code.
public class MainActivity extends AppCompatActivity {
private List<String> mImagesLinks = new ArrayList<>();
private GridView mGridView;
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
int nCurrentPermission = 0;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
mGridView = findViewById(R.id.grid_view);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(MainActivity.this, ImageActivity.class)
.putExtra("Link", mImagesLinks.get(i)));
}
});
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_grid);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImages();
refreshLayout.setRefreshing(false);
}
});
getImages();
}
private void getImages() {
Call<List<String>> imagesResponse = NetworkUtils.getInterface().loadImages();
imagesResponse.enqueue(new Callback<List<String>>() {
#Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
if (response.isSuccessful()) {
mImagesLinks = response.body();
ImagesAdapter imagesAdapter = new ImagesAdapter(MainActivity.this, mImagesLinks);
mGridView.setAdapter(imagesAdapter);
imagesAdapter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this, R.string.error_response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<String>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SET_WALLPAPER,
Manifest.permission.READ_CONTACTS)
.check();
}
}
Just use Collections.shuffle(list); in your getImages() function.
Refer this for more information : https://www.geeksforgeeks.org/shuffle-or-randomize-a-list-in-java/

Fragment cannot be cast to java.util.concurrent.Executor error

I'm attempting to sign in or sign up using fragments, and after a successful sign-in/sign up, the HomeActivity supposed to load. The issue is that when I click the sign-in/sign up button, it returns to the same fragment instead of going to the HomeActivity.class. The app's initialization page is called LoginRegistrationActivity.class where it will call the SignIn fragment. I confirmed that Sign in/Sign Up is working well, but I am unable to navigate to the HomeActivity.class after successful authentication. I'm not sure if there is an issue with the AndroidManifest.xml file.
I got this logcat error after I clicked sign in:
java.lang.ClassCastException: com.fyp.selfzen.fragments.O_LoginRegistration.SignIn cannot be cast to java.util.concurrent.Executor
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn.login(SignIn.java:124)
at com.fyp.selfzen.fragments.O_LoginRegistration.SignIn$1.onClick(SignIn.java:87)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
SignIn.java fragment
public class SignIn extends Fragment{
private EditText editText_email, editText_password;
private String email, password;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
LoginRegisrationActivity loginRegistration;
public SignIn(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
}
public static SignIn newInstance(LoginRegisrationActivity loginRegistration) {
SignIn fragment = new SignIn(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_email = view.findViewById(R.id.editText_email_login_activity);
editText_password = view.findViewById(R.id.editText_password_login_activity);
TextView button_login = view.findViewById(R.id.button_login_activity);
TextView textView_signup_login = view.findViewById(R.id.textView_signup_login);
final SmoothCheckBox checkBox = view.findViewById(R.id.checkbox_login_activity);
checkBox.setChecked(false);
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = editText_email.getText().toString();
password = editText_password.getText().toString();
editText_email.clearFocus();
editText_password.clearFocus();
login(email, password);
}
});
textView_signup_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignUp f2 = SignUp.newInstance(loginRegistration);
loginRegistration.loadFrag(f2, getResources().getString(R.string.regis));
}
});
return view;
}
public void login(String email, String password) {
editText_email.setError(null);
editText_password.setError(null);
if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if(password.isEmpty()){
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else {
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Successfully sign in!", Toast.LENGTH_LONG).show();
// Intent i = new Intent(loginRegistration, HomeActivity.class); //First try to go to HomeActivity
Intent i = new Intent(getContext(), HomeActivity.class); //Second try
startActivity(i);
//loginRegistration.finish();
} else {
Toast.makeText(getContext(), "Sign in failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
} //onComplete
}); // firebaseAuth
}// else
} // login end
}
SignUp.java fragments
public class SignUp extends Fragment{
private EditText editText_name, editText_email, editText_password, editText_phoneNo;
private String name, email, password, phoneNo;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
LoginRegisrationActivity loginRegistration;
public SignUp(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
// Required empty public constructor
}
public static SignUp newInstance(LoginRegisrationActivity loginRegistration) {
SignUp fragment = new SignUp(loginRegistration);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_name = view.findViewById(R.id.editText_name_register);
editText_email = view.findViewById(R.id.editText_email_register);
editText_password = view.findViewById(R.id.editText_password_register);
editText_phoneNo = view.findViewById(R.id.editText_phoneNo_register);
TextView button_submit = view.findViewById(R.id.button_submit);
TextView textView_login = view.findViewById(R.id.textView_login_register);
// Go to login page
textView_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn f1 = SignIn.newInstance(loginRegistration);
loginRegistration.loadFrag(f1, getResources().getString(R.string.login));
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = editText_name.getText().toString();
email = editText_email.getText().toString();
password = editText_password.getText().toString();
phoneNo = editText_phoneNo.getText().toString();
form();
}
});
return view;
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void form() {
editText_name.setError(null);
editText_email.setError(null);
editText_password.setError(null);
editText_phoneNo.setError(null);
if (name.equals("") || name.isEmpty()) {
editText_name.requestFocus();
editText_name.setError(getResources().getString(R.string.please_enter_name));
}
else if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if (password.equals("") || password.isEmpty()) {
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else if (phoneNo.equals("") || phoneNo.isEmpty()) {
editText_phoneNo.requestFocus();
editText_phoneNo.setError(getResources().getString(R.string.please_enter_phone));
}
else {
editText_name.clearFocus();
editText_email.clearFocus();
editText_password.clearFocus();
editText_phoneNo.clearFocus();
}
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Successfully registered!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(loginRegistration, HomeActivity.class);
Intent i = new Intent(getActivity(), HomeActivity.class);
startActivity(i);
//loginRegistration.finish();
}
else{
Toast.makeText(getContext(), "Sign up failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
} // end of form
}
LoginRegistrationActivity.class
public class LoginRegisrationActivity extends AppCompatActivity {
private String curent;
VideoView vide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_regisration);
vide = findViewById(R.id.vide);
String video_url = "android.resource://" + getPackageName() + "/" + R.raw.login_video;
Uri videoUri = Uri.parse(video_url);
vide.setVideoURI(videoUri);
vide.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
vide.requestFocus();
vide.start();
}
});
SignIn f1 = SignIn.newInstance(this);
loadFrag(f1, getResources().getString(R.string.login));
}
public void loadFrag(Fragment f1, String name) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(!name.equals(curent)){
curent =name;
ft.replace(R.id.frame_layout, f1, name);
}
ft.commitAllowingStateLoss();
}
}
AndroidManifest.xml
<activity
android:name="com.fyp.selfzen.activities.LoginRegisrationActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.fyp.selfzen.activities.HomeActivity"
android:label="#string/title_activity_home"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Have you solved your problem yet?
I ran into a similar but different issue when trying to use Fragments with FirebaseAuth. All of the documentation I found only referenced using Activities. Changing .addOnCompleteListener to .addOnSuccessListener and adding an .addOnFailureListener made my app work as expected. My app was originally crashing because of the Executor even though it would successfully authenticate users; the success/failure listeners fixed my issue.
My original code (written with help from Firebase Docs):
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( (java.util.concurrent.Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
FragmentFactory.startAdminFragment((MainActivity) getActivity());
} else
Toast.makeText( getContext(), "Authentication failed.", Toast.LENGTH_SHORT ).show();
}
});
}
Current/Working code:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener( new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FragmentFactory.startAdminFragment((MainActivity) getActivity());
}
})
.addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// If sign in fails, display a message to the user.
Log.d(TAG, "signInWithEmail:failure");
Toast.makeText( getContext(), e.getMessage(), Toast.LENGTH_LONG ).show();
}
} );
}
Note:
I only have 1 Activity so I was able to login and continue to my desired Fragment but you should be able to modify my code (FragmentFactory.startAdminFragment((MainActivity) getActivity());) to continue to your HomeActivity.class
This video helped a lot: https://www.youtube.com/watch?v=fPhy1PKR1Wg
I hope this helps.
In SignIn.java and SignUp.java fragment you add addOnCompleteListener() for firebaseAuth. So, pass arguments in it,
Instead of,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {}
To,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(getContext(), new OnCompleteListener<AuthResult>() {}
IF, getContext() not work then try to write getActivity().

Pass EditText value to ListView from two different activities

appreciate if you can help me here.
I am creating a To Do List, where the ListView is in the MainToDoList Activity with a "Add a new Task" button that takes the user to the second activity.
In the second activity, there is a Edit Text field where user can input the title of the task. Two buttons are "Save" and "Cancel"
My question is, how to pass the edit text value after pressing the save button to display it into the listview in the first activity.
First Activity:
public class Todolistactivity extends AppCompatActivity {
private Button btn;
private ListView list;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.todolistactivity);
btn = findViewById(R.id.addTask);
list = findViewById(R.id.task_list);
}
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Todolistactivity.this, EditToDo.class));
}
});
}
Second Activity:
public class EditToDo extends Todolistactivity {
private static final String TAG = "EditToDo";
private Button save;
private Button cancel;
private EditText title;
#Override
protected void onCreate (Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_taskedit);
save = findViewById(R.id.saveTask);
cancel = findViewById(R.id.cancelTask);
title = findViewById(R.id.taskTitle);
saveButton();
cancelButton();
}
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent backToDo = new Intent
(getBaseContext(),Todolistactivity.class);
String titleEntered = title.getText().toString();
backToDo.putExtra("task", titleEntered);
startActivity(backToDo);
}
});
}
Use startActivityForResult
in your Todolistactivity class
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Todolistactivity.this, EditToDo.class), 100); // 100 is request code.
}
});
}
//...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("task");
}
else if (resultCode == Activity.RESULT_CANCELED) {
//...
}
}
}
In Your EditToDo class
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titleEntered = title.getText().toString();
Intent intent = new Intent();
intent.putExtra("task", titleEntered);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}

my register info will not store in parse

I keep getting an error message when trying to register my users in parse. I also have it set up for email verification too. I can't tell if i doing wrong in my code, looks like i followed parse to the "T".
public class Register extends AppCompatActivity {
protected EditText mUsername;
protected EditText mEmail;
protected EditText mPassword;
protected EditText mPhone;
protected EditText mDob;
protected Button mRegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mUsername=(EditText)findViewById(R.id.username);
mEmail=(EditText)findViewById(R.id.email);
mPassword=(EditText)findViewById(R.id.password);
mPhone=(EditText)findViewById(R.id.phonenumber);
mDob=(EditText)findViewById(R.id.birthday);
mRegisterButton=(Button)findViewById(R.id.registerbutton);
//listen to register button click
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get info covert to string
String username = mUsername.getText().toString().trim();
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String phonenumber= mPhone.getText().toString().trim();
String birthday = mDob.getText().toString().trim();
//store to parse
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.put(phonenumber, "650-253-0000");
user.put(birthday,"00-00-000");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
//user signed up succesfully
Toast.makeText(Register.this, "Welcome To The Party...", Toast.LENGTH_LONG).show();
//take user to home page
} else {
Toast.makeText(Register.this, "Error Try Again...", Toast.LENGTH_LONG).show();
//there was an error siging up
}
}
});
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}

Resources