Saving a string from first run to later start an activity - android

I have 4 activities in my android app.
1) Splash Activity - To decide if the app is being launched for the first time and to decide which activity to open
2)Main Activity - Button to open camera and start scanning i.e go to QR activity
2) QR Activity - Scan a QR code
3) Web Activity - On successful scanning, open a web page in the app. Use the data from the QR code to make a URL for the web page
In my splash activity, I check if it is the first run. If it is, I got to the main activity and if not, I want to go to the web activity. In my QR activity, I scan QR code and get a number from it. I use this number in the next activity, i.e, web activity to make a url using the scanned number and open the web page, But now, since I want to start different activity depending on the app run number, I want to save the scanned number from the first activity for all future runs of the app. Much like Facebook, which stores our login credentials for all future runs.
I am trying to do something like this, but the scanned value is not passed to my web activity
ScannerActivity.java
public static final String PREFS_NAME = "myPrefs";
if (barcodes.size() != 0) {
Intent intent = new Intent(getApplication(), WebActivity.class);
//intent.putExtra("result",barcodes.valueAt(0));
SharedPreferences.Editor editor=settings.edit();
editor.putString("result", barcodes.valueAt(0).displayValue);
editor.commit();
startActivity(intent);
finish();
}
WebActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String result = settings.getString("result", "");
/*Barcode barcode = (Barcode) getIntent().getParcelableExtra("result");
Toast.makeText(WebActivity.this, barcode.displayValue, Toast.LENGTH_LONG).show();*/
Toast.makeText(WebActivity.this, result, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(" http://url?u="+result);
}

You're recommended to visit Android Studio Storage Option to have an enlarged perception of the mechanism and functionality
that being said, allow me to provide you with a snippet of how I store values in my application
Note you need to make minor adjustments, since I am applying Sharedpreferences inside a fragment
first
addusername = (EditText) oView.findViewById(R.id.addnewUsername);
second
//adjustment and reattachment
String bonsiour = addusername.getText().toString().trim();
SharedPreferences sPref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = sPref.edit();
edt.putString("key1", bonsiour);
edt.commit();
//toast to confirm value has been saved
String buzo = sPref.getString("key1", "empty");
Toast.makeText(getActivity(), "You're " + buzo + "!!", Toast.LENGTH_LONG).show();
This is how to extract/read from it
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("key1", "No name defined");
if(name.equals("PDF_FOUND")){
Toast.makeText(Controller.this,"IT WORKED !", Toast.LENGTH_SHORT).show();
//skip the splash screen and move to another activity asap
} else{
Toast.makeText(Controller.this,"BAD NEWS !", Toast.LENGTH_SHORT).show();
//display Splash screen
}
}

You can use SharedPreferences to store your String and re-use it later
If you want to store a String for example, first create keys to get your values
public static final String sharedPreferencesKey = "shareKey";
public static final String stringKey = "stringKey";
To store your value
SharedPreferences sharedpreferences =
context.getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putString(stringKey, "");
ed.apply();
To get your value
if (sharedpreferences.contains(stringKey))
sharedPreferences.getString(stringKey, "")

To store your String in shared preferences, you can do the following in a one liner:
String QRCode = "code";
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("QRCode", QRCode).commit();
To retrieve the value of your stored String, use this:
//The second parameter for getString() is the default value to return if QRCode is not set
String QRCode = PreferenceManager.getDefaultSharedPreferences(this).getString("QRCode", "NOT_FOUND");
if(QRCode.equals("NOT_FOUND")){
//open MainActivity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
//open WebActivity
Intent intent = new Intent(this, WebActivity.class);
//you can pass code to webactivity or retrieve it from shared prefs
intent.putExtra("QRCode", QRCode);
startActivity(intent);
}

Related

How to pass data from a Fragment to Fragment to Activity

So basically I'm trying to pass an EditText String to another fragment which is in the same Activity. Then pass that data to another Activity, depending on which button the pressed. My problem is the application works fine but I just don't see the string being created. I've tried to use a textview just to check if it works when I pass it through the first data, but nothing shows.
I just want to pass the string to another fragment then depending on the button they press pass it on the whichever Activity.
This is my code
Passing my Data to the next Fragment and going to the fragment.
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ItemStorageFragment.class);
intent.putExtra("itemName", addName.getText().toString());
((AddInventoryActivity)getActivity()).ToExpiration(null);
}
});
Grabbing the data from my First Fragment
Intent intent = getActivity().getIntent();
value = intent.getStringExtra("itemName");
Then Sending it to the Activity
mToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(getActivity(), FreezerActivity.class);
in.putExtra("itemNameToFreezer", value);
startActivity(in);
}
});
Then Adding it to my RecyclerView
Intent i = getIntent();
String string = i.getStringExtra("itemNameToFreezer");
mDataset.add(string);
mAdapter.notifyDataSetChanged();
Intent extras are fine to share data between Activities, but you cannot use them for Fragments directly, as you did in your code. I assume, you are a beginner, so I recommend you read in depth about Intents here: Android - Intents and Filters
There are several ways of passing data between Activities and Fragments, most common of which is passing arguments. Yet, in your situation I'd recommend using SharedPreferences. You can store String data at any point inside your Fragment or Activity and then easily take it out with these simple steps:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}

