Adding intent code in an if else statement - java

I'm trying to use the following intent code to add in an if else statement to redirect if login is successful after displaying the toast message under
if (password.equals(storedPassword)) { but I get an "Cannot resolve constructor error.
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
if (password.equals(storedPassword)) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this, "Username or Password incorrect.", Toast.LENGTH_LONG).show();
}
}
});
like this
if (password.equals(storedPassword)) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Username or Password incorrect.", Toast.LENGTH_LONG).show();
}
}
});
I have an ImageView that is visible in Preview, but is not shown in the emulator. I have already clean/build the project and sync gradle files. What could be the issue?

Do you use this from an anonymous inner class? Then thisrefers to the inner class instead of the activity. Use this instead (like you did with the toasts):
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);

Change your intent definition to this :
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
I look at how you call your toast and I infer that your lines of codes are in a inner class, so to refer to your activity context, you need to use MainActivity.this.

Replace this with current activity and for better experience alwyas use a try and catch block for this kind of intent

Related

Check validation and pass value from edit text to move activity

I have a LoginActivity that is not tied to any online database, I only validate the username via edit text component to login and move to the MainActivity. LoginActivity appears when the value of text in MainActivity is null, therefore I created a validation method when the username is null, then the layout will move to LoginActivity, I made it like this with the aim that LoginActivity does not become the main layout of the app.
Validation users in MainActivity.java:
private void checkUsername() {
Intent intent = getIntent();
if(intent.getExtras() != null){
String users = intent.getStringExtra(LoginActivity.EXTRA_USER);
txuser.setText(users);
//NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String)
ContentValues cv = new ContentValues();
cv.put(Contract.UserEntry.NAME_COLUMN,users);
database.insert(Contract.UserEntry.TABLE_NAME,null,cv);
} else {
startActivity(new Intent(this, LoginActivity.class));
}
}
LoginActivity.java
private void loginUser() {
final String username;
username = user.getText().toString();
if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "Name cannot be blank!", Toast.LENGTH_SHORT).show();
}
if (!cbAgree.isChecked()) {
Toast.makeText(this, "Login fails!", Toast.LENGTH_SHORT).show();
}
fabLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, UtamaActivity.class);
intent.putExtra(EXTRA_USER, username);
startActivity(intent);
}
});
}
How do I fix this?, because when I open the app for the first time, the LoginActivity is successfully displayed, but when I enter to MainActivity it immediately forces close. I have included the logcat comment in the checkUsername() method
Change Intent intent = new Intent(LoginActivity.this, UtamaActivity.class);
to Intent intent = new Intent(LoginActivity.this, MainActivity.class);

android.content.Context.getPackageName() on a null object reference

I am getting this error when transtioning from a fragment to an activity as shown below:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ComponentName.<init>(ComponentName.java:130) at android.content.Intent.<init>(Intent.java:6108)
Below is my code for going to the next activity, The error occurs on the first line of the code below.
Intent mainIntent = new Intent (getContext(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
I don't see any solution so far online.
It seems that you're getting a wrong context that raises this NullPointerException
Try to replace the below line:
Intent mainIntent = new Intent (getContext(), MainActivity.class);
With: >> if you're within an activity
Intent mainIntent = new Intent (this, MainActivity.class);
with: >> if you're within a callback listener within the activity
Intent mainIntent = new Intent (MyActivityName.this, MainActivity.class);
With: >> if you're within a fragment
Intent mainIntent = new Intent (requireActivity(), MainActivity.class);
Please try with getActivity() intsead of getContext()
I work the transaction of the fragment with this code
private Context context;
context.startActivity(new Intent(context, MainActivity.class));
I have been able to find a work around this. I realised I am getting the error because I am creating the new Intent inside the firebase OnCompleteListener as shown below. So after i removed it from inside the listener and called it outside, my program works properly.
I instead created a global boolean variable that I updated to true on successful data storage. Then I can access it somewhere else and then transtion to another if true.
#BEFORE
PostsRef.child(key).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getActivity(), "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
Intent mainIntent = new Intent (getActivity(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
} else {
Toast.makeText(context, "Error occured while updating your post.", Toast.LENGTH_SHORT).show();
}
}
});
#AFTER
PostsRef.child(key).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mSuccess = true;
Toast.makeText(getActivity(), "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error occured while updating your post.", Toast.LENGTH_SHORT).show();
}
}
});
Hello guys I have also realised one of the big causes of this error is the lifecycle methods.So I was overriding them inside my fragment to update the user state on the firebase database. Because of this they caused the android.content.Context.getPackageName() on a null object reference error whenever I tried to move to the main activity managing it. Incase I used the fragment transition to move to another fragment, the MainActivity would get excecuted more than twice. After stopping to override them my application worked properly. If someone would explain why that happens it would be great.
#Override
public void onStart() {
super.onStart();
updateUserState("Online");
}
#Override
public void onResume() {
super.onResume();
updateUserState("Online");
}
Since, you are calling from a Fragment, you should use getActivity() here instead of getContext()
Intent mainIntent = new Intent (getActivity(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
This should help I hope.
Sometimes startActivity method throws an exception like:
Calling startActivity() from outside of an Activity context requires
the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So you should intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) method

android studio AsyncTask not intenting and context.finish crashes

i am new to android,and trying to use AsyncTask to get a connection to mysql from the server
protected void onPostExecute(String result) {
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(context,profile.class);
//not usefull
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
((Activity)context).finish();
Toast.makeText(context, "done", Toast.LENGTH_LONG).show();
}else //..... the rest of the code .....//
}
everything works fine but when the result is true it doesn't intent to the new activity
and by using ((Activity)context).finish(); it will crash
the app always toast done
context is defined Context context , i got its value from MainActivity by typing this
Using this is reference to the activity, I think you should be referencing the application context to start an activity.
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(context.getApplicationContext(),profile.class);
context.getApplicationContext().startActivity(intent);
((YourActivityName)context).finish();
Toast.makeText(context, "done", Toast.LENGTH_LONG).show();
}else //..... the rest of the code .....//

