In my app I have an edit user details page and I want to display the current name, email address etc in the corresponding editText fields and then the user can just erase that and enter a new one if they want.
Is there a way to do this? Thanks for any help
There is the hint feature? You can use the setHint() to set it, or set it in XML (though you probably don't want that, because the XML doesn't 'know' the name/adress of your user :) )
You can use EditText.setText(...) to set the current text of an EditText field.
Example:
yourEditText.setText(currentUserName);
From the xml:
android:text="yourtext"
You can use text property in your xml file for particular Edittext fields.
For example :
<EditText
android:id="#+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
You can do it in this way
private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "abc#xyz.com";
and inside onCreate method
nameEdit = (EditText) findViewById(R.id.name);
nameEdit.setText(nameDefaultValue);
nameEdit.setOnTouchListener( new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
return false;
}
});
nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
nameEdit.setText(nameDefaultValue);
} else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
}
});
emailEdit = (EditText)findViewById(R.id.email);
emailEdit.setText(emailDefaultValue);
emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
emailEdit.setText(emailDefaultValue);
} else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
emailEdit.setText("");
}
}
});
First you need to load the user details somehow
Then you need to find your EditText if you don't have it-
EditText et = (EditText)findViewById(R.id.youredittext);
after you've found your EditText, call
et.setText(theUserName);
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.et);
EditText et_city = (EditText) findViewById(R.id.et_city);
// Set the default text of second EditText widget
et_city.setText("USA");
}
}
Use android android:hint for set default value or android:text
We wish there is a default value attribute in each view of android views or group view in future versions of SDK. but to overcome that, simply before submission, check if the view is empty equal true, then assign a default value
example:
/* add 0 as default numeric value to a price field when skipped by a user,
in order to avoid parsing error of empty or improper format value. */
if (Objects.requireNonNull(edPrice.getText()).toString().trim().isEmpty())
edPrice.setText("0");
Related
I have tried different things for quite some hours now, but I cannot seem to wrap my head around how to update a TextView when a user inputs a new text through an EditTextPreference in Android.
I use a switch statement in the onSharedPreferenceChanged method, inside an anonymous listener class. However, when i set player1View.setText(value), nothing happens. Is there an easier way of accomplishing this task – namely updating the textView through user input?
Here is the bit of code I cannot make work:
public class SettingsActivity extends AppCompatActivity
{
private TextView player1View;
private TextView player2View;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
player1View = findViewById(R.id.player1);
player2View = findViewById(R.id.player2);
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
createListener();
}
private void createListener()
{
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
EditTextPreference etp = (EditTextPreference) sharedPreferences;
String value = sharedPreferences.getString("player_one", "NULL");
switch(key)
{
case "switch_setting1":
//Do something
break;
case "player1_key":
player1View.setText(value);
break;
case "player2_key":
player2View.setText(value);
break;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}
The screenshots below should emphasize more clearly what i mean. The fields I want to change are the ones named "Player 1" and "Player 2", and to accomplish that the user inputs new names through settings as shown.
Screenshots from the Android Emulator
Try maybe instead of:
String value = sharedPreferences.getString("player_one", "NULL");
This:
String value = sharedPreferences.getString("player_one", null);
or you might want to create two String variables(value, value2 for example), one for "player_one" and the other for "player_two" if you have forgot to add. I don't know exactly what you are trying to build.
Needed some help here. In my map test app I have 2 Autocomplete textViews. First textView gets the address of marker on load as well as chages the address if map is dragged.
But I am struggling for second textView where I need the same feature depending which textView is active.
I tried it like:
private AutoCompleteTextView mFromAddress;
private AutoCompleteTextView mToAddress;
mFromAddress = (AutoCompleteTextView) findViewById(R.id.fromAddress);
mToAddress = (AutoCompleteTextView) findViewById(R.id.toAddress);
// Decoder Coding.. str prints address
if (mFromAddress.isSelected()) {
mFromAddress.setText(str);
} else if (mToAddress.isSelected()) {
mToAddress.setText(str);
}
But no expected results. Even the first textView stops working.
I am new to java and Android Studio. I am looking for some suggestions here.
Try hasFocus() function
if (mFromAddress.hasFocus()) {
mFromAddress.setText(str);
} else if (mToAddress.hasFocus()) {
mToAddress.setText(str);
}
Another way is that define another TextView in code and set it as active TextView when focus change in OnFocusChangeListener
AutoCompleteTextView activeET;
activeET = mFromAddress; // set mFromAddress as active text in start
mFromAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mFromAddress;
}
});
mToAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mToAddress;
}
});
Now you just need to set text to activeET
activeET.setText(str);
Of late I was just trying to create a mems geneator app, yes I had been following the new bostons and in that buckey created them using 2 fragments and here i just want to do in a single main activity, but I just can't figure out how to retrieve the text from the edit text field and set the text of Text view to it. I know it's pretty a newbie question but still I don't know how to code it so please help...
I had just imported some widgets,views,etc and done some modified the on create function and my on create function is:
public class MainActivity extends AppCompatActivity {
public static EditText topText;
public static EditText bottomtext;
public static TextView top;
public static TextView bottom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topText = (EditText) findViewById(R.id.topedit);
bottomtext = (EditText) findViewById(R.id.bottomedit);
top = (TextView) findViewById(R.id.top);
bottom = (TextView) findViewById(R.id.bottom);
Button myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View V) {
top.setText((CharSequence) topText);
bottom.setText((CharSequence) bottomtext);
}
}
);
}
Simply do this:
if(topText.getText()!=null){
top.setText(topText.getText().toString());
}
if(bottomtext.getText()!=null){
bottom.setText(bottomtext.getText().toString());
}
Try this to get text of the EditText field:
CharSequence text = topText.getText();
And set the text above for the textView:
top.setText(text);
Use this short example to understand the concept
store=ret.getText().toString();
show.setText(store);
Explanation
ret: is the name of the edit text field;
store: is used to hold anything gotten from ret (text field)
show.setText(store) displays the result in the textview
This question has already been answered:
"Use getText() on your EditText object".
Get Value of a Edit Text field
Next time do a quick search ;)
I followed steps in how to change value of textview according to selected item and here is a piece of the code
public void onCreate(Bundle savedInstanceState){.......
final TextView privacyTextView = (TextView) findViewById(R.id.eventPrivacy);
privacySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String selectedItem = parent.getItemAtPosition(position).toString();
privacyTextView.setText(selectedItem);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
list is :
<string-array name="privacy_levels">
<item>Everyone</item>
<item>Friends of Friends</item>
<item>Friends Only</item>
<item>Customize</item>
</string-array>
I have text view with value : privacy when running app it's automatically changed to Everyone -frist one on the list- so what is going wrong ?!!!
Add android:prompt in Spinner xml and set a name like
android:prompt="Privacy";
So first time it will show privacy then user can select from the drop down list.
Try this...!
final String selectedItem = parent.getSelectedItem().toString().trim();
privacyTextView.setText(selectedItem);
If you want to get first item as privacy then you need to add another item in your array as Privacy.
There is a attribute called android:spinnerMode this is used to get the spinner in two modes as dialog or dropdown.
where as the attribute android:prompt is to get the spinner Title or Heading after opening it(in Dialog mode).
Just try to this so you will get selected string:
String name = spinner.getSelectedItem().toString();
I'm creating an EditText in onOptionsItemSelected() and trying to get it's information in onClick(). Here's the offending code:
onOptionItemSelected(MenuItem item){
...
EditText mealCalories = new EditText(context);
mealCalories.setId(MealCalId) //in this example it's just an integer 1.
...
}
onclick(View v){
EditText mealCaloriesInBox = (EditText)findViewById(mealCalId);
}
When I haven't selected an item from the menu (and thus haven't called onOptionItemSelected();) it doesn't crash when I click the button. However, when I actually have created the EditText and I click the button it crashes as it's trying to create the instance, giving me the aforementioned error. Any ideas on why it could be doing that?
EDIT
Here's more of my code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
switch(item.getItemId()) {
case R.id.addMeal:
trackMealItems++;
mealCalId++;
mealFatId++;
mealCarbId++;
mealProteinId++;
//the base layout
LinearLayout root = (LinearLayout)findViewById(R.id.linearLayout1);
//make the layout that holds the meal item and add it to the base layout
LinearLayout mealItem = new LinearLayout(context);
mealItem.setId(trackMealItems);
mealItem.setOrientation(LinearLayout.VERTICAL);
mealItem.setLayoutParams(mealItemParams);
root.addView(mealItem);
//make the TextView that holds the name of the meal and add it to the mealItem layout
EditText mealName = new EditText(context);
mealName.setLayoutParams(mealNameParams);
mealItem.addView(mealName);
//make the TextViews that hold the information about the meal and stick them in a
//horizontal LinearLayout
LinearLayout mealStats = new LinearLayout(context);
mealStats.setOrientation(LinearLayout.HORIZONTAL);
mealStats.setLayoutParams(mealStatParams);
mealItem.addView(mealStats);
EditText mealCalories = new EditText(context);
mealCalories.setId(mealCalId);
mealCalories.setLayoutParams(mealStatParams);
mealStats.addView(mealCalories);
EditText mealFat = new EditText(context);
mealFat.setId(mealFatId);
mealFat.setLayoutParams(mealStatParams);
mealStats.addView(mealFat);
EditText mealCarbs = new EditText(context);
mealCarbs.setId(mealCarbId);
mealCarbs.setLayoutParams(mealStatParams);
mealStats.addView(mealCarbs);
EditText mealProtein = new EditText(context);
mealProtein.setId(mealProteinId);
mealProtein.setLayoutParams(mealStatParams);
mealStats.addView(mealProtein);
return true;
case R.id.removeMeal:
LinearLayout removeMe = (LinearLayout)findViewById(trackMealItems);
removeMe.setVisibility(View.GONE);
trackMealItems--;
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v){
EditText mealCaloriesInTextBox = (EditText)findViewById(mealCalId);
}
You seem to be using two different values: MealCalId when you create your EditText and mealCalId when you call findViewById. That's one possible problem. The other is that if you have more than one view with the same id, findViewById will not necessarily return the one you want.
EDIT
At first glance, your code looks like it should work. I don't know what's going wrong, but I have a suggestion for a work-around. When you create the view, instead of assigning it an ID, assign it a tag:
mealCalories.setTag(mealCalId);
(The int value will be autoboxed to an Integer.) Then in your onClick handler, retrieve it by tag:
EditText mealCaloriesInTextBox =
(EditText) getContentView().findViewWithTag(mealCalId);
If there's any kind of funny interaction with view IDs, this technique will avoid them.
If that doesn't work (or if you prefer anyway) you can also try diagnosing the ID-based retrieval using the Hierarchy Viewer.
For those who are having this error for the same reason I did....
Just try cleaning your project and re-building.
Solved it for me.
i tried to run your code and what i found is that
when menu item is not clicked and button is clicked, the edit text is null.
So if you will call any method on this object, it will crash with NULLPointerException
When menu item is clicked and then button is clicked, the edit text is not null so you call any method on this object.