Search code examples
javaandroidandroid-fragmentsdesign-patternsandroid-popupwindow

Android : Approach of passing variable generated in click event of fragment and popup window to activity


I wonder what kind of approach available for the transfer of the variable generated from class of fragment or popup window to activity provided that the fragment or popup window class is separated from activity.

Any code example of elegant approach is appreciated.


Solution

  • It all depend of what kind of data you wish to pass between fragment or popup window to activity one way can be using intent

        //create an Intent object 
            Intent intent=new Intent(context, Activity.class);
        //add data to the Intent object
            intent.putExtra("text", "Data");
        //start the second activity
            startActivity(intent);
    

    and for receiving intent data use

    getIntent().getStringExtra("text")
    

    Another way can be using sharedpreferences

    SharedPreferences prefs = this.getSharedPreferences(
          "com.example.app", Context.MODE_PRIVATE);
    

    To read preferences: String dateTimeKey = "com.example.app.datetime";

    // use a default value using new Date()

    long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
    

    To edit and save preferences

    Date dt = getSomeDate();
    prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();