I am unable to get Shared Preferences of other application - android

I am new to Android.I am trying access SharedPreferences of one application in another application.
But i am not getting those values.
My code was posted below.
Create.java in SharedPref1
package com.example.sharedpref1;
public class Create extends Activity implements OnClickListener{
EditText et1,et2;
Button btn;
String LogID,Pwd;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
et1 = (EditText)findViewById(R.id.etC1);
et2 = (EditText)findViewById(R.id.etC2);
btn = (Button)findViewById(R.id.bCreate);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bCreate)
{
LogID = et1.getText().toString();
Pwd = et2.getText().toString();
Toast.makeText(getApplicationContext(), "User Profile Createad With\nUser ID: "+LogID +"\nPassword: "+Pwd, Toast.LENGTH_LONG).show();
SharedPreferences.Editor store = loginDetails.edit();
store.putString("logid", LogID);
store.putString("pass", Pwd);
store.commit();
finish();
}
}
}
Show.java in SharedPref2
package com.example.sharedpref2;
public class Show extends Activity implements OnClickListener{
EditText log,pwd;
Button back;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
log = (EditText)findViewById(R.id.etid);
pwd = (EditText)findViewById(R.id.etPwd);
back = (Button)findViewById(R.id.bBack);
back.setOnClickListener(this);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
log.setText(loginDetails.getString("logid", "defValue"));
pwd.setText(loginDetails.getString("pass", "defValue"));
}
}
I am getting values as below

I am trying access SharedPreferences of one application in another application.
This is a bad idea. Quoting the documentation for MODE_MULTI_PROCESS:
SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
(emphasis added)
Moreover, the only way this could possibly work is if you make the SharedPreferences MODE_WORLD_READABLE, which means any app can get to those preferences. Programmers with talent would not do this, but would use other IPC mechanisms that would limit the communications to between the two applications and only with user permission, so as to not leak user data to others.
Finally, you do not have any code that will work across processes. getSharedPreferences() will get preferences for your own process. The only way I can think of to get a SharedPreferences from another process would require calling getSharedPreferences() on a Context created via createPackageContext(), and I haven't tried this, as I wouldn't dream of implementing what you are proposing.

If you need to share content between applications I would suggest using a content provider and not SharedPrefrences. In my experience SharedPrefernces is unreliable in these situations.
MODE_WORLD_READABLE is depracated in API level 17.
http://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE

Related

How to know the last launch time of an app

Hi After doing lots of Search , I could not find the answer of a question, that seems somewhat simple.
I have multiple apps installed on device. Is there any way of finding the last launching date of all apps?
You could put the time and date in an SharedPref when the app opens.
Then, the next time you open the app the app reads the SharedPref and displays it.
Something like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar c = Calendar.getInstance();
SharedPreferences sp = this.getPreferences(Context.MODE_PRIVATE);
String lastLaunch = sp.getString("launch", "First launch!");
SharedPreferences.Editor editor = sp.edit();
editor.putString("launch", c.getTime().toString());
editor.commit();
}
The String lastLaunch is the last time it launched! If it's the first time the string is: "First launch!"
I hope that i have helped you a little bit :)
Based on your requirements from the comments above, I'm providing a method to share the launch times between a bunch of our apps using SharedPreferences.
Firstly, we need to allow our apps to share local storage so they can access preference data. For this, we use the sharedUserId property in the app manifest. This can be your own unique string and each of the apps that share the space must have this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.myapp"
android:sharedUserId="string.user.id.here">
...
</manifest>
Secondly, we use the Application class to determine when the app comes to the foreground and when it does, write the timestamp in Context.CONTEXT_IGNORE_SECURITY mode to share between our apps:
public class MyApp extends Application implements ActivityLifecycleCallbacks {
private boolean appInBg;
private int TIMEOUT = 5000;
private Handler mHandler = new Handler();
#Override
public void onActivityResumed() {
if (appInBg) {
writeToPref();
} else {
mHandler.cancelCallbacksAndMessages(null);
}
}
#Override
public void onActivityPaused() {
mHanlder.postDelayed(new Runnable() {
#Override
public void run() {
appInBg = true;
}
}, TIMEOUT);
}
...
private void writeToPref() {
SharedPreferences prefs = myContext.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
prefs.edit().putInt("last_run", System.currentTimeMillis()).apply();
}
}
Here, we allow a buffer time of 5 seconds to switch between screens. This should be adequate in most cases.
Finally, we can read the written SharedPreference value as follows:
Context context = createPackageContext("example.com.myapp", 0);
SharedPreferences pref = context.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
int lastLaunch = pref.getString("last_run", System.currentTimeMillis());
// Similarly, for other apps.
Hope this solves your issue.