1 User Multiple Accounts 1 android app transfer data from login activity to splashscreen activity

I'm developing an app where user must be able to switch between his accounts. As of now I'm able to allow the app with one account log in. How can I allow the user to create an another account and then switch between them in my android app?
update:-
I'm able to auth by Google button (firebase)
I want to do something like this in my app!
In my login.class I stored the value of UID which i got from firebase. Now i want to send this data to my splashscreen where it will check if uid==null then it will redirect to login and if uid !=null then it will redirect to MainActivity.
login.class
String MyPREFERENCES = "MyPrefs" ;
String uid = "uidKey";
SharedPreferences sharedpreferences = login.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("uid", UID);
editor.putBoolean("is_logged_before",true); //this line will do trick
editor.commit();
Toast.makeText(login.this,"uid:"+UID,Toast.LENGTH_LONG).show();
String uid1 = sharedpreferences.getString("uid", "");
Log.i("shareduser",uid1);
Intent i = new Intent(login.this,splashScreen.class);
i.putExtra("message",uid1);
startActivity(i);
splashscreen
public class splashScreen extends Activity {
private static int SPLASH_TIME_OUT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
/*Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Log.i("received uid",message);*/
Intent homeIntent = new Intent(splashScreen.this, login.class);
startActivity(homeIntent);
finish();
}
},SPLASH_TIME_OUT);
}
}
The scope of your answer is very wide. Please ask only genuine doubts related to programming only.
Looks like you need to implement Auto-Login of the User. For this you need to use Shared Preferences.
After successful login of the user, store the username and password in the shared preferences.
Then when the user again tries to login you need to check the sharedPref to check for the username and password.
Moreover it again depends on the type of authentication you are implementing as you can also get the Session Id for the user.
Check this answer for that
Also for Account Picker check this answer

close previous Activity and open new activity on Item click

Hi everyone,
I have created a listview which is available on left side. On each item click opens new activity opens but when I traverse among listitems the new activity does not open after first attempt. I have closed the present activity in each case with finish() method. but it does not seems to work. here is code snippet ..let me know if anybody could help..appreciated
if (listname.equalsIgnoreCase("Time Table")) {
intent = new Intent(getApplicationContext(), TimeTable.class);
startActivity(intent);
Attendance.this.finish();
} else if (listname.equalsIgnoreCase("Announcements")) {
intent = new Intent(getApplicationContext(), Announcement.class);
startActivity(intent);
Attendance.this.finish();
}
I found the solution for my own problem, the issue was that I was not forwarding the some needed values to next activity such as userid, password etc. So I used SharedPreferences to pass the needed values on other activities. Here is example ..I hope it can be useful for others.
This is now created and committed shared preference
SharedPreferences prefs = getSharedPreferences("ABCPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserId", login);
editor.putString("password", password);
editor.putString("IsInside", Inside);
editor.putString("UserType", "S");
editor.commit();
To access values through shared preference, It is simple
String listname = ((TextView)view).getText().toString();
String userid = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("UserId", login);
String paswrd = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("password", password);

Saving information after closing the app

I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.
Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}
use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.
#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}

How to ensure the data remain in an activity after clicking a button to another page then return to current page?

I've an application where a user creates events. The user need to retrieve a certain name from an activity which is a ListView of names list.
I'm having an issue with making sure that a name should remain in an activity after clicking a date button which links to another activity(calendar activity), then return back to the current activity.
My codes of the 3 pages:
Create_Events.java - codes for getting a certain name from ListView activity and the btnDate onClickListener which links to the another activity(calendar activity)
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
String date = bundle.getString("date");
txtDate.setText(date);
}
Bundle b = getIntent().getExtras();
if(b != null)
{
String name = bundle.getString("name");
txtName.setText("Create an event for:" +name);
}
buttonDate = (Button) findViewById(R.id.btnDate);
buttonDate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent calIntent = new Intent(Create_Events.this, Calendar_Event.class);
startActivity(calIntent);
}
});
ContactsList.java -- the ListView of the names which is passed to the Create_Events page.
Cursor cursor = null;
cursor = (Cursor) l.getItemAtPosition(position);
Intent intent = new Intent(ContactsList.this, Create_Events.class);
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
startActivity(intent);
I need help with this. Any help provided will be greatly appreciated. Thanks in advance! =)
you can get this behavior by saving you current screen state,
you can either use shared preferences or other ways (xml,data base, ..),
this way before you leave the activity (onPause) you save any information you need..
and on (onResume) if the information exists (its not the first time the activity loads),
collect the data and put it on screen..
if this is too much for you and you only need the name string to save,
try doing this :
How to declare global variables in Android?
hope it helps...
okay what i understand from your question is you want to retain your data on screen after coming back from another activity.
like Activity A--> Activity B--> Activity A
so, set in menifest file for activity A
android:launchmode="singletop"
and, when you are coming back from Activity B to Activity A
set
Intent intent=new Intent(ActivtyB.this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
you can use SharedPreferences to store the name while use bundle to store the date.
From contactLists.java add these codes
private void SavePreferences(String key, String value)
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences()
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String name = sharedPref.getString("name", "");
}
Then set the name to the textView which will show on the listView. And then load the preference in the create_events page and the name will be shown even when you go to another activity.
Do inform me if you still have any questions. (:

Categories

Resources