Activity that runs for once is not coming again when user close that app - android-studio-2.2

i have my app's signup type page which is use for getting details of user and i have made it to run for one time only using sharedpreferences method but i got one problem that if user close that app during filling of details than that activity is not coming again.
setContentView(R.layout.register_data);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
boolean isFirstRun = getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun){
startActivity(new Intent(MainActivity.this, RegisterDetail.class));
.edit()
.putBoolean("isFirstRun", false)
.apply();
}

Check this link
May be it is helpful to you
Some ref
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}

Related

Show different activities based on user choice in Android studio

How can I set my app to behave in such a way that when user arrives on my app for the first time a page appears for them to choose their status?
E.g
Student
Teacher
What I want is for two buttons to appear on that first screen they will see on the app.
So if a user clicks Student, each time he/she opens that app he will always be directed to an activity I designed for just students e.g student_activity layout.
But if the student choose Teacher, each time the app runs it will take the user to teacher_activity layout.
I will be so much thankful to anyone that can provide me with a good to set this on my app.
Plenty thanks as you look into it.
you need to use sharedPrefrences to store the user choice and then check the saved choice when your application is launched
create a SharedInfo class :
public class SharedInformation {
private Context context;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
public SharedInfo(Context c){
context = c;
sharedPreferences =context.getSharedPreferences("login.conf", Context.MODE_PRIVATE);
editor=sharedPreferences.edit();
}
public void setusertype(String type){
editor.putString("type",type);
editor.apply();
editor.commit();
}
public String getusertype(){
return sharedPreferences.getString("type","");
}
public void clearinfo(){
editor.clear();
editor.commit();
}
}
In your main/welcome activity:
SharedInfo sharedinfo = new SharedInfo(this);
if(sharedinfo.getusertype().isEmpty()){ //do nothing let the user pick a choice}
if(sharedinfo.getusertype().equals("student"){
//make an intent to send to student activity
}
if(sharedinfo.getusertype().equals("teacher"){
//make an intent to send to teacher activity
}
//etc
When the user picks a choice for the first time make sure to save it in your SharedInfo class like that :
sharedinfo.setusertype("yourtype");

How to pass data between activities that don't follow one another

I have a scenario where I want to keep the username value I entered in my login activity and send this
value, not to the following activity Intent intent = new Intent(LoginActivity.this, SecondActivity.this), but to another activity further in the appThirdActivity or FourthActivity.
So basically the question is how do you pass data between non successive activities.
Its very simple you can add Shared Preferences in your login activity add the following code
First, make a constant
public static final String USERNAME = "0";//Write this at the start
//Then add this inside a function
SharedPreferences sharedPreferences = getSharedPreferences("username", 0);
Editor editor = sharedPreferences.edit();
editor.putString(USERNAME, username);//username is your username.
editor.apply();
Then maybe in your third/fourth activity add this in function onCreate()
SharedPreferences sharedPreferences = getSharedPreferences("username", 0);
String Username = sharedPreferences.getString(USERNAME, "");
//Now you can use the String Username wherever you want

How to retrieve SharedPreferences string?

While working on an android app, I discovered, that I would have to use SharedPreferences to store login data (url, port, name), but since I am new to this, I am not sure, how to access the data for MQTT to use those inputs and login.
in tab3_fragment.java, the SharedPreferences get set this way:
public void saveData(){
SharedPreferences userDetails = (SharedPreferences) getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userDetails.edit();
editor.putString(url, input_url.getText().toString());
editor.putString(port, input_port.getText().toString());
editor.apply();
Toast.makeText(getActivity(), "Einstellungen gespeichert", Toast.LENGTH_SHORT).show();
}
public void loadData(){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
text_url = userDetails.getString(url, " ");
text_port = userDetails.getString(port, " ");
}
This is how I try to access the SharedPreferences:
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
final String url = userDetails.getString(tab3_fragment.url, " ");
final String port = userDetails.getString(tab3_fragment.port, " ");
String strArray2[] = {url, port};
String serverUri = TextUtils.join(":", strArray2);
Toast.makeText(getActivity(), serverUri, Toast.LENGTH_SHORT).show();
When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method `getContext()`.
How can I make the MqttHelper access the SharedPreferences?
When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method getContext().
As I can see in your code you are passing the context already by parameter, so I don't see any need to use getContext() there, you can easy use context
Bad
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Good
public MqttHelper(Context context){
SharedPreferences userDetails = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Also I'm seeing that you are displaying a Toast using getActivity() you can use also getActivity() to get the context as an alternative.

How can I display a dialog on Currently visible activity on BroadcastReceiver?

I have a main Activity (OceanintelligenceActivity). In this activity I register the device for push notifications and also I registered a receiver that shows a Dialog and starts the proper Activity depending on the info sent from my server. This is the code I'm using to register the device and the receiver :
protected void gcmRegistration(){
PMApplication thisApp = PMApplication.getInstance();
AppDelegate delegate = thisApp.getAppDelegate();
final Context context = this;
// 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);
// Let's declare our receiver
registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
Log.d("", "Lets register for Push");
GCMRegistrar.register(this, SENDER_ID);
}else {
if(GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
String apnsToken = delegate.sso.getAPNSToken();
if(!apnsToken.equals(regId)){
Log.d("", "The Device RegId has changed on GCM Servers");
// We should let our servers know about this
ServerUtilities.update(regId, context);
}
} else {
Log.d("","Is not register on PM Server");
// 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.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
This is how I set the receiver:
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
Log.d("","BroadcastReceiver onReceive");
notificationIntent = GCMIntentService.getNotificationIntent(context);
new AlertDialog.Builder(context)
.setMessage(newMessage+". Would you like to see it right now?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Show update
startActivity(notificationIntent);
}
})
.setNegativeButton("No", null).show();
}
};
GCMIntentService.getNotificationIntent(context). This line returns the the Intent with the Activity I want to start.
Whenever there is a notification onReceive gets called but the Dialog only shows if I am on the main activity. So if the app is on a different activity, onReceive still gets called but the dialog doesn't show and therefore I can't start the proper activity.
How can I display a dialog on Currently visible activity on BroadcastReceiver?
Playing around with this one and searching on google I came across a solution. It is not the best one but it works. I still can't believe there is not an easy way to get the current context in Android. So this is what I did to manage to show the Dialog regardless of what the current activity is : I have a public static property of type Context on my singleton class(AppDelegate) and on each activity I override the onResume method and set the Context to the current activity like this AppDelegate.CURRENT_CONTEXT = this. Then on my dialog : AlertDialog.Builder(AppDelegate.CURRENT_CONTEXT).....

Outlook add in , text box , delete\backspace not working

I developed an outlook add in (custom task pane), with web browser in the user control.
All the things working well beside the backspace or the delete button when I am writing something in text box in the web browser, I can't use those keys, am I missing something?
I am a few years late to the party but I managed to fix this. The easiest way to fix this is to ensure proper focus is given to the input fields, so you will need to be able to run your own javascript on whatever page is being loaded.
The javascript I run on the page is as follows (using jQuery):
$(document).on("click", function (e) {
// first let the add-in give focus to our CustomTaskPane
window.external.focus();
// then in our web browser give focus to whatever element was clicked on
$(e.target).focus();
});
the window.external variable contains code run from the plugin (c# or VB I assume) which is exposed so we can interact from web page back to the add-in.
In the add-in code for the custom taskpane set the context of window.external:
// event when webBrowser is finished loading document
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// sets context of window.external to functions defined on this context
webBrowser1.ObjectForScripting = this;
}
And a public method for focusing:
// can be called by the web browser as window.external.focus()
public void focus()
{
this.Focus();
}
This worked for me, and I hope it helps others. Although do note that this probably doesn't work if the user keyboard navigates using tab, but you can either extend this code for that use case, or safely assume that the average outlook user will have his hand glued to the mouse.
Ok I solved the problem ,
The problem is that the custom task pane in not always gets fucos from the outlook.
So, I raised an event every time that there is "onclick" for all the pane, and then forced the pane to be in focus.
spent a lot of time trying to get this working in Outlook v16.0.13801.20288 the above did not work for me. I ended up with this working code.
Create a user control and add your webbrowser control to it then customize the .cs as below
private void CreateTaskPane() {
MyWinFormUserControl webBrowser = new MyWinFormUserControl();
webBrowser.webBrowser3.Url = new Uri("https://google.com");
webBrowser.webBrowser3.Width = 500;
webBrowser.webBrowser3.Dock = DockStyle.Fill;
webBrowser.webBrowser3.Visible = true;
webBrowser.Width = 500;
webBrowser.Dock = DockStyle.Fill;
webBrowser.Visible = true;
this.CRMTaskPaneControl = CustomTaskPanes.Add(webBrowser, "My App");
//Components.WebViewContainerWPFUserControl webView = (Components.WebViewContainerWPFUserControl)_eh.Child;
//webView.webview.Source = new Uri("https://localhost:3000");
this.CRMTaskPaneControl.Width = 500;
System.Windows.Forms.Application.DoEvents();
this.CRMTaskPaneControl.Control.Focus();
this.CRMTaskPane.Visible = true;
}
public partial class MyWinFormUserControl : UserControl
{
public WebBrowser webBrowser3;
public System.Windows.Forms.WebBrowser webBrowser1;
public MyWinFormUserControl()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.webBrowser3 = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webBrowser3
//
this.webBrowser3.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser3.Location = new System.Drawing.Point(0, 0);
this.webBrowser3.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser3.Name = "webBrowser3";
this.webBrowser3.Size = new System.Drawing.Size(500, 749);
this.webBrowser3.TabIndex = 0;
this.webBrowser3.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser3_DocumentCompleted);
//
// MyWinFormUserControl
//
this.Controls.Add(this.webBrowser3);
this.Name = "MyWinFormUserControl";
this.Size = new System.Drawing.Size(500, 749);
this.Load += new System.EventHandler(this.MyWinFormUserControl_Load);
this.ResumeLayout(false);
}
void webBrowser3_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument doc;
doc = webBrowser3.Document;
doc.Click += doc_Click;
}
void doc_Click(object sender, HtmlElementEventArgs e)
{
this.Focus(); // force user control to have the focus
HtmlElement elem = webBrowser3.Document.GetElementFromPoint(e.ClientMousePosition);
elem.Focus(); // then let the clicked control to have focus
}
private void MyWinFormUserControl_Load(object sender, EventArgs e)
{
//Control loaded
}
Turns out this is an easy issue to fix.
Just write
class MyBrowser : WebBrowser {}
Then use MyBrowser instead of the .NET one.

Resources