0

I Want to save a message on a textView, not just to display it in another activity. For example if the application is closed the next time when will be open I want to see the message which I added.

I have two activities.

  1. Activity one -> I save the date using SharedPraferences in the variable NAME_RESTAURANT and I sent the date throw method 'getMsg()'

  2. Activity two -> I receive the date and I want to put it into a TextView named etWelcomeToRestaurant2

The date is represented by a string which I get it from a EditText named etDRestaurantName in first Activity.

My problem is that in SecondActivity the date is not displayed.

The activity where I save the date and from where I transmite the date to the Other activity

public class AdminAreaActivity extends AppCompatActivity {

        public static final String SHARED_PREFS = "sharedPrefs";
        public static final String RESTAURANT_NAME = "restaurantName";

        private String NAME_RESTAURANT;
        private EditText etDRestaurantName;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_admin_area);


            etDRestaurantName = findViewById(R.id.etRestaurantName);
            final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);

            bRestaurantChange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!etDRestaurantName.getText().toString().matches("")){
                        Intent mainIntent = new Intent(AdminAreaActivity.this,MainActivity.class);
                        saveData();
                        loadData();
                        etDRestaurantName.getText().clear();
                        startActivity(mainIntent);
                    }
                    else
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
                        builder.setMessage("Failed!")
                                .setNegativeButton("Retry", null)
                                .create()
                                .show();
                    }
                }
            });



        }



        public void saveData(){
            SharedPreferences sharedPreferences =getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString(RESTAURANT_NAME,etDRestaurantName.getText().toString()+"!");
            editor.apply();
            Toast.makeText(this,"Data saved!",Toast.LENGTH_SHORT);

        }

        public void loadData(){
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
            NAME_RESTAURANT = sharedPreferences.getString(RESTAURANT_NAME,"Your Restaurant here!");
        }

        public  String getMsg(){
           return NAME_RESTAURANT;

        }



    }

The activity where I want to put data and where I received it:

public class MainActivity extends AppCompatActivity {

    private TextView etWelcomeToRestaurant2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
        String messg = "Welcome to,\n";
        etWelcomeToRestaurant.setText(messg);

        etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);

        AdminAreaActivity admOBj = new AdminAreaActivity();
        etWelcomeToRestaurant2.setText(((AdminAreaActivity)admOBj).getMsg());

    }


}
Mahdi Moqadasi
  • 2,029
  • 4
  • 26
  • 52
Andrei
  • 49
  • 8
  • 2
    Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Hossam Hassan Jan 03 '19 at 20:40
  • I want so save the date, not just to display it in another activity. For example if the application is closed the next time when will be open I want that the message to be still visible. – Andrei Jan 03 '19 at 20:44
  • you can just set it in sharedpreferences – Hossam Hassan Jan 03 '19 at 20:50
  • I tried that and i did not get the message in the other activity. – Andrei Jan 03 '19 at 21:00

2 Answers2

0

In Android, you never should be using the new operator with an Activity class.

MainActivity should instead open the same shared preference file and read the value using the same key used in AdminAreaActivity. You already have the preference file name and key as public static variables, so you can reference those variables from MainActivity.

Better yet, create a helper class to manage the preferences. Call it something like PreferenceHelper and it would look something like this:

public class PreferenceHelper {

    public static final String SHARED_PREFS = "sharedPrefs";
    public static final String RESTAURANT_NAME = "restaurantName";

    public static String getResturantName(Context context) {
        return context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).getString(RESTAURANT_NAME,"Your Restaurant here!");
    }

    public static void setResturantName(Context, String name) {
        context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).edit().putString(RESTAURANT_NAME, name).apply();
    }
}

Now you can call your helper from both classes.

Greg Moens
  • 1,705
  • 8
  • 15
  • Thank you very much, sir, for the information, I literally have started android development 3 days ago and I did not know about instantiating an activity.Also. the atemp of making a class I think that is very versatile, but i'm struggling to understand what a Context is. Can you make me a short summary. Thank you very much in advance! – Andrei Jan 03 '19 at 22:14
  • A context can be many things, but in your example, a context is the activity. Activity extends context so you can pass in an activity whenever you see a context is needed as a parameter. – Greg Moens Jan 03 '19 at 23:54
0

SharedPreferences might be the wrong way for storing data, because "It is using expensive operations which might slow down an app.". Have a look at Room for storing.

To answer your question:

  1. Delete the loadData() method and its execution from your AdminAreaActivity, since you want to load the data in your MainActivity. Additionally you called the wrong SharedPreference name (NAME_RESTAURANT).
  2. Only write Constants with capital letters
  3. You can edit your saveData() and loadData() to reuse it later

See my fix below

AdminAreaActivity

 public class AdminAreaActivity extends AppCompatActivity {
    public static final String SHARED_PREFS = "sharedPrefs";
    public static final String RESTAURANT_NAME = "restaurantName";

    private EditText etDRestaurantName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_area);

        etDRestaurantName = findViewById(R.id.etRestaurantName);
        final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);

        bRestaurantChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!etDRestaurantName.getText().toString().matches("")) {
                    Intent mainIntent = new Intent(AdminAreaActivity.this, MainActivity.class);
                    saveData(RESTAURANT_NAME, etDRestaurantName.getText().toString() + "!");
                    etDRestaurantName.getText().clear();
                    startActivity(mainIntent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
                    builder.setMessage("Failed!").setNegativeButton("Retry", null).create().show();
                }
            }
        });

    }

    public void saveData(String prefName, String prefValue) {
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(prefName, prefValue);
        editor.apply();
        Toast.makeText(this, "Data saved!", Toast.LENGTH_SHORT);

    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    private TextView etWelcomeToRestaurant2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
        String messg = "Welcome to,\n";
        etWelcomeToRestaurant.setText(messg);

        etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
        etWelcomeToRestaurant2.setText(loadData(AdminAreaActivity.RESTAURANT_NAME, "Your Restaurant here!"));

    }

    public String loadData(String prefName, String defValue){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
        return sharedPreferences.getString(prefName, defValue);
    }
}
algtr
  • 68
  • 9
  • Thank you very much that I was expected from my question, now I have a better understanding about SharedPreferences. Also, I will go further to learn about Room. I will update your comment as the "solved one" in a short period of time. Thank you! – Andrei Jan 03 '19 at 22:18
  • I'm glad that I could help you! Have fun with android :) – algtr Jan 04 '19 at 09:08