Duckduckgo Android search Intent

Anyone knows the intent to search directly through the official Duckduckgo app on Android?
Tried this one so far, i think they dont have a query key in extras
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.setPackage("com.duckduckgo.mobile.android");
intent.putExtra("query", subject);
context.startActivity(intent);
It is actually pretty simple than i thought
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://duckduckgo.com/?q=" + subject));
try {
intent.setPackage("com.duckduckgo.mobile.android");
context.startActivity(intent);
} catch (ActivityNotFoundException a) {
intent.setPackage(null);
context.startActivity(intent);
}

I want to pass flag name to other activity and to show each web view if equal flag

I have two main activities.In login activity ,if I clicked login button to pass flag to main activity.In main activity,if equal flag go to login page of web view .if not so,stay home page.When I created it,pass flag variable is ok but if I clicked login button ,it always go to home page.Please help me kindly.I am learning android as a beginner.
piece of code of MainActivity.java
String flag = getIntent().getStringExtra("flag");
Log.d("FlagCheck", "this flag is (" + flag + ")");
if (flag=="add"){
webview.loadUrl(login_address);
Log.d("FlagCheck", "this flag is login_address");
}else{
webview.loadUrl(home_address);
Log.d("FlagCheck", "this flag is home_address");
}
piece of code of LoginActivity.java
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
savePreferences("CheckBox_Value", checkBoxRememberMe.isChecked());
if (checkBoxRememberMe.isChecked())
savePreferences("storedName", mEmailView.getText().toString());
savePreferences("storedPass", mPasswordView.getText().toString());
/* int requestCode = 1001;
Intent intent = new Intent( getApplicationContext(), MainActivity.class );
startActivityForResult( intent, requestCode );
intent.putExtra( "key", "result_val" );
setResult( Activity.RESULT_OK, intent );*/
finish();
// startActivity(new Intent(LoginActivity.this, HomeActivity.class));
// finish();
Intent i= new Intent(LoginActivity.this, MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("flag", "add");
startActivity(i);
}
});
You should use str.equals("add") or str.equalsIgnoreCase().
As == doesn't checks whether both strings are equal or not, it compares string's location.
You can click here for more information about it.
Try this
if (flag.equalsIgnoreCase("add")){
webview.loadUrl(login_address);
Log.d("FlagCheck", "this flag is login_address");
}else{
webview.loadUrl(home_address);
Log.d("FlagCheck", "this flag is home_address");
}
USed this...
finish();
Intent i= new Intent(LoginActivity.this, MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("flag", "add");
startActivity(i);
Instead of (Remove Finish to above)
Intent i= new Intent(LoginActivity.this, MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("flag", "add");
startActivity(i);
finish()
You Have Value pass the add and or other than you send also like that
if (flag.equalsIgnoreCase("add")){
Intent i= new Intent(LoginActivity.this, MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("flag", "add");
startActivity(i);
finish()
}
else
{
Intent i= new Intent(LoginActivity.this, MainActivity.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("flag", "home");
startActivity(i);
finish()
}

Categories