0

I have created a setting in the Settings menu that allows a user to enter their name. What I need to know now, is how to display that name. I have pretty much everything done except displaying the name to the right of the nameLabel. Any help is greatly appreciated.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >

<!-- The bill amount -->

<TextView
    android:id="@+id/billAmountLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="@string/bill_amount_label"
    android:textSize="20sp"
    android:textStyle="bold" />

<EditText
    android:id="@+id/billAmountEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/billAmountLabel"
    android:layout_marginLeft="5dp"
    android:layout_toRightOf="@+id/billAmountLabel"
    android:ems="8"
    android:inputType="numberDecimal"
    android:text="@string/bill_amount"
    android:textSize="20sp" >

    <requestFocus />
</EditText>

<!-- The tip percent -->

<TextView
    android:id="@+id/percentLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/billAmountLabel"
    android:layout_below="@+id/billAmountLabel"
    android:padding="10dp"
    android:text="@string/tip_percent_label"
    android:textSize="20sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/percentTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/percentLabel"
    android:layout_alignLeft="@+id/billAmountEditText"
    android:padding="5dp"
    android:text="@string/tip_percent"
    android:textSize="20sp" />

<Button
    android:id="@+id/percentDownButton"
    android:layout_width="45dp"
    android:layout_height="45dp"
    android:layout_alignBaseline="@+id/percentTextView"
    android:layout_marginLeft="25dp"
    android:layout_toRightOf="@+id/percentTextView"
    android:text="@string/decrease"
    android:textSize="20sp" />

<Button
    android:id="@+id/percentUpButton"
    android:layout_width="45dp"
    android:layout_height="45dp"
    android:layout_alignBaseline="@+id/percentDownButton"
    android:layout_toRightOf="@+id/percentDownButton"
    android:text="@string/increase"
    android:textSize="20sp" />

<!-- the tip amount -->

<TextView
    android:id="@+id/tipLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/percentLabel"
    android:layout_below="@+id/percentLabel"
    android:padding="10dp"
    android:text="@string/tip_amount_label"
    android:textSize="20sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/tipTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/tipLabel"
    android:layout_alignLeft="@id/billAmountEditText"
    android:padding="5dp"
    android:text="@string/tip_amount"
    android:textSize="20sp" />

<!-- the total -->

<TextView
    android:id="@+id/totalLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/tipLabel"
    android:layout_below="@+id/tipLabel"
    android:padding="10dp"
    android:text="@string/total_amount_label"
    android:textSize="20sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/totalTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/totalLabel"
    android:layout_alignLeft="@+id/tipTextView"
    android:padding="5dp"
    android:text="@string/total_amount"
    android:textSize="20sp" />

<TextView
    android:id="@+id/nameLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/totalLabel"
    android:padding="10dp"
    android:text="Name"
    android:textSize="20sp"
    android:textStyle="bold" />
<TextView
    android:id="@+id/nameTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/nameLabel"
    android:layout_alignLeft="@+id/nameLabel"
    android:padding="5dp"
    android:text=""
    android:textSize="20sp" />

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen 
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:key="pref_remember_percent"
    android:title="@string/remember_percent_title"
    android:summary="@string/remember_percent_summary"
    android:defaultValue="true" />
<ListPreference
    android:key="pref_rounding"
    android:title="@string/rounding_title"
    android:summary="@string/rounding_summary"
    android:dialogTitle="@string/rounding_title"
    android:entries="@array/rounding_keys"
    android:entryValues="@array/rounding_values"
    android:defaultValue="@string/rounding_default" />
<EditTextPreference
    android:defaultValue="Default value"
    android:key="pref_name"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:text="Enter Name"
    android:title="Name" />
</PreferenceScreen>

MainActivity.java

