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 .....//
Related
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
I'm new to android studio, I'm using java to write my application.
I found that when I use intent to make the page jump from a page call PhotosActivity to another page call AndroidTabLayoutActivity was failed,I have no idea with what is going on.The android simulator does't give me any error massage and it just close the application automatically.
the code of calling intent:
if (!error) {
Toast.makeText(getApplicationContext(), "Offer successfully inserted.", Toast.LENGTH_LONG).show();
// Jump to the AndroidTabLayoutActivity page
Intent intent = new Intent(
PhotosActivity.this,
AndroidTabLayoutActivity.class);
startActivity(intent);
finish();
}
The code of AndroidTabLayoutActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// Tab for Photos
TabSpec photospec = tabHost.newTabSpec("Photos");
photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.icon_photos_tab));
Intent photosIntent = new Intent(this, PhotosActivity.class);
photospec.setContent(photosIntent);
//there is still some others tab in here
// Adding all TabSpec to TabHost
tabHost.addTab(photospec); // Adding photos tab
}
You have using getApplicationContext() in this toast method
Replace with activity context, i am sure your code is working fine
Toast.makeText(getApplicationContext(), "Offer successfully inserted.",
Toast.LENGTH_LONG).show();
Use like this
Toast.makeText(PhotosActivity.this, "Offer successfully inserted.",
Toast.LENGTH_LONG).show();
As there is no any particular error log. We have to backtrack all the possibilities .
First of all replace your toast with this.
Toast.makeText(getApplicationContext(), "Offer successfully inserted.", Toast.LENGTH_LONG).show();
After that ensure that you've declared your AndroidTabLayoutActivity in your AndroidManifest.xml file
In your AndroidTabLayoutActivity Cooment out all your code and check its working ? if yes than problem is in AndroidTabLayoutActivity. reply me with whats working for you
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'm trying to use in my project a broadcast receiver which listens to battery status of charging/not charging and throw a toast in each of the options .
every time i change the charger status in the app ,the app crash.
(if i start the app with the charger connected it's show me the right toast
but when i uncharge the phone the app crashes)
here is the code
thanks in advance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging==true){
Toast.makeText(this, "Charging", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Charger not connected", Toast.LENGTH_SHORT).show();
UPDATE
i'm having an hard time to understand what i suppose to do.
i'm pretty new so be patient with me :)
here is the code i made
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBatteryState(null);
public void checkBatteryState(View sender) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, filter);
int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
String strState;
switch (chargeState) {
case BatteryManager.BATTERY_STATUS_CHARGING:
case BatteryManager.BATTERY_STATUS_FULL:
strState = "charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
break;
default:
strState = "not charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
}
}
}
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
is this what you're using?
Maybe you haven't ensured your Intent is sticky.
My advice would be not to use a registerreceiver with a null argument.
Try this method for creating a broadcastreceiver:
How to send data to another app which is not started
put your Toasts in the onReceive() function.
The code is not actually registering a receiver, just getting a sticky broadcast. If the broadcast has never been sent the this will return null which will cause a NPE in the remaining code.
I created my lockscreen application that trigerred by a SMS.. i have ListenSMS class that always listen for incoming SMS. Here's the code :
for (SmsMessage message : messages) {
String tempMessage[] = message.getDisplayMessageBody().toString().split(" ");
//checking command dan password
if (tempMessage[0].toString().equalsIgnoreCase("andro-lock") && tempMessage[1].toString().equals(tempPassword.toString())) {
//Toast.makeText(ListenSMSservice.this, "Menjalankan command andro-lock", Toast.LENGTH_LONG).show();
openDatabase();
updateStatusL();
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}
else if (tempMessage[0].toString().equalsIgnoreCase("andro-unlock") && tempMessage[1].toString().equals(tempPassword.toString())) {
//Toast.makeText(ListenSMSservice.this, "Menjalankan command andro-unlock", Toast.LENGTH_LONG).show();
openDatabase();
updateStatusNL();
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle myKillerBundle = new Bundle();
myKillerBundle.putString("kill","1");
myIntent.putExtras(myKillerBundle);
getApplication().startActivity(myIntent);
}
}
If ListenSMS service has received an andro-lock command, it will go to the lockscreen.java and will go to the lockscreen.java with intent extra (putExtra) kill when it receive command andro-unclock. Here's my lockscreen.java:
public class LockScreenForm extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.lockscreen);
Bundle extra = getIntent().getExtras();
if (extra == null) {
return;
}
//Toast.makeText(this, extra.getString("kill"), 1).show();
else if(this.getIntent().getExtras().getString("kill").equalsIgnoreCase("1")) {
try {
Toast.makeText(this, "extra accepted", 1).show();
finish();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, e.getMessage(), 1).show();
}
}
}
}
I want to close my locksreen.java when my ListenSMS service has received "andro-unlock" command, so I put extra on intent "kill" and check it in lockscreen.java. This lockscreen.java can check the extra intent and can display a toast "extra accepted" but can close the lockscreen activity with finish().
My assumption is for now that Intent.FLAG_ACTIVITY_NEW_TASK is duplicating a locksreen activity. So it will create a double lockscreen activity and the finish method is closing another lockscreen.java that started by Intent.FLAG_ACTIVITY_NEW_TASK. That's only assumption. Am i wrong? Please correct me.
Has anyone know how to solve my problem? I really want that "andro-unlock" command can close the lockscreen activity and need it works for my college final project. Please help.
From http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK:
When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. See FLAG_ACTIVITY_MULTIPLE_TASK for a flag to disable this behavior.
I expect your problem is somewhere else. I'd suggest having the lockscreen Activity register a BroadcastReceiver, and then when the unlock message is received send an Intent that the BroadcastReceiver will catch. The Activity can then cleanly exit.
Try this: Intent.FLAG_ACTIVITY_NEW_TASK