EditText is always returning a null value - android

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

Related

variables need to be saved

I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.

Why isn't this shared preference being persisted on screen rotation?

Order of calls according to logcat is onCreate, setViewValues, setStrikethroughFlag, (ROTATE), onCreate, setViewValues:
SharedPreferences mSettings;
Editor spEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
....
mSettings = getSharedPreferences("prefs", "")
spEditor = mSettings.edit();
setViewValues();
}
public void setViewValues() {
boolean isStrikeThru = mSettings.getBoolean(STRIKETHROUGH, false);
Log.d("TRACE", "setViewValues, strikethrough " + isStrikeThru);
}
public void setStrikethroughFlag() {
spEditor.putBoolean(STRIKETHROUGH, true);
spEditor.commit();
}
The logcat says setStrikethroughFlag() is called. Then I rotate the screen, onCreate and setViewValues are called. In setViewValues, I thought it would recognize the saved value of STRIKETHROUGH, true. But the logcat trace says the value of isStrikeThru is false.
Try calling the setViewValues() from the Constructor. In Screen orientation change, the oncreate of the activity will gets called again and resets your values.
From know i can see, that you creating local variable in your onCreate()
And in your setViewValues() you accessing your class field variable.
So i am not sure that you are calling getSharedPreferences() on your field variable.
The same is about your spEditor. Fix this and try one more time.
If this will not help you, give as the rest of your code.
UPDATE
Try this mSettings = getSharedPreferences("prefs", Context.MODE_PRIVATE);
The mistake was using quotes around the key when storing my shared preference. The keys didnt match so nothing was persisted, sorry.

application gets crashed while using shared preferences [duplicate]

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

How do I save the content view of my activity?

Alright so in my activity i changed my content view from one to another as you can see. so i was wondering how to save the content view that was there last when my activity was closed.
public class Levels extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
setContentView(R.layout.levels);
final EditText anstext1 = (EditText) findViewById(R.id.anstext1);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = anstext1.getText().toString();
if(result.equals("they"))
setContentView(R.layout.social);
else
Toast.makeText(getApplicationContext(), "Wrong", Toast.LENGTH_LONG).show();
}
});
}
}
setContentView
You should call this method only once in the Activity lifecycle.
Saving State
Most of the time you will save your models using onSaveInstanceState and restore them using the bundles generated from that method. Activity, Fragment and Views have these kind of methods build in.
Persisting state
If you are required to use the data for a longer period than the current app lifecycle you can use one of the following mechanisms:
SharedPreferences
SQL-lite DB
File I/O
Create a variable that has the type of R.layout.levels. Assuming R.layout.levels is a RelativeLayout: RelativeLayout rl;
Initialize it like this:
rl = (RelativeLayout) getLayoutInflater().inflate(R.layout.levels,null);
setContentView (rl);
If you want to save the variable for when the activity is destroyed you can put it in a custom Application class and retrieve it from there. You find here how to do it at "maintaining global state" : http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android
I don't know if it is good or bad to do this, but it could be a solution for what you're asking.

Android: Set Widgets Once Only using FindViewById

Right now, every time I want to access a widget I use:
mEditText1 = (EditText) findViewById(R.id.edittext1);
And then perform the action I would like to on the widget.
However, I am wondering if I am able to store a reference to a widget and use that reference multiple times in different methods within the activity, without having to always call findViewById...
I've tried the following:
public class MyActivity extends Activity {
public static String ACTIVITY_NAME = "MyActivity";
EditText mEditText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(this.APP_NAME, "In " + ACTIVITY_NAME);
mEditText1 = (EditText) findViewById(R.id.edittext1);
setContentView(R.layout.main);
prefillFieldsIfNecessary();
}
private void prefillFieldsIfNecessary(){
if(AppPreferences.checkExistence(MyActivity.this, AppPreferences.Name)) {
mEditText1.setText(AppPreference.Name);
}
However, my app just crashes and I get a NullPointerException, which I know speaks to the mEditText1.setText() line, because when I comment that out, my app runs fine.
Asha, this should work and is completely valid. How do you know it's not working? Are you getting an error? Is textToSave not being populated appropriately?
Check if you're declaring "EditText mEditText1;" after your import statements and before your class declaration. Also specify an access modifier, not specifying an access modifier to a class field is not good. It would be nice if you can post a full example of your Activity, so that we can see if you're declaring "EditText mEditText1;" as a class member or variable.
Edit:
Move
setContentView(R.layout.main);
right after
super.onCreate(savedInstanceState);
and you'll be fine. Generally try to have those 2 lines
on top of your onCreate() and do all logic, after those 2 lines.

Categories

Resources