How to skip second activity after first run forever? - java

I am working on one app which contain SplashScreen.java my first activity. After that its show LoginActivity.java for login. And my LoginActivity.java class eventually start SplashActivity.java. I want after login first time everytime i start my app SplashScreen.java calls SplashActivity.java instead of LoginActivity.java. For this i made some changes in my SplashScreen.java class but its not working fine.
SplashScreen.java Class-
public class SplashScreen extends Activity
{
private long splashDelay = 5000; //5 seconds
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Anyone else help me. Now the only problem after first run. App start from SplashActivity instead of starting from SplashScreen.

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
Boolean Exist=pref.getBoolean("activity_executed", false);// Check is user logged in or not
if(Exist)// if allready logged in then forward it to Splash Activity
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else // Not logged in
{
Handler handler = new Handler();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 2000L);
}
Runnable runnable = new Runnable() {
public void run() {
new AsyncParsing().execute();
}
};
private class AsyncParsing extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
Log.d("Splash Activity", "In pre execute");
}
#Override
protected Void doInBackground(Void... params) {
Log.d("Splash Activity", "In do in backgriund ");
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.d("Splash Activity", "In post execute");
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
}

Step 1 : Declare this in ur login class
SharedPreferences pref;
SharedPreferences.Editor editor;
Step 2 :Declare In onCrete method
pref = getSharedPreferences("login", MODE_PRIVATE);
editor = pref.edit();
Step 3 : OnClick of submit button in login page paste the lines below
:
String check=pref.getString("selected", "nil")
if(check.equals("TRUE"))
{
Intent intent=new Intent(this,splash.class);
startActivity(intent);
}
Step 4: put this where u r getting the success message when user credentails and db credentials matches.
editor.putString("selected", "TRUE");
editor.commit();

#John check and just refer this working code, i hope,it help u,
setContentView(R.layout.main);
pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Log.v("","onCreate is calling");
if(pref.getBoolean("activity_executed", false))
{
Log.v("","Before if called");
setContentView(R.layout.menu_frame);
Log.v("","after if called");
new Handler().postDelayed(csRunnable1, 3000);
}
else
{
new Handler().postDelayed(csRunnable2, 3000);
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
Runnable csRunnable1=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, SplashActivity.class);
startActivity(intent);
finish();
}
};
Runnable csRunnable2=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
};

I would think you have a logic problem there. Should be if not executed, run it and mark as executed.
if(!pref.getBoolean("activity_executed", false)) {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}

The problem is that calling finish does not stop the rest of onCreate from being executed. You need to put a return statement after:
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();

You missing I hope It will solve your problem
public class SplashScreen extends Activity
{private long splashDelay = 5000; // 5 seconds
/** Called when the activity is first created. */
TimerTask task = new TimerTask() {
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(Test.this,
LoginActivity.class);
startActivity(mainIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF",
Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
}

// try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run() {
timer.cancel();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
finish();
}
};
timer.schedule(task, splashDelay);
}
}

Related

Android using shared preferences to check on first run

