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

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

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");

Is there a way to make custom lookup on dialog field on Microsoft Dynamics 365?

I have problems with my dialog field. I have button that opens dialog tab with field. It was supposed to show on that field lookup exact records(i guess i need select there by one field value). Right now i have this code:
DialogField Journal = dialog.addField(extendedTypeStr(JournalId));
This dialog line adds a field with all values on that EDT. I have 3 journal types - NEW, UPDATE, DELETE. Right now on that field lookup it shows me all 3 journal types. I want to make custom lookup that shows exact type , example - if i click that button on journal that has type "NEW", then it should show only "NEW" type of journal types on lookup. I heard there is something like dialog.addLookup or something. Can someone help me?
You already added your dialog field (in the dialog() method). Now add the dialogRunPost() method that is executed after the form GUI is initialized. At that point you can fetch the underlying FormStringControl behind the dialog field. Subscribing to the FormStringControl.OnLookup event allows you to override the lookup.
I did not have some journal data available, so I created a similar example with customers. My example dialog (MyDialog) takes a source customer (customerCaller) and shows a dialog with a custom lookup that only shows customers with the same customer group.
My example is also a standalone, runnable class and is not called from a form. Comments have been added to indicate where this affects the code.
Full example
public class MyDialog extends Runbase
{
// fields
protected Args args;
protected CustTable customerCaller;
protected DialogField dfCustomerId;
// construct
public static MyDialog newArgs(Args _args)
{
MyDialog ret = new MyDialog();
ret.args = _args;
return ret;
}
// initialize
public boolean init()
{
boolean ret = super();
// validate and fetch caller
if (args.record() && args.record().TableId == tableNum(CustTable))
//if (args.caller() && args.caller().dataset() == tableNum(CustTable)) --> when called from form
{
customerCaller = args.record();
//customerCaller = args.caller().record();
}
else
{
throw error(Error::missingRecord('My Dialog'));
}
return ret;
}
// build dialog
public Object dialog()
{
Dialog ret = super();
// optional reference to visualize the input
ret.addText('Caller customer group = ' + customerCaller.CustGroup);
// add field
dfCustomerId = ret.addField(extendedTypeStr(CustAccount)); // default lookup = all CustTable.AccountNum values
return ret;
}
public void dialogPostRun(DialogRunbase dialog)
{
super(dialog);
// subscribe to lookup event
FormStringControl fscCustomerId = dfCustomerId.control();
fscCustomerId .OnLookup += eventhandler(this.customerId_OnLookup);
}
// custom lookup for customer id
protected void customerId_OnLookup(FormControl _sender, FormControlEventArgs _e)
{
// cancel default
FormControlCancelableSuperEventArgs eventArgs = _e;
eventArgs.CancelSuperCall();
// define lookup query (list all customers with same customer group as input customer)
Query query = new Query();
QueryBuildDataSource qbds = SysQuery::findOrCreateDataSource(query, tableNum(CustTable));
SysQuery::findOrCreateRange(qbds, fieldNum(CustTable, CustGroup)).value(SysQuery::value(customerCaller.CustGroup));
// do lookup
SysTableLookup lookup = SysTableLookup::newParameters(tableNum(CustTable), _sender);
lookup.parmQuery(query);
lookup.addLookupfield(fieldNum(CustTable, AccountNum), true);
lookup.addLookupfield(fieldNum(CustTable, CustGroup));
lookup.performFormLookup();
}
// run dialog
public static void main(Args _args)
{
// I am running this dialog directly (not from a form), generating some random input
CustTable customer;
select firstonly customer where customer.CustGroup != '';
_args.record(customer);
// end of random input
MyDialog md = MyDialog::newArgs(_args);
md.init();
if (md.prompt())
{
md.run();
}
}
}
Result

Interacting with Hidden Fields and Actions with Javascript

I am trying to figure out how to get values back and forth between an external javascript library and the Acumatica back end.
Currently I have 2 fields that are hidden (set to hidden on the PXUIField Attribute) and I am picking up their values successfully as follows:
function doSomething() {
var url = px_alls['txtUrl'].value;
var clientId = px_alls['txtClientID'].value;
}
However I am not having the same luck setting a hidden fields values and then posting the data to the back end in this way:
client.on('someEvent', (data) => {
px_alls['txtId'].value = data.id;
Save();
})
How can I accomplish this?
Thanks
-Kyle
Reading form fields from px_alls works fine but I was not able to automate saving.
I use action callback to send the values from JavaScript to an action defined in the Graph.
var ds = px_alls['ds'];
ds.executeCallback('TestAction', 'parameter value');
Then In the graph you can use the parameter value to update the document:
public PXAction<PrimaryDAC> TestAction;
[PXButton]
[PXUIField(DisplayName = "Test Action")]
public virtual IEnumerable testAction(PXAdapter adapter)
{
string parameterValue = adapter.CommandArguments;
// Update document here with parameter value
return adapter.Get();
}

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.

Activity that runs for once is not coming again when user close that app

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();
}

Resources