How can i avoid app forcefully closing error - android

App is designed in the way that it will check for Firebase ID on launching. If not,he will be taken to a Registration Activity. If already registered, he will be taken to home activity instead.
Along with this I have configured for click_action of push notification in launcher activity.
On the first opening, user can complete registration completes and open homeactivity as well. But when App is once closed and opened, App crash with message "forcefully closed".
When i checked in the Logcat, error showing is "null object at string line switch (clickaction){ .
please advise how can i rectify this.
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
String clickaction;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth=FirebaseAuth.getInstance();
FirebaseUser currentuser1 =firebaseAuth.getCurrentUser();
if (getIntent().getExtras() == null){
if (currentuser1!= null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
}, SPLASH_TIME_OUT);
}
else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent regintent = new Intent(MainActivity.this, Registration_Activity.class);
startActivity(regintent);
finish();
}
},SPLASH_TIME_OUT);
}
}
else
{
clickaction = (String) getIntent().getExtras().get("openactivity");
Intent intent=new Intent();
switch (clickaction){
case "Act1":
intent=new Intent(this, Activity1.class);
break;
case "Act2":
intent=new Intent(this, Activity2.class);
break;
case "Act3":
intent=new Intent(this, Activity3.class);
break;
default:
intent = new Intent(this, HomeActivity.class);
break;
}
startActivity(intent);
}
}
}

Related

Load app/activity when phone wakes up from sleep

I have an android activity, but when the phone goes to sleep(meaning I leave the phone there for a few seconds and then the screen goes black) and I turn it back on, the activity/app disappears(it's still active but i have to press the overview button to come back to the activity/app). How do I get it to come back automatically?
What I want to do is when the phone goes to sleep, when I turn it back on, the app/activity is there as it was when it went to sleep. I've checked up onResume, BroadcastReceivers, WakeLock, KeepScreenOn, Services, but I know I'm not doing it right.
OnResume doesn't work, WakeLock doesn't work, KeepScreenOn, just keeps the screen on and doesn't allow the phone to sleep, I haven't tried Services and BroadcastReceivers, but I thought I should ask here first.
Please help. Thanks.
I have MainActivity.java which opens initially and then starts AdminAddMerchantActivity.java. AdminAddMerchantActivity.java is a navigationView that starts 4 fragments including TimeFragment.java which has a tab layout, a view pager and a pager adapter. TimeFragment.java starts 5 fragments including PriceFragment.java.
Below is the activities lifecycle methods below.
MainActivity.java:
...
#Override
protected void onPause() {
super.onPause();
Log.d("state", "Pausing Main");
// Handle countdown stop here
}
#Override
protected void onResume() {
super.onResume();
Log.d("state", "Resuming Main");
currentActivity = sharedPreferences.getString(CURRENT_ACT, "main");
if(mAuth.getCurrentUser() != null)
{
if(currentActivity.equals("confirmFinalOrder"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, ConfirmFinalOrderActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("merchantDetails"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, MerchantDetailsActivity.class);
intent.putExtra("mid", sharedPreferences.getString("merchantid", ""));
startActivity(intent);
finish();
}
else if(currentActivity.equals("navigation")) {
isResumed++;
Intent intent = new Intent(MainActivity.this, NavigationActivity.class);
fragment = sharedPreferences.getString("fragment", "Find Food");
intent.putExtra("activity", fragment);
startActivity(intent);
finish();
}
else if(currentActivity.equals("adminaddnewmerchant"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, AdminAddNewMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("searchmerchants"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SearchMerchantsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsuser"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsmerchant"))
{
isResumed++;
Intent intent = new Intent(this, SettingsMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
}
else{
if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
else if(!sharedPreferences.getString("current activity", "main").equals("login user")
&& !sharedPreferences.getString("current activity", "main").equals("login merchant"))
{
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
}
}
// Handle countdown start here
}
#Override
protected void onStop() {
super.onStop();
Log.d("state","Stopping Main");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("state", "Destroyed Main");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("state", "Restarted Main");
}
#Override
protected void onStart() {
super.onStart();
Log.d("state", "Started Main");
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("state", "onRestoreInstanceState Main");
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("state", "onSaveInstanceState Main");
}
//if the user
#Override
public void onBackPressed() {
Log.d("state", "back login");
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
}
...
AdminAddNewMerchantActivity.java:
...
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
// Get the Camera instance as the activity achieves full user focus
//if (mCamera == null) {
//initializeCamera(); // Local method to handle camera init
//}
}
...
PriceFragment.java:
...
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("scrollPrice", scrollView.getScrollY());
editor.commit();
}
#Override
public void onResume() {
Log.d("onResume", "Resumed");
super.onResume();
}
...
TimeFragment.java:
...
#Override
public void onResume() {
super.onResume();
}
...
The default Android behavior should do this automatically...
Are you doing something special on the onPause or onStop methods?
And if you're not, can you create a new project via Android Studio and test to see if this behavior persists on the new app?

Launch Invisible Activity To Obtain Permissions For Service

thanks to everyone for reading. here's an application that has a boot-receiver so it launches upon starting android device:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i1 = new Intent(context, SplashActivity.class);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i1.putExtra("permission_for_service","");
context.startActivity(i1);
}
SplashActivity.class is implemented to obtain permissions before launching MainActivity.class.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkAllRequestedPermissions()) {
ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
}
else {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private boolean checkAllRequestedPermissions() {
for (String permission : allRequestedPermissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
What I'm trying to do is to prevent launching a user interface on boot-up by using a service instead:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (!checkAllRequestedPermissions()) {
ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
} else {
if (getIntent().hasExtra("permission_for_service")) {
//service init
if (!isServiceRunning(SchedulerService.class)) {
startService(new Intent(this, SchedulerService.class));
}
finish();
} else {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
Unfortunately, this crashes on BOOT_COMPLETE. Any ideas on how to make it work? Thanks a million

How to get last/previous intent to refresh

I am working on an online radio app demo. I've created an error Activity which I want to take the user to, when an error occurs. In the error page, there is a refresh button, which is supposed to refresh the last Activity where an error occurred. But I don't know how to get the Intent of previous Activity which led to the error page to get it refresh on ButtonClick, I only know to make it return to a particular Activity.
You can use startActivityForResult in both calling activities
In MainActivity.java
int REFRESH = 1;
private void startErrorActivity() {
startActivityForResult(new Intent(this, ErrorActivity.class), REFRESH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REFRESH) {
//do refresh
}
}
And in ErrorActivity.java
Button button = findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish(); //this will take you back to calling activities onActivityResult method
}
});
UPDATE:
I honestly think #sneharc's answer is better. Use that.
Try this:
public class ActivityA extends Activity {
public void myFunction(){
try{
// something bad happens here. need to go to ErrorActivity
}
catch (SomeException e){
Intent startErrorActivityIntent = new Intent(this, ErrorActivity.class);
startErrorActivityIntent.putExtra("sourceActivity", ActivityA.class.getSimpleName())
startActivity(this, startErrorActivityIntent)
}
}
}
public class ActivityB extends Activity {
public void myFunction(){
try{
// something bad happens here. need to go to ErrorActivity
}
catch (SomeException e){
Intent startErrorActivityIntent = new Intent(this, ErrorActivity.class);
startErrorActivityIntent.putExtra("sourceActivity", ActivityB.class.getSimpleName())
startActivity(this, startErrorActivityIntent)
}
}
}
public class ErrorActivity extends Activity {
private Intent mReceivedIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
mReceivedIntent = getIntent();
}
public void onClickRefresh(){
String retryActivityName = mReceivedIntent.getStringExtra("sourceActivity");
Intent retryActivityIntent = null;
if (!TextUtils.isEmpty(retryActivityName)){}
if (retryActivityName.equalsIgnoreCase(ActivityA.class.getSimpleName()))
retryActivityName = new Intent(this, ActivityA.class);
if (retryActivityName.equalsIgnoreCase(ActivityB.class.getSimpleName()))
retryActivityName = new Intent(this, ActivityB.class);
}
if (retryActivityIntent != null)
startActivityForResult(this, retryActivityIntent);
}
}