import java.text.NumberFormat;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class TipCalculatorActivity extends Activity 
implements OnEditorActionListener, OnClickListener {

// define variables for the widgets
private EditText billAmountEditText;
private TextView percentTextView;   
private Button   percentUpButton;
private Button   percentDownButton;
private TextView tipTextView;
private TextView totalTextView;
private TextView nameTextView;
private TextView username;

// define instance variables that should be saved
private String billAmountString = "";
private float tipPercent = .15f;
private String nameLabel;

// define rounding constants
private final int ROUND_NONE = 0;
private final int ROUND_TIP = 1;
private final int ROUND_TOTAL = 2;

// set up preferences
private SharedPreferences prefs;
private boolean rememberTipPercent = true;
private int rounding = ROUND_NONE;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tip_calculator);

    // get references to the widgets
    billAmountEditText = (EditText) findViewById(R.id.billAmountEditText);
    percentTextView = (TextView) findViewById(R.id.percentTextView);
    percentUpButton = (Button) findViewById(R.id.percentUpButton);
    percentDownButton = (Button) findViewById(R.id.percentDownButton);
    tipTextView = (TextView) findViewById(R.id.tipTextView);
    totalTextView = (TextView) findViewById(R.id.totalTextView);
    nameTextView = (TextView) findViewById(R.id.nameTextView);

    // set the listeners
    billAmountEditText.setOnEditorActionListener(this);
    percentUpButton.setOnClickListener(this);
    percentDownButton.setOnClickListener(this);

    // set the default values for the preferences
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // get default SharedPreferences object
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String username = 
PreferenceManager.getDefaultSharedPreferences(this).getString("pref_name", 
"No name");
nameTextView.setText(username);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_tip_calculator, menu);
    return true;
}

@Override
public void onPause() {
    // save the instance variables       
    Editor editor = prefs.edit();        
    editor.putString("billAmountString", billAmountString);
    editor.putFloat("tipPercent", tipPercent);
    editor.commit();        

    super.onPause();      
}

@Override
public void onResume() {
    super.onResume();

    // get preferences
    rememberTipPercent = prefs.getBoolean("pref_remember_percent", true);
    rounding = Integer.parseInt(prefs.getString("pref_rounding", "0"));

    // get the instance variables
    billAmountString = prefs.getString("billAmountString", "");
    if (rememberTipPercent) {
        tipPercent = prefs.getFloat("tipPercent", 0.15f);
    } else {
        tipPercent = 0.15f;
    }

    // set the bill amount on its widget
    billAmountEditText.setText(billAmountString);

    // calculate and display
    calculateAndDisplay();
}

public void calculateAndDisplay() {        
    // get the bill amount
    billAmountString = billAmountEditText.getText().toString();
    float billAmount; 
    if (billAmountString.equals("")) {
        billAmount = 0;
    }
    else {
        billAmount = Float.parseFloat(billAmountString);
    }

    // calculate tip and total
    float tipAmount = 0;
    float totalAmount = 0;
    float tipPercentToDisplay = 0;
    if (rounding == ROUND_NONE) {
        tipAmount = billAmount * tipPercent;
        totalAmount = billAmount + tipAmount;
        tipPercentToDisplay = tipPercent;
    }
    else if (rounding == ROUND_TIP) {
        tipAmount = StrictMath.round(billAmount * tipPercent);
        totalAmount = billAmount + tipAmount;
        tipPercentToDisplay = tipAmount / billAmount;
    }
    else if (rounding == ROUND_TOTAL) {
        float tipNotRounded = billAmount * tipPercent;
        totalAmount = StrictMath.round(billAmount + tipNotRounded);
        tipAmount = totalAmount - billAmount;
        tipPercentToDisplay = tipAmount / billAmount;
    }

    // display the other results with formatting
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    tipTextView.setText(currency.format(tipAmount));
    totalTextView.setText(currency.format(totalAmount));

    NumberFormat percent = NumberFormat.getPercentInstance();
    percentTextView.setText(percent.format(tipPercentToDisplay));
}

@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    int keyCode = -1; 
    if (event != null) {
       keyCode = event.getKeyCode();
    }
    if (actionId == EditorInfo.IME_ACTION_DONE ||
        actionId == EditorInfo.IME_ACTION_UNSPECIFIED ||
        keyCode == KeyEvent.KEYCODE_DPAD_CENTER || 
        keyCode == KeyEvent.KEYCODE_ENTER) {
        calculateAndDisplay();
    }        
    return false;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.percentDownButton:
        tipPercent = tipPercent - .01f;
        calculateAndDisplay();
        break;
    case R.id.percentUpButton:
        tipPercent = tipPercent + .01f;
        calculateAndDisplay();
        break;
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_settings:
            // Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(), 
SettingsActivity.class));
            return true;
        case R.id.menu_about:
            // Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(), 
AboutActivity.class));
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

}

user2441911
  • 17
  • 1
  • 6

2 Answers2

1

You can read the value of name from EditTextPreference element like below

String username = PreferenceManager.getDefaultSharedPreferences(this).getString("pref_name", "No name");

And then display it in the TextView like this

