In the Android application I'm working on, I have one activity where the user inputs data that is saved using SharedPreferences, and is used for certain calculations on the main activity. An issue I'm having is that after saving the data, the changes do not actually take effect until after the application is restarted. Is there a way I can make it so the variables associated with these SharedPreferences are updated before restarting?
Here is where I save the data in a separate activity.
saveBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedWeight", weightString).commit();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedAge", ageString).commit();
//Intent i = new Intent("com.williammiller.capstonelapv2.MainActivity");
//startActivity(i);
finish();
}
});
And here is where I'm checking in the main activity to see what they are
String age = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedAge", "25");
String weight = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedWeight", "200");
startBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "weight = " + weightInt + " age = " + ageInt, Toast.LENGTH_LONG).show();
}
});
You can use a BroadcastReceiver to achieve that. Do as following:
Register a BroadcastReceiver in your Main Activity:
public static final String UPDATE_ACTION = "yourpackage.update";
public static final String EXTRA_KEY_AGE = "key_age";
public static final String EXTRA_KEY_WEIGHT = "key_weight";
private BroadcastReceiver mReceiver;
// In the onCreate() method
mReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UPDATE_ACTION)){
// Here you get the update data from another activity
String age = intent.getStringExtra(EXTRA_KEY_AGE);
String weight = intent.getStringExtra(EXTRA_KEY_WEIGHT);
}
}
};
registerReceiver(receiver, new IntentFilter(UPDATE_ACTION ));
// Add the following code to onDestroy() method
unregisterReceiver(mReceiver);
Send a broadcast in your "separate activity":
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
Intent intent = new Intent(MainActivity.UPDATE_ACTION );
intent.putExtra(MainActivity.EXTRA_KEY_AGE, ageString);
intent.putExtra(MainActivity.EXTRA_KEY_WEIGHT, weightString );
sendBroadcast(intent);
}
Update: Change part of the code to unregister the BroadcastReceiver when activity is destroyed.
Related
I'm making a chat app and using intent service for sending messages to firebase database even after activity is destroyed. When the uploading is successful i want to clear text in Edittext in the IntentService class but don't know how to do it.
Acivity class code
Intent sendmsgService = new Intent(getApplicationContext(),SendMessageService.class);
sendmsgService.putExtra("msg",message);
sendmsgService.putExtra("time",time);
sendmsgService.putExtra("cuser",current_user);
sendmsgService.putExtra("otheruser",otherusername);
startService(sendmsgService);
IntentService class code
public class SendMessageService extends IntentService {
DatabaseReference msgDatabase , mDatabase;
String current_user,otherusername,message,time;
public SendMessageService() {
super("SendMessageService");
mDatabase = FirebaseDatabase.getInstance().getReference();
msgDatabase = mDatabase.child("messages").child(current_user).child(otherusername);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
assert intent!=null;
message = intent.getStringExtra("msg");
time = intent.getStringExtra("time");
current_user = intent.getStringExtra("cuser");
otherusername = intent.getStringExtra("otheruser");
DatabaseReference push_database = msgDatabase.push();
String msg_push = push_database.getKey();
DatabaseReference d = FirebaseDatabase.getInstance().getReference();
String cuser = current_user+"/"+otherusername+"/";
String ouser = otherusername+"/"+current_user+"/";
Map<String,Object> chatitems = new HashMap<>();
chatitems.put("seen",false);
chatitems.put("msg",message);
chatitems.put("from",current_user);
Map<String,Object> msgitemmap = new HashMap<>();
chatitems.put("time", ServerValue.TIMESTAMP);
msgitemmap.put("servertime",ServerValue.TIMESTAMP);
msgitemmap.put("time",time);
msgitemmap.put("msg",message);
msgitemmap.put("from",current_user);
msgitemmap.put("to",otherusername);
msgitemmap.put("seen",false);
msgitemmap.put("key",msg_push);
Map<String,Object> chatmap = new HashMap<>();
chatmap.put("chatlist/"+cuser,chatitems);
chatmap.put("chatlist/"+ouser,chatitems);
chatmap.put("messages/"+cuser+msg_push,msgitemmap);
chatmap.put("messages/"+ouser+msg_push,msgitemmap);
d.updateChildren(chatmap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Here i want to clear the edittext
}
});
}}
If any other solution please suggest.
Intent service runs on background thread not on main(UI) thread but we can use the Handler mechanism to send/update data to activity.
To send data to activity you need to declare handler in your activity like:
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle reply = msg.getData();
// do whatever with the bundle here
}
};
in the intent service class pass data in this way:
Bundle bundle = intent.getExtras();
if (bundle != null) {
Messenger messenger = (Messenger) bundle.get("messenger");
Message msg = Message.obtain();
msg.setData(data); //put the data here
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.i("error", "error");
}
}
Most Important invoke the intent service from activity to pass handler to it:
Intent intent = new Intent(this, IntentService1.class);
intent.putExtra("messenger", new Messenger(handler));
startService(intent);
Hope this will help you
Simple solution is to use Broadcast Reciever Declare this in your activity class
BroadcastReceiver broadCastNewMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do your stuff here
edittext.setText("");
}
};
Now in onCreate() register this
registerReceiver(this.broadCastNewMessage, new IntentFilter("uploading_done"));
And in onDestroy()
unregisterReceiver(broadCastNewMessage);
Now Call this method from the service class where u want to update the activity
sendBroadcast(new Intent().setAction("uploading_done"));
So I'm trying to save a value to sharedpreferences by a click of a button, and then see which value it is in another activity. (to basically set a background for activity2 based on which button they pressed in activity1)
Saving code:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
background.remove("selectedBG");
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putInt("selectedBG", 1);
background.commit();
}
if(btn2 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 2);
Toast.makeText(this, "btn2", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn3 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 3);
Toast.makeText(this, "btn3", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn4 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 4);
Toast.makeText(this, "btn4", Toast.LENGTH_SHORT).show();
background.commit();
}
}
And then, the Toast here always shows "chosenbackground:0":
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
LLayout=(LinearLayout)findViewById(R.id.llayout);
SharedPreferences background2 = getSharedPreferences("Background", MODE_PRIVATE);
int chosenBackground = background2.getInt("selectedBg", 0);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
if (chosenBackground != 0) {
if(chosenBackground==1)
{
LLayout.setBackgroundColor(Color.WHITE);
}
if(chosenBackground==2)
{
LLayout.setBackgroundColor(Color.rgb(34,34,34));
}
if(chosenBackground==3)
{
LLayout.setBackgroundColor(Color.rgb(51,68,85));
}
if(chosenBackground==4)
{
LLayout.setBackgroundColor(Color.rgb(68,34,17));
}
}
}
Answer for your question is that you have misspelled the key in second activity, in first one you are using "selectedBG" but in the second one "selectedBg". It is not the same, it's case sensitive. Correct in the second one for "selectedBG" and it should work.
Using the SharedPreferences here it's really bad idea, if u only want to pass a background or rather a color if I see it correctly. Just pass it in intent:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("EXTRA_BACKGROUND_ID", background);
startActivity(intent);
Access that intent on next activity for eg. in onCreate()
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
#Updated
public class PreferencesUtils {
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor prefsEditor;
public static final String KEY_BACKGROUND = "BACKGROUND";
public PreferencesUtils(Context context) {
this(context, PREFS_DEFAULT);
}
public PreferencesUtils(Context context, String prefs) {
this.sharedPrefs = context.getSharedPreferences(prefs, Activity.MODE_PRIVATE);
this.prefsEditor = sharedPrefs.edit();
}
public int getValue(String key, int defaultValue){
return sharedPrefs.getInt(key, defaultValue);
}
public boolean saveValue(String key, int value){
prefsEditor.putInt(key, value);
return prefsEditor.commit();
}
}
PreferencesUtils preferencesUtils = new PreferencesUtils(this);
preferencesUtils.saveValue(PreferencesUtils.KEY_BACKGROUND, 1); //saveValue
preferencesUtils.getValue(PreferencesUtils.KEY_BACKGROUND, 0); //getValue,
second arg is defult if not found
Use if (!background2.contains("selectedBg"))
to check ,first whether the key exists and if not getInt is not able to create a key and hence always returns default value 0.Also you can use apply() instead of commit to check whether commit has taken place successfully.Debug the code more to see all possibilities
int chosenBackground=0;
if (!background2.contains("selectedBg"))
{
//is called once when after you freshly install the app
background2.putInt("selectedBG", 0);
}
else
chosenBackground = background2.getInt("selectedBg", 0);
I am using following UsbSerial example from below link https://github.com/felHR85/SerialPortExample. I want receive data from over usb from the device shown in the photo.
Device is basically a counter machine which is sending counter data over serial port.
I am able to connect device and open port from it but unable to read data stream from it. Below is the code used. code is not giving any error
Mainactivity class
public class MainActivity extends AppCompatActivity {
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
private TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
display = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
Button sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("")) {
String data = editText.getText().toString();
if (usbService != null) { // if UsbService was correctly binded, Send data
display.append(data);
usbService.write(data.getBytes());
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
mActivity.get().display.append("Handle:");
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().display.append(data);
break;
}
}
}
}
I know it's bit late, however just to help others who might come across similar issue, did you find solution to your problem? If not, I cannot see the other java file corresponding to the service (USBService.java) as described in the example referred by you. The same file contains following code snippet which you would like to debug to find out what's going wrong (could be a problem with byte to string conversion or so). Hope this helps.
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback()
{
#Override
public void onReceivedData(byte[] arg0)
{
try
{
String data = new String(arg0, "UTF-8");
if(mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT,data).sendToTarget();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
};
I am new in android development. i want my application to directly launch MainActivity if the User has already registered. how can i do this.
this is my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
Button btnTip, btnApp, btndos, btnAbout, btnServices;
ConnectionDetector cd;
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
public static String contact;
public static String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Dental Application");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnTip = (Button) findViewById(R.id.tips);
btndos = (Button) findViewById(R.id.dos);
btnApp = (Button) findViewById(R.id.appointments);
btnAbout = (Button) findViewById(R.id.about);
btnServices = (Button) findViewById(R.id.services);
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please check your Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
contact = i.getStringExtra("contact");
imei = i.getStringExtra("imei");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId, contact, imei);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
btnTip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TipsActivity.class);
startActivity(intent);
}
});
btndos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DosActivity.class);
startActivity(intent);
}
});
btnApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BookAppointmennts.class);
startActivity(intent);
}
});
btnAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AboutUsActivity.class);
startActivity(intent);
}
});
btnServices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ServicesActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
//lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver", "> " + e.getMessage());
}
super.onDestroy();
}
}
and the RegisterActivity
public class RegisterActivity extends Activity {
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
// UI elements
EditText txtName;
EditText txtEmail;
EditText txtContact;
// Register button
Button btnRegister;
String imei;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtContact = (EditText) findViewById(R.id.contact);
btnRegister = (Button) findViewById(R.id.btnRegister);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = mngr.getDeviceId();
/*
* Click event on Register button
* */
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Read EditText dat
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String contact = txtContact.getText().toString();
// Check if user filled the form
if (name.trim().length() > 0 && email.trim().length() > 0 && contact.trim().length()>0) {
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
i.putExtra("contact", contact);
i.putExtra("imei", imei);
startActivity(i);
finish();
} else {
// user doen't filled that data
// ask him to fill the form
alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
}
}
});
}
}
i am using GCM. the user is first registered and MainActivity is Displayed. Next time when the user opens the application i want directly MainActivity to be displayed. how can i do this. Can anyone please help me.
You will have to make LauncherActivity like SplashScreen in which check from shared prefrences or sqlite data that user is already registered or not
then by checking this transfer to corresponding activity.
If the user is not registered then show Registration Screen and when user register then save info in Sqlite or sharedpreferences or any other way.
If the user is already registered the show HomeScreen
First of all just post only the code that needs modification, you've posted all of the code in that Java file of yours. We could be more helpful if your code isn't cluttered.
I have two activities, LoginActivity and MainActivity.
LoginActiviy is the launcher Activity, its purpose is to check whether the user is signed in or not if he's signed in; go to MainActivity.
Although I set android:noHistory="true" to LoginActivity the activity's onResume(LoginActivity) is called again when user exits(means onPause called) the program and launch it again.
Did I misunderstood what noHistory means ? if so what can I do to make the OS forget about the existence of LoginActivity?
EDIT : I tried to put this on LoginActivity's onResume , but it calls MainActivity's onCreate, which I don't want
if(!firstTime) {
goToMainActivity();
}
LoginActivity :
public class LoginActivity extends Activity {
protected static final String PASSED_TWITTER = "mosaed.thukair.alsafytooth.LoginActivity";
private static final String TAG = "mosaed.thukair.alsafytooth.LoginActivity";
protected static final int RESULT_BROWSER = 0;
private SharedPreferences prefs;
private Twitter twitter;
private RequestToken requestToken;
private AccessToken accessToken;
private String authUrl;
private Button login;
private boolean firstTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
firstTime = true;
if(isAuthenticated()) {
Log.i(TAG, "splash screen");
setContentView(R.layout.splash_screen);
String token = prefs.getString(Constants.OAUTH_TOKEN, "");
String tokenSecret = prefs.getString(Constants.OAUTH_TOKEN_SECRET, "");
Log.i(TAG, "oauth login");
OAuthLogin(token, tokenSecret);
} else {
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.connect_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i(TAG, "clicked");
LoginActivity.this.setContentView(R.layout.splash_screen);
OAuthLogin();
}
});
}
}
private boolean isAuthenticated() {
String token = prefs.getString(Constants.OAUTH_TOKEN, "");
if(token.equals(""))
return false;
String secret = prefs.getString(Constants.OAUTH_TOKEN_SECRET, "");
if(secret.equals(""))
return false;
return true;
}
private void OAuthLogin() {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
requestToken = twitter.getOAuthRequestToken(Constants.CALLBACK_URL);
authUrl = requestToken.getAuthenticationURL();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
Log.i(TAG, "open browser");
LoginActivity.this.startActivity(myIntent);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
private void OAuthLogin(final String token, final String tokenSecret) {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
AccessToken accessToken = new AccessToken(token, tokenSecret);
twitter.setOAuthAccessToken(accessToken);
return null;
}
#Override
protected void onPostExecute(Void param) {
goToMainActivity(twitter);
}
}.execute();
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
if ((this.getIntent() != null) && (this.getIntent().getData() != null)) {
setContentView(R.layout.splash_screen);
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
Uri uri = LoginActivity.this.getIntent().getData();
afterBrowser(uri);
return null;
}
#Override
protected void onPostExecute(Void uri) {
storeAccessToken();
goToMainActivity(twitter);
}
}.execute();
} else if(!firstTime) {
goToMainActivity(twitter);
}
}
private void afterBrowser(Uri uri) {
String verifier = uri.getQueryParameter("oauth_verifier");
String token = uri.getQueryParameter("oauth_token");
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
requestToken = new RequestToken(token, Constants.CONSUMER_SECRET);
accessToken = twitter.getOAuthAccessToken(requestToken,
verifier);
twitter.setOAuthAccessToken(accessToken);
} catch (TwitterException ex) {
Log.e(TAG, "" + ex.getMessage());
}
}
private void storeAccessToken() {
prefs.edit()
.putString(Constants.OAUTH_TOKEN, accessToken.getToken())
.putString(Constants.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret())
.commit();
}
private void goToMainActivity(Twitter twitter) {
firstTime = false;
Intent myIntent = new Intent(this, MainActivity.class);
MyApplication.getInstance().setTwitter(twitter);
startActivity(myIntent);
}
}
if(!firstTime) {
goToMainActivity();
finish();
}
What no history does is that it doesn't let that certain activity register in the stack of past activities, it doesn't allow it to skip parts of the Activity lifecycle.
If you don't want certain code not to execute then you should do something like:
Login Activity:
if(!firstTime) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent. putExtra("skip", true);
finish();
}
Main Activity: (inside onCreate)
if(!getIntent().getBundle().getBoolean("skip", false)) {
//You code that you don't want
}
This is the activity lifecycle I hope it's beneficial to you:
android:noHistory Whether or not the activity should be removed from
the activity stack and finished (its finish() method called) when the
user navigates away from it and it's no longer visible on screen —
"true" if it should be finished, and "false" if not. The default value
is "false". A value of "true" means that the activity will not leave a
historical trace. It will not remain in the activity stack for the
task, so the user will not be able to return to it.
This attribute was introduced in API Level 3.
Quoting the documentation, "it's finish() method called", have you tried finishing the activity yourself?
noHistory = true means once the activity is finish() for that user session, the user will never see it again, however, if the activity is just being paused without finishing, then it will be restarted when going back to it. Before you go to the main activity, just finish() it, if thats your desired behavior.