How to close app in activity

My app start with splash screen. Splash screen visible for 5 seconds then menu activity start. But when splash screen on display and I press back or home button app go in background but after few seconds its come on foreground automatically with menu activity. I want if user press home or back key app close permanently. Here is what I have tried so far.
Splash Screen Activity-
public class SplashScreen extends Activity
{
/** Called when the activity is first created. */
TimerTask task;
Intent objIntent, intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
new Handler().postDelayed(csRunnable2, 5000);
}
Runnable csRunnable2=new Runnable()
{
#Override
public void run()
{
intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
public void onBackPressed()
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}
}
You can see in onPause and onBackPressed I am closing app. But its start with menu activity after few seconds.
what suitianshi suggests is
public class SplashScreen extends Activity
{
/** Called when the activity is first created. */
TimerTask task;
Intent objIntent, intent;
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
handler = new Handler();
handler.postDelayed(csRunnable2, 5000);
}
Runnable csRunnable2 = new Runnable()
{
#Override
public void run()
{
intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
public void onBackPressed()
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}
#Override
protected void onStop() {
super.onStop();
handler.removeCallbacks(csRunnable2);
}
}
As, Chris mentioned, Declare your HANDLER globally as,
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
handler = new Handler();
handler.postDelayed(csRunnable2, 5000);
}
Here in this Line,
handler.postDelayed(csRunnable2, 5000);
You are calling your "csRunnable2", after 5 seconds, So, it will come up after 5 seconds until unless,
=> You destroy your instance of handler class completely or ,
=> Make all the references Null.
So, When ever you are closing or pausing your activity(as in onBackPressed(), onPause(), onStop(), onDestroy() etc.,.) make sure to call :
handler.removeCallbacksAndMessages(null);
before you start next Activity.
This will makes null of all Handler instances.
For eg., in your code you can call,
public void onBackPressed()
{
handler.removeCallbacksAndMessages(null);
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null);
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}

How to start Activity for result from IME

I'm developing an app that should return some text to the app that started the intent.
But the app that starts the intent is a IME/soft Keyboard. So StartActivityForResult is not available because an IME is a service.
How can I achieve this?
What I got so far:
Keyboard:
final Intent intent = new Intent("com.example.helloworld.GETTEXT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.putExtra("keyboard", true);
startActivity(intent);
Other App:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
} else {
finish();
}
}
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("test", "PASSED");
setResult(RESULT_OK, data);
super.finish();
}
You can use ResultReceiver.
Look at this example, it's pretty clear explains how it works.
You could use a ResultReceiver for this is think.
ResultReceiver lReceiver = new KeyboardResultReceiver(aListener);
final Intent intent = new Intent("com.example.helloworld.GETTEXT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.putExtra(EXTRA_RESULT_RECIEVER, lReceiver);
intent.putExtra("keyboard", true);
startActivity(intent);
private static final class KeyboardResultReceiver extends ResultReceiver {
public FileUploadResultReceiver() {
}
#Override
protected void onReceiveResult(int aResultCode, Bundle aResultData) {
//Do your thing here you can also use the bundle for your data transmission
}
}

Categories

Resources