Hi I'm trying to detect whether my app has been opened for the first time. If it has, I need to run an activity and once it's opened for the second time it should not show it again.
This is my code:
fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
But all it does is start the activity and when I start it again it freezes in a white screen but checking the logs it shows like the else statement is constantly running over and over. I'm fairly new to Android so some help or advice would be greatly appreciated
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}
It looks like your activity is looping because within your else statement, you tell it to restart the activity which lands again in the else statement and so on and so on.
Try using editor.commit if editor.apply not working
editor.putBoolean("firstRun", false);
editor.apply(); // Save all changed settings
editor.commit(); // Save all changed settings
In else case your starting "MainActivity.class".
Why your loading MainActivity from the oncreate of MainActivity ?
it will make a loop.
Remove the start activity from else case.
Try this approach:
public class MainActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstRun", true)) {
Intent intent = new Intent(MainActivity.this, TutorialFeaturedActivity.class);
startActivity(intent);
prefs.edit().putBoolean("firstRun", false).commit();
}
else
{
//do nothing
}
getSpecials();
}
}
Please Try this my friend
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "ManageRun";
private static final String KEY_IS_RUN = "isRun";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLatest(boolean isRun) {
editor.putBoolean(KEY_IS_RUN, isRun);
// commit changes
editor.commit();
Log.d(TAG, "Manage Version session modified!");
}
public boolean isLatest() {
return pref.getBoolean(KEY_IS_RUN, true);
}
}
**In first Activity Check **
private SessionManager session;
session = new SessionManager(getApplicationContext());
if (session.isLatest()) {
session.setLatest(false);
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
return firstTime;
}
if (isFirstTime()) {
Intent i = new Intent(SplashActivity.this, Intro_slider.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
final UserFunctions uf = new UserFunctions();
if (uf.isUserLoggedIn(SplashActivity.this)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, Social_Login_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
Try this code.

How to use SharedPreferences for splash activity to launch once

I want to launch splash activity only once using SharedPreference, how it could be happen. any help will be highly appreciated. Thanks
Thread thread;
MediaPlayer audio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
if (first_run == true){
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
audio.release();
}
}
};
thread.start();
}
}
try this:
Declare
public static final String MyPREFERENCES = "MyPrefs";
public static final String ID = "idKey";
SharedPreferences sharedPreferences;
Now in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
String first = (sharedPreferences.getString("First", ""));
if (!first.equals("true")) {
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("First", "true");
editor.commit();
finish();
audio.release();
}
}
};
thread.start();
}
}
Instead of sharedprefrence ,i would like to suggest you to use static boolean value like - isFirstTime and set it true by default and on second activity (next to splash) set it to false. Whenever you kill app static value will become dead.Check in onCreate of Splash -
if(!isFirstTime){
goToNextActivity();
}else{
//continue splash code
}
If you want to use shared preference then use same Logic ,take a boolean value and save it in shared pref -
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
and in next activity simply set it to false or clear value. by calling editor.clear(); and put a check in splash if shared pref has some value or have isFirstTime and do next code accordingly.

how to make same instance as new instance to top of the stack when same instance is running in android