Checking if Shared Preferences Exist

Trying to check if if Shared Preferences exist or not. What I need is to allow the user to arrive on a page if they have been here before (i.e. shared preferences exist and are not equal to "") or put them to the welcome page if it is their first time on the app (i.e. shared preferences are blank as user hasn't entered any data).
public class PersonalDetails extends Activity {
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_details);
if (sharedPreferences.contains("")) {
Intent intent = new Intent(PersonalDetails.this, Welcome.class);
startActivity(intent);
}
I think getPreferences needs two inputs as below.
public abstract SharedPreferences getSharedPreferences(String name,
int mode);
// Example
getSharedPreferences("your_app_name", MODE_PRIVATE);

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Make and store string? [duplicate]

This question already has answers here:
Making data persistent in android
(2 answers)
Closed 10 years ago.
I got some help here today to make a string, which gets displayed after pressing the button:
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
And it gets displayed with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
But i noticed that that is only temporarily. As soon as i leave the app or go to an other activity, the string gets reset..
My question is: How can i store the local string to a real string and thus display it on other activities and even after the app gets closed?
Is it something with strings.xml?
Thanks
Is it something with strings.xml?
No - This is read only and used during compile.
How can i store the local string to a real string and thus display it on other activities and even after the app gets closed?
What you are talking about is persistent storage. You have 3 main options (there are others but as this is quite a broad topic I shall keep things simple):
Store it in a file
Save the string to a file and load it when the app starts or where ever you need it.
See this SO post on reading/writing text files Android write file
Use SharedPreferences
SO Post showing code on this android read/write user preferences
Probably the best answer for storing a simple string and easy to code. If you start your Activity and there is no intent passed in then you can load the string from SharedPreferences.
mTextview.setText(getIntent().getStringExtra("mytext"));
becomes
final String myString = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE).getString("SOME_STRING", "Default if not found");
mTextview.setText(myString);
The above is purely to demonstrate and probably needs tidying up and refining for your own needs.
Use a Database
Probably the worst option for you but worth thinking about. If you begin to have more than one String or complex option then SQLite is built into Android.
A good tutorial is found here http://www.vogella.com/articles/AndroidSQLite/article.html
I prefer to use Shared Preferences to store value.
MainActivity.java
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
SharedPreferences sp = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("mytext", text);
editor.commit();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
startActivity(myIntent);
}
});
Calculated.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("mytext",null););
}

Creating Arrays which can save text in android and be able to open them

Now I know this may be a lot to ask for. But what I want to do is have the ability to save and open notes. Now currently I am able to save and load data on the phone to be opened the next time the app is open with this code here:
public class Notes extends Activity{
EditText savedText;
TextView dataResults;
public static String stringFolder = "SharedData";
SharedPreferences String;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setupVariables();
String = getSharedPreferences(stringFolder, 0);
}
private void setupVariables(){
savedText = (EditText) findViewById(R.id.notes_text_view);
dataResults = (TextView) findViewById(R.id.notes_text_view);
}
public void saveNotes(View v)
{
String stringData = savedText.getText().toString();
SharedPreferences.Editor editor = String.edit();
editor.putString("SharedData", stringData);
editor.commit();
}
public void loadNotes(View v){
String = getSharedPreferences(stringFolder, 0);
String dataReturned = String.getString("SharedData", "Could not load");
dataResults.setText(dataReturned);
}
Now what I am hoping to do is every time the user clicks save it adds the text entered into an array under a name which the user can enter. When the user clicks load I want a list view to pop up showing all the names of the notes which have previously been saved and click on one to load it. i know this is a lot to ask but I'm wondering if anyone out there knows. Or there might be a very simple way to do this. I am very much a beginner to android.
Thanks, Reid
It seems like you want to display a dialog with EditText on saving and a dialog with ListView on loading. Basics on creating dialogs can be found here. See also this question.

Categories

Resources