1

I have a settings section in my android application, where the user using radio buttons, is able to change the main activity's background image. The problem is that when I turn the method for storing the selection of the user into static, I can not use this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);to read the preferences. The method is called setColorOnPreference() and is lunched on the onCreate method of the main activity to check the last user's selection of background. But the method belongs to the settings activity.

public class Settings extends Activity {


private final static String userSettings="userSettings.txt";

private EditText txtEditor;
static LinearLayout mScreen;

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

    txtEditor=(EditText)findViewById(R.id.textbox);
    mScreen = (LinearLayout) findViewById(R.id.homeScreen);

    try {

        InputStream in = openFileInput(userSettings);             
        if (in != null) {             
        InputStreamReader tmp=new InputStreamReader(in);            
        BufferedReader reader=new BufferedReader(tmp);             
        String str;            
        StringBuilder buf=new StringBuilder(); 

        while ((str = reader.readLine()) != null) {            
        buf.append(str);             
        }            
        in.close();             
        txtEditor.setText(buf.toString());             
        }            
        }

        catch (java.io.FileNotFoundException e) {         
        }

        catch (Throwable t) {             
        Toast.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG).show();            

        }                    
    }

public void saveClicked(View v) {        
    try {        
    OutputStreamWriter out=      
    new OutputStreamWriter(openFileOutput(userSettings, 0));         
    out.write(txtEditor.getText().toString());       
    out.close();         
    Toast.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG).show();
    }
    catch (Throwable t) {
    Toast.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG).show();
    }

    }
public void saveBgColorPreference()
{
    RadioGroup g = (RadioGroup) findViewById(R.id.prefgroup);     
    int selected = g.getCheckedRadioButtonId();     
    RadioButton b = (RadioButton) findViewById(selected);     
    String selectedValue = (String) b.getText();   
    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);     
    SharedPreferences.Editor prefsEditor = myPrefs.edit();    
    prefsEditor.putString("bgcolor", selectedValue);     
    prefsEditor.commit();    
}

public static void setColorOnPreference()    
{
    SharedPreferences myPrefs2 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);        
    String prefName = myPrefs2.getString("bgcolor", "Navy Blue");        
    if(prefName.equals("Navy Blue"))         
    mScreen.setBackground( getResources().getDrawable(R.drawable.mainbg));         
    else         
    mScreen.setBackgroundColor(0xffff0000);            
}

public void savepreferencesClicked(View v) {         
    saveBgColorPreference();        
    setColorOnPreference();      
    }

The error I am getting is that I can use SharedPreferences myPrefs2 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); and also on the mScreen.setBackground( getResources().getDrawable(R.drawable.mainbg)); suggesting me that I cannot use this. in a static method. Sorry for the lots of text, I just wanted to make sure that you understand my issue. Open to any suggestions and implementations

The question here is how will I call a method into another activity?

cmario
  • 605
  • 1
  • 7
  • 22
  • why do you need it static? – Blackbelt Mar 06 '15 at 18:28
  • 1
    You cannot reference non static variable in static method. – StackFlowed Mar 06 '15 at 18:29
  • how will I call the method in another activity? – cmario Mar 06 '15 at 18:29
  • Bundle the object, add it to the intent, and call the method from the activity. http://stackoverflow.com/questions/14876273/simple-example-for-intent-and-bundle or just recreate the object in the new activity. – HappyCactus Mar 06 '15 at 18:46
  • I think you may be looking for a sort of a `OnBackgroundColorChangeListener`. An interface which will have the method `onColorChanged(int color)` and you would call the listeners who implement this interface everytime you update the background color, regarding wheter they're activities or anything else. – vinitius Mar 06 '15 at 18:48
  • @vinitius - that is probably not a route to a solution. How would you get references to the objects on which to call it? – Chris Stratton Mar 06 '15 at 18:51
  • @ChrisStratton His settings activity keeps doing what it already does, except when he updates the background color , then he can get his backgroundColorListeners(may be more than one) and call the method with the color reference that was updated. How is this not a possible solution? – vinitius Mar 06 '15 at 18:55
  • Okay, that is something you could ultimately develop towards a solution, but it would be a tricky one as each of these Activities has a fairly independent lifetime - registering with each other is going to be tricky, and they won't be able to act on that information until they next show as part of an ordinary user flow. – Chris Stratton Mar 06 '15 at 19:09

2 Answers2

0

if method is static you can call it using just class name, as:

MYActivity.methodName();

If method is non static you have to create class's object first then call to method as:

MyActivity mObj = new MyActivity();

mObj.methodName();
Rahul Sharma
  • 5,949
  • 5
  • 36
  • 46
  • That is not the question which was asked. Further, on Android you cannot simply call new for an Activity class as the result will be non-functional. You must use an Intent to create an Activity instance. – Chris Stratton Mar 06 '15 at 18:44
0

You can change the static method to:

public static void setColorOnPreference(Context ctx){
     SharedPreferences myPrefs2 = ctx.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);        
....         
}

and call it like this:

public void savepreferencesClicked(View v) {         
  ....
   setColorOnPreference(v.getContext());      
}

you can call the method from another activity like this:

Settings.setColorOnPreference(this.getApplicationContext());
Titus
  • 22,031
  • 1
  • 23
  • 33
  • what about mScreen.setBackground( getResources().getDrawable(R.drawable.mainbg)); in the static method? – cmario Mar 06 '15 at 18:42
  • That won't work either. Nor would it be safe - there isn't necessarily any instance of the target activity in existence for that to operate on (and if there isn't, you can't simply make one in the singleton pattern, you would need to fire an Intent to ask the system to create one). – Chris Stratton Mar 06 '15 at 18:43
  • @ChrisStratton what are you suggesting me? create new intent of my main activity which I want to change the background? – cmario Mar 06 '15 at 18:46
  • You should be able to just change it in preferences yourself, or call a static method with a context argument to do so. Your challenge is more prompting the Activity in question to update its display in onResume() - you could fire an new intent to do that, or set a dirty flag somewhere it can see or have it simply re-read the preferences on every resume. – Chris Stratton Mar 06 '15 at 18:54
  • @ChrisStratton this can work, he can retrieve the color from the preference file, store it as a static variable and reset the background to this color in the `onCreate` `onResume` etc. methods, – Titus Mar 06 '15 at 18:54
  • how to call that I my main activity? Settings.setColorOnPreference(...); – cmario Mar 06 '15 at 18:58
  • @cmario Yes you can call it like that but keep in mind that `mScreen` will be `null` until you create the `Settings` activity. – Titus Mar 06 '15 at 19:01
  • what shall I put as a context ? Settings.setColorOnPreference(?); – cmario Mar 06 '15 at 19:10
  • There's a path to a solution here, but a necessity to conceptually separate updating the *desired* setting, from making sure that the change is *applied* at the next appropriate opportunity. – Chris Stratton Mar 06 '15 at 19:11
  • @cmario you can use the context of the activity from which you call the method. The shared preferences files are saved per application not per activity so calling that method using another activity's context will get you the same settings (at least this is my understanding, I haven't developed for android in a while). – Titus Mar 06 '15 at 19:14
  • I am struggling with it because I cant find what type of context to insert in the Settings.setColorOnPreference(?); so far everything looks okay apart from the calling from the main activity to retrieve the value of the user's selection – cmario Mar 06 '15 at 19:15