nameTextView.setText(username);
Onur A.
  • 3,007
  • 3
  • 22
  • 37
  • And that would go in the MainActivity.java correct? – user2441911 Mar 12 '18 at 14:01
  • yes, but goes into which method depends on when you want to display it. – Onur A. Mar 12 '18 at 14:10
  • Now it just displays "false" over the nameLabel – user2441911 Mar 12 '18 at 14:15
  • that's what the user stores into the pref_name EditTextPreference – Onur A. Mar 12 '18 at 14:16
  • When I enter my name into the EditTextPreference it still displays "false" and not my name. – user2441911 Mar 12 '18 at 14:36
  • on which view you enter your name? what is its id? – Onur A. Mar 12 '18 at 14:43
  • In the EditTextPreference that I have set to pref_name – user2441911 Mar 12 '18 at 14:45
  • It cannot deliver "false". It can deliver "Default value" or "No name" if called like ......getString("pref_name", "No name"). And then only if nothing is filled in by the user. Show the code you use please. Adapt your post. – greenapps Mar 12 '18 at 15:04
  • You nowhere set a value for String nameLabel. You nowhere set a text in nameTextView. So what did you update? And you nowhere set the value of String username in any gui element. – greenapps Mar 12 '18 at 15:11
  • The "false" text is gone now, that was an error on my part. Now, it still does not show the name in "nameTextView" – user2441911 Mar 12 '18 at 15:12
  • You should use the line `nameTextView.setText(username);`. – greenapps Mar 12 '18 at 15:14
  • I did set a value for nameLabel, it is in the strings.xml file. I didn't set text in the nameTextView because it is supposed to be blank until a user puts their name in the Name field that I created in the settings menu. Like my original post says. – user2441911 Mar 12 '18 at 15:16
  • You should add that line in your code. Already two people told you to do so. How many should tell you yet? – greenapps Mar 12 '18 at 15:17
  • @greenapps I don't know where I'm supposed to put it, and when I put it in the MainActivity.java code I get an error "cannot resolve method 'setText(android.widget.TextView)' – user2441911 Mar 12 '18 at 15:18
  • If you want to keep it blank until there is a name then use "" as default value. Simple! – greenapps Mar 12 '18 at 15:19
  • Stop being rude, I accidentally hit the enter key. – user2441911 Mar 12 '18 at 15:23
  • @user2441911 the place where you put `nameTextView.setText(username) `is correct but you should define username out of `onCreate()` method, i.e where you define other variables. – Onur A. Mar 12 '18 at 15:26
  • @OnurA. I thought I did with "private TextView username;" – user2441911 Mar 12 '18 at 15:28
  • `Stop being rude, ` ??? So you are calling someone who already tries to help you for half an hour rude? Strange attitude. – greenapps Mar 12 '18 at 15:34
  • Yes, I am. Because you're not waiting for my response before you type something else. I have that line of code in my code and it throws the above error. – user2441911 Mar 12 '18 at 15:42
  • @user2441911 that one was different, you should have two one is TextView and the other is plain String, of course with different names – Onur A. Mar 12 '18 at 15:43
1

Your Preferences will save their value in your app's default SharedPreference object when the user changes the value in the UI. You can access that default SharedPreference from anywhere using the PreferenceManager. For example in your MainActivity's onCreate():

SharedPreferences sharedPreferences =
                    PreferenceManager.getDefaultSharedPreferences(this);

To avoid checking for new values frequently you register a handler that is notified when a preference changes (e.g. by a user). In this example the activity sets itself as the handler:

sharedPreference.registerOnSharedPreferenceChangeListener(this);

Therefore your activity would have to implement this interface:

public class MainActivity extends AppCompatActivity
    implements SharedPreferences.OnSharedPreferenceChangeListener {

Finally, you implement onSharedPreferenceChanged:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    String username = sharedPreferences.getString("pref_name", "default");
    textView_username.setText(username);
}

"pref_name" is the preference key you declared in your preferences.xml.

After all the activity that's interested in a settings change might look something like this:

public class MainActivity extends AppCompatActivity
    implements SharedPreferences.OnSharedPreferenceChangeListener {

    TextView textView_username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        textView_username = findViewById(R.id.textView_username);
        SharedPreferences sharedPreferences =
            PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreference.registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        String username = sharedPreferences.getString("key", "default value");
        textView_username.setText(username);
    }
}
Tobias Uhmann
  • 2,757
  • 2
  • 25
  • 35