Search code examples
javaandroidandroid-activity

How to display data from an activity to another and in the same time to save it?


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

    }


}

Solution

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