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
Related
I'm trying to use a button to change from Main Activity on android studio to Main Activity 2 and I get the error
no suitable constructor found for Intent(<anonymous OnClickListener>,Class<MainActivity2>)
Intent intent = new Intent(this, MainActivity2.class);
^
I'm on version 4.1 and I want to assume i'm following an old tutorial or I just missed some punctuation.
This is my code:
buttonPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity2();
}
public void openMainActivity2(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
Just to give more clarity to Caio's answer, when you use this
Intent intent = new Intent(this, MainActivity2.class);
The intent is created in an anonymous inner class i.e. OnClickListener. Thus this does not refer the instance of your Activity (or Context) as intended. You need to provide the correct context of your class.
Hence , do this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
You have to try getApplicationContext() or activity.this instead of this.
I think you are having this issue for "this". Cause, I can't see any other issue.
Intent intent = new Intent(getApplicationContext(),MainActivity2.class)
startActivity(intent);
you should provide the correct context of your class.
try this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
This java code is for the old version, it does not work with android studio's latest version.
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivities(intent);
here is code for the more recent versions:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
public void openMainActivity() {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
};
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 .....//
I'm trying to send messages through in built sms app through Intent. Its working fine. Here is my code
public class Main_Act extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startBtn = (Button) findViewById(R.id.button);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(sendSMS()) {
Intent intent = new Intent(Main_Act.this, Sample.class);
startActivity(intent);
}
}
});
}
protected boolean sendSMS() {
ArrayList<String> nums = new ArrayList<String>();
nums.add("111111111");
nums.add("222222222");
Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" ,nums);
smsIntent.putExtra("sms_body" , "Test ");
try {
startActivity(smsIntent);
finish();
return true;
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Main_Act.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
return false;
}
}
}
But the problem is it gets navigated to another activity without clicking send button in sms application. It should goto another activity only after clicking the send button in messaging app. Can anyone help me with this problem, Thanks in advance.
Let's clear out a slight misunderstanding in your code:
You should not try to start both intents in the same part/run of the code as you do here.
A startActivity will not execute directly going to the activity and then return to the same place in the code when activity execution finishes. In stead it asynchronously queues the intent for execution. Then your code queues another intent for execution. After the current code finishes (in this case when the button onClick() method ends) Android queue mgmt can start picking off the queue. Probably the first intent is executed shortly and then directly overrun by an immediate execution of the second.
So what happens in summary is that you first add one intent to the queue in sendSMS and then add intent 2 to the queue in onClick, before leaving. Now both the intents are executed.
What you need to do is to change the sendSMS code to something like:
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" ,nums);
smsIntent.putExtra("sms_body" , "Test ");
// To force the SMS app to return immediately after sent SMS
smsIntent.putExtra("exit_on_sent", true);
startActivityForResult(smsIntent, MY_SMS_REQUEST_RESPONSE_CODE);
Note the startActivityForResult() method that indicates that we expect Android to return and the "exit_on_sent" extra, to force a swift return.
MY_SMS_REQUEST_RESPONSE_CODE is just any random code you select to recognize the returning result in the callback method (even if you currently do not expect any other returning results, you may have some in the future).
Next thing to do is to remove the second intent creation and queuing. In stead you implement the following callback method (added to this activity):
#Override
protected void onActivityResult(
int callbackIdentifier, int resultCode, Intent intent) {
// Is this the expected sendSMS callback ?
if (callbackIdentifier== MY_SMS_REQUEST_RESPONSE_CODE) {
if (resultCode == RESULT_OK) {
// Continue where you left off (e.g. execute intent 2)
Intent intent = new Intent(Main_Act.this, Sample.class);
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// Error handling/retrying etc
}
}
// Support inherited callback functions
super.onActivityResult(callbackIdentifier,resultCode,intent);
}
Note: if you want to pass data and type don't call method separately because will delete each other you must pass it in one method
wrong
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
true
smsIntent.setDataAndType(Uri.parse("smsto:"),"vnd.android-dir/mms-sms");
I want to start another activity in finish() depending on a condition. I got the same code working in onDestroy() but I think this is not the right place from the lifecycle point of view.
(Activities might be destroyed, although there were not actively left by the user).
The following code did not have any effect:
#Override
public void finish() {
if (mCondition) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
}
super.finish();
}
Why is it not working, are there alternatives?
I think the best option is starting the new activity then finish the current one:
if (mCondition) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finish();
}
I have Used Myself this and it is working fine
public void ToBeClosed()
{
Intent a = new Intent(context,NewActivity.class);
startActivity(a);
OldActivity.this.finish();
}
and use the function in if statement body
if (mCondition) { ToBeClosed(); }
Im running an AsyncTask in an inner class and once complete within the onPostExecute() I want to use an intent to pass values to another activity however I have two errors that im not sure how to fix.
The errors occur on the setResult() line at RESULT_OK and the finish() line explaining that these two actions cannot occur outside of an activity. How would i use this intent in the onPostExecute of the 'AsyncTask'?
Code:
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Intent intent = new Intent();
intent.putExtra("jobs", jobStatus);
intent.putExtra("requestsSent", requests);
setResult(RESULT_OK, intent);
finish();
}
you need use Context of Activity class like following for finish method:
YourActivity.this.finish()
and RESULT_OK exists on activity class, so you need:
Activity.RESULT_OK
so your code must be like following:
Intent intent = new Intent();
intent.putExtra("jobs", jobStatus);
intent.putExtra("requestsSent", requests);
setResult( Activity.RESULT_OK, intent);
YourActivity.this.finish()
setResult and finish() are method of Activity class. You will need activity context for the same
http://developer.android.com/reference/android/app/Activity.html.
Now pass the Activity context to the constructor of AsyncTask
new TheTask(ActivityName.this).execute(params);
Then
Context mContext;
public TheTask(Context context)
{
mContext = context;
}
If AsyncTask is an inner class of the Activity you can use ActivityName.this
((Activity) mContext).setResult(Activity.RESULT_OK, intent);
((Activity) mContext).finish();