Here, i am trying to call setText method but my application is getting crashed because of some initialization problem.
EditText edittext;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =(ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.logo);
settings= getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if(settings.contains("sharedString")){
String returnString=settings.getString("sharedString","Couldn't load the data");
edittext.setText(returnString);
}
}
edittext is not initialized. Initialize it in onCreate.
In onCreate you have
edittext.setText(returnString); // not initialized in onCreate
You have
edittext =(EditText)findViewById(R.id.edit_message); // initialized in sendMessage
in sendMessage. So you may be setting text to edittext even before it is initialized
Please try with the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =(ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.logo);
edittext = (EditText)findViewById(R.id.edittext);
settings= getBaseContext().getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("sharedString", "Shared Preference Data");
editor.commit();
String returnString=settings.getString("sharedString","Couldn't load the data");
edittext.setText(returnString);
}
Before to use the code first look about thee shared Preferences and their examples.
SharedPreference
SharedPreferences Example
Hope it should work. Please let me know.If it not working means tell me what you want to do actually.
its a very common mistake .. I should initialize the editText before calling a method on it by
edittext =(EditText)findViewById(R.id.edit_message);
Related
I am trying to create a method that saves a score in my app. It was previously in the onCreate method, and I thought that was why every time I started the app the users score was set Back to 0. I have since then changed it to an onStart method (line 14-19) which does the exact same thing. Should I be using a different method? I have successfully saved the score, but would I need to call it back within the onStart method?
public class MainActivity extends Activity implements OnClickListener {
TextView textView1;
EditText editText1;
Button button1;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);}
public void onStart(){
super.onStart();
SharedPreferences score = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = score.edit();
editor.putInt("key", counter);
editor.commit();
textView1 = (TextView)findViewById(R.id.textView1);
editText1 = (EditText)findViewById(R.id.editText1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);}
public void onClick(View v){
if (v == button1){
counter++;
editText1.setText(Integer.toString(counter));
}
}
}
You can use:
1. SharedPreferences or store highscores in a file in storage.
2. Alternately, you can use firbase to store highscores online.
3. Use both of these while keeping in mind internet availability
I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
When i'm calling my editText it returns a Null value
My code is here:
public class LogIn extends Activity {
EditText userNameEditor;
EditText passwordEditor;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.activity_login_screen);
userNameEditor = (EditText)findViewById(R.id.editTextUserName);
passwordEditor = (EditText)findViewById(R.id.passwordEditor);
preferences = getSharedPreferences(User.KEY_FOR_PREFERENCES, MODE_PRIVATE);
userNameEditor.setHint(preferences.getString(User.KEY_FOR_USERNAME, ""));
}
}
I think keep getting a nullPointerException is it because i'm calling setHint in onCreate?
NOTE: thanks everyone for the help. what it was, was i accidentally put in a previous id of the userNameEditor(i changed it) so the one in findViewById and android:id were different lol. never forget to check the little things i suppose
Make sure you call setContentView() before trying to find any views with findViewById(), and of course make sure there is actually a view of the correct type and with the correct ID in the layout.
call this method in your OnCreate() method
super.onCreate(savedInstanceState);
above this line
setContentView(R.layout.activity_login_screen);
Guess one: There is no R.id.editTextUserName at the XML that you are inflating.
Two: you are not setting the content view
If this is your complete code you are missing the call to
setContentView(R.<your_activity_layout>)
so try
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.<layout>);
editTextVar = (EditText)findViewById(R.id.editTextUserName);
SharedPreferences preferences = getSharedPreferences(User.Key_FOR_PREFERENCES, MODE_PRIVATE);
editTextVar.setHint(preferences.getString(User.KEY_FOR_USERNAME, ""));
}
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'm trying to learn how to use SharedPrences to save data.
In the test code below, getString returns no value, instead of 'ted', but I cannot figure out why.
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted");
pre.edit().commit();
String tr;
tr=pre.getString("label","no value");
of course both answers are right but dmon's solution is much more easer and short:)
its enough to rewrite your code like this :
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted").commit();
String tr=pre.getString("label","no value");
Easy, edit() creates an Editor. You're putting the value in one and committing in another one. Just save the edit() return value in an Editor variable and call commit() in that.
Could it be because you re-call the edit() function? try this:
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = pre.edit();
ed.putString("label","ted");
ed.commit();
String tr;
tr=pre.getString("label","no value");
}