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););
}
Related
I need to know peoples phone number for the app I'm making, because the app revolves around the phone number. Since I can't find any foolproof way of getting the A Number off a phone, I want the very first time someone opens the app, them to enter their phone number. And I can't seem to find something similar to this on google.
Any lads here that got any ideas on how to make this work?
PS.
I'm rather new to Android programming and programming in general!
You can get the phone number with
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
And in Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
However this wont work all off the time (some comments in similar questions here on SO like this even suggest it hardly works at all).
So what you should do is prompt the user when the app starts, get his input from a textfield or something and store it somewhere you will be able to get it. The best way for you might be to store it in SharedPreferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
String phoneNumber = "";
//save
prefs.edit().putString("phoneNumber", phoneNumber).apply();
//read
phoneNumber = prefs.getString(phoneNumber, "");
Similar to this you can save a bool (putBoolean and getBoolean) after you first started the app, so you can keep track of that. Just set it to false after you got the number and check for it every time you start the app again.
Add a new activity and from AndroidManifest.xml make it the launcher activity
public class PhoneActivity extends Activity {
String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkStatus();
//considering that SliderActivity is your current main activity
if (number.equals("")) { //finish this activity if number already present
Intent sliderIntent = new Intent(PhoneActivity .this,
SliderActivity.class);
startActivity(sliderIntent);
finish();
}
//In xml create an edittext
phoneEditText.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
SharedPreferences.Editor editor = settings.edit();
editor.putString("number", phoneEditText.getText().toString());
Intent sliderIntent = new Intent(PhoneActivity .this,
SliderActivity.class);
startActivity(sliderIntent);
finish();
}
});
}
public void checkStatus()
{
SharedPreferences settings = getSharedPreferences("myPref", 0);
number= settings.getString("number", "");
}
}
Hi please tell me whats wrong in the code I am learning shared preferences and after using them my app is not running it's stopped by displaying unfortunately example stopped.where will be the data stored i am not finding any file related to preferences in DDMS.`
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp=getSharedPreferences(MY_FILE,Context.MODE_PRIVATE);
Editor e=sp.edit();
e.putString("name", textview1.getText().toString());
e.commit();
String name=sp.getString("name","");
Log.i("NAme","name entered:"+ name);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,MenuScreen.class);
startActivity(i);
}
});
}`
You have not initialized textview1. Add something like
textview1 = (TextView)findViewById(R.id.your_textview_id);
after setContentView().
No preferences are saved as the program terminates before the sharedpreferences edit is committed.
To answer the question in the title, the shared preferences are stored under your app package's data directory.
For app crashes, always first have a look at the exception stacktrace in logcat. Include it in the questions you post, too.
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();
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
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.