Here the group chat activity is running currently. Group chat activity means chat window. in that chat window i retrieved the message from sqlite and showed by list view adpater. Here i am doing group chat for one event when new message is arrived for other event the notification issued. When i click the notification my group chat activity is not executed again even if i passed the intent from other class or activity.
This is my groupchatActivity code
#Override
protected void onStart() {
super.onStart();
if (activeEventMO != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processExtraData();
}
private void processExtraData() {
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
setContentView(R.layout.chat_main);
EventMO eventMO = new EventMO();
context = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
//this activeEventMO is a static object
processExtraData();
// activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
//this for loop is for avoiding the notification coz notification also stores groupchat table in sqlite
for (ChatMO chatMO1 : chatMOs) {
chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
/* if (!sharedpreferences.getString("MessageMO", "null").equals("null")) {
MessageMO messageMO1 = (MessageMO) gson.fromJson(sharedpreferences.getString("MessageMO", "null"), new TypeToken<MessageMO>() {
}.getType());
eventMO.setEventId(messageMO1.getEventId());
Log.e("shared","eventID"+messageMO1.getEventId());
Log.e("shared","eventID"+eventMO.getEventId());
eventMO.setText(messageMO1.getEventTitle());
Log.i("message values", messageMO1.toString());
ChatMO chatMO = new ChatMO();
//chatMessageObjects.setMessage(messageMO1.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMO1.getfromUserName());
listChatMessageObjectses.add(chatMO);
//listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getUsersForEvent(activeEventMO.getEventId());
}
#Override
protected void onPostExecute(String eventLists) {
eventUserMOs = gson.fromJson(eventLists, new TypeToken<ArrayList<UserMO>>() {
}.getType());
Toast.makeText(getApplicationContext(), "event users " + eventUserMOs.size(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
Button sendButton = (Button) findViewById(R.id.btnSend);
This gcmIntent here i am passing the intent from this gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
//here messageMO having the details of received message here i am setting eventId from messageMO to eventMO
// Inorder to passs gropchatActivity
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify((int) (long) messageMO.getEventId(), mBuilder.build());
You need to do couple of things to achieve the result.
Set launch mode of groupchatactivity to SingleTask
Override onNewIntent() method in groupchatactivity
Call setIntent(intent) for new received intent in onNewIntent()
Reflect as appropriate on above answer.

killing a task in android by handler

I am scheduling few functions by using timer handler.This is what happens.
When i press the button the timer starts sending sms and it opens another activity.
Then in the another activity i have put the stop button to terminate the timer and return back to main activity.
The timer terminates but it crashes the app and return back to main activity.
Here is the code
MainActivity.java
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
The next activity is this
maps.java
public class maps extends FragmentActivity implements LocationListener {
MainActivity maine= new MainActivity();
GoogleMap googleMap;
Button stop;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.maps);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View aView)
{
maine.stoptimertask(aView);
Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
startActivityForResult(toAnotherActivity, 0);
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
}
});
i created an object of mainactivity and called the stoptimertask method. The app crashes with this log cat :-
FATAL EXCEPTION: main
Process: com.example.textmessage, PID: 27301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.example.textmessage.MainActivity.stoptimertask(MainActivity.java:129)
at com.example.textmessage.maps$1.onClick(maps.java:42)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
What i want is when the button stop is pressed in maps.java, the sending sms function should stop and it should return back to MainActivity.java
You can't create an Activity by using new. It will not be a valid activity. Only the Android framework can create a valid Activity object. To start a new Activity, call startActivity. WHile using new to create an Activity will compile, that object will not be properly initialized and weird crashes will result.
The maine.stoptimertask(aView); does not contain the correct instance.
Basically you have to in your
stop.setOnClickListener (new View.OnClickListener ()
{
public void onClick(View aView)
{
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
this.finish();
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
}
});
returning to MainActivity the value you want to go there and implement a
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 0) { // because you startActivityForResult(toAnotherActivity, 0);
// Make sure the request was successful
if (resultCode == RESULT_OK) {
stoptimertask(); // forget view you don't need
}
}
}
to find out that there was an action in your activity maps.
See documentation for getting a result from an Activity in this link:
http://developer.android.com/training/basics/intents/result.html

Open tutorial on first run doesn't work properly

I have a tutorial in my app showing up when a user runs it for the first time
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (firstRun == true) {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
firstRun = false;
}
}
}, 200);
I have delayed it because without a delay i just get a black screen (the interface doesn't have the time to load)
But doing so i get the Tutorial.class opened many times, what am i doing wrong?
EDIT:
Here is some more code, i won't paste all of it since it would be only too long to read and it wouldn't be relevant to the problem
I save my preferences like this
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label1", label1S);
editor.putString("Label2", label2S);
editor.commit();
}
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.commit();
}
Here is how i restore them inside the onCreate();
// Restore previous settings and data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int counterRestored = settings.getInt("Counter1", 0);
int counter2Restored = settings.getInt("Counter2", 0);
boolean firstRunRestored = settings.getBoolean("FirstRun", true);
String label1Restored = settings.getString("Label1", "Counter 1");
String label2Restored = settings.getString("Label2", "Counter 2");
counter = counterRestored;
counter2 = counter2Restored;
firstRun = firstRunRestored;
label1S = label1Restored;
label2S = label2Restored;
renameLabel();
calculateTotal();
This is my second activity Tutorial.class
public class Tutorial extends MainActivity{
ImageButton btnSkip, btnSkip2, btnNext, btnNext2;
RelativeLayout tutorial, tutPage1, tutPage2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
btnSkip = (ImageButton) findViewById(R.id.btn_skip);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnSkip2 = (ImageButton) findViewById(R.id.btn_skip2);
btnNext2 = (ImageButton) findViewById(R.id.btn_next2);
tutorial = (RelativeLayout) findViewById(R.id.tutorial);
tutPage1 = (RelativeLayout) findViewById(R.id.page1);
tutPage2 = (RelativeLayout) findViewById(R.id.page2);
btnSkip.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnSkip2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.GONE);
tutPage2.setVisibility(View.VISIBLE);
}
});
btnNext2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.VISIBLE);
tutPage2.setVisibility(View.GONE);
tutorial.setVisibility(View.VISIBLE);
finish();
}
});
}
}
why don't you try
if(firstRun){
firstRun = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
}
}
}, 200);
}
The value of firstRun will not be stored persistantly over several runs.
You should store this value in SharedPreferences so that it will retain its value even after the app has been closed. You can find a tutorial on how to use SharedPreferences here.

Categories

Resources