Android changing background color from different activity

0

I'm trying to change the backgroud color of my main activity. From the menu, I select settings and brings me into another activity with settings. When I click on my checkbox to change the backgroud, it crashes. I'm trying to change the backgroud of the main activity view. LinearLayout is child of the main activity and the one I wish to change. But I keep getting nullpointers, any help on what I can do to fix this or what do I need to do get this to work?

settings activity class:

public class ShowSettingsActivity extends Activity {
    static final String TAG = "CAT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_settings_layout);

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        StringBuilder builder = new StringBuilder();

        builder.append("\n" + sharedPrefs.getBoolean("night_mode_key", true));
        builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
        builder.append("\n" + sharedPrefs.getString("language_key", "-1"));

        //builder.append("\n" + sharedPrefs.getBoolean("time_history_key", true));

        TextView settingsTextView = (TextView) findViewById(R.id.settings_text_view);
        settingsTextView.setText(builder.toString());    
    }
}

preference activity class:

public class QuickPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
    CheckBoxPreference isReg;
    static final String TAG = "QuickPrefsActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);        
        addPreferencesFromResource(R.xml.preferences); 

        PreferenceManager.setDefaultValues(this,R.xml.preferences, false);

        CheckBoxPreference  night_checkbox = (CheckBoxPreference) findPreference("night_mode_key");        

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //menu.add(Menu.NONE, 0, 0, "Show current settings");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                startActivity(new Intent(this, ShowSettingsActivity.class));
                return true;
        }
        return false;
    }

    @Override
    public void onStart(){
        super.onStart();
        SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(QuickPrefsActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        SharedPreferences s = getSharedPreferences("MY_PREFS", 0);

        // Create a editor to edit the preferences:
        SharedPreferences.Editor editor = s.edit();

        // Let's do something a preference value changes
        if (key.equals("night_mode_key")) 
        {
            // Create a reference to the checkbox (in this case):
            CheckBoxPreference mHints = (CheckBoxPreference)getPreferenceScreen().findPreference("night_mode_key");

            //Lets change the summary so the user knows what will happen using a one line IF statement:
            //mHints.setSummary(mHints.isChecked() ? "Hints will popup." : "No hints will popup.");
            // Lets store the new preference:
            //SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            boolean checkBoxValue = s.getBoolean("night_mode_key", false);

            if (checkBoxValue) 
            {
                Log.d(TAG, "true onshared" + checkBoxValue);

                //setContentView(R.layout.activity_main);
                View v = findViewById(R.id.LinearLayout1);
                //View root = v.getRootView();

                v.setBackgroundColor(0xffffffff);
                /*((TextView) findViewById(R.id.hanziTextView)).setTextColor(0xff000000);
                  ((TextView) findViewById(R.id.timerTextView)).setTextColor(0xff000000);
                  ((TextView) findViewById(R.id.instructionTextView)).setTextColor(0xff000000);*/

            }
            else
            {
            /* findViewById(R.id.LinearLayout1).setBackgroundColor(0xff000000);
                ((TextView) findViewById(R.id.hanziTextView)).setTextColor(0xff444444);
                ((TextView) findViewById(R.id.timerTextView)).setTextColor(0xff444444);
                ((TextView) findViewById(R.id.instructionTextView)).setTextColor(0xff444444);*/
                Log.d(TAG, "false onshared" + checkBoxValue);
            }                      

            //checkBox.setChecked(false);

            editor.putBoolean("night_mode_key", mHints.isChecked());

            // Save the results:
            editor.commit();
        }

        if (key.equals("language_key")) {

            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
           //ListPreference listPref = (ListPreference) sharedPreferences; 
           String entryvalue = sharedPreferences.getString( "language_key", "");
           Log.d(TAG, "Entryvalue " + entryvalue);

            if (entryvalue.equals("EN"))
            {
                Log.d(TAG, "EN " + entryvalue);
                Toast.makeText(getBaseContext(), "English Selected", Toast.LENGTH_SHORT).show();
            }
            else if (entryvalue.equals("CH"))
            {
                Log.d(TAG, "CH " + entryvalue);
                Toast.makeText(getBaseContext(), "Chinese Selected", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getBaseContext(), "You may not go where no1 has gone before, pick again!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

main layout xml... the one i'm trying to change background:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">        

    <android.gesture.GestureOverlayView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/gestureOverlayView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        tools:context=".MainActivity">

        <LinearLayout 
            android:id="@+id/LinearLayout1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="10dp" 
            android:layout_gravity="start">

            <TextView
                android:id="@+id/timerTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_marginRight="5sp"
                android:text="@string/startTime"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textSize="30sp" />

        </LinearLayout>

    </android.gesture.GestureOverlayView>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="#666"
        android:dividerHeight="1dp"
        android:background="#333"
        android:paddingLeft="15sp"
        android:paddingRight="15sp"
        />    
</android.support.v4.widget.DrawerLayout>
android
android-layout
view
asked on Stack Overflow Mar 12, 2014 by MAXGEN • edited Mar 3, 2020 by MyStackRunnethOver

2 Answers

2

It will crash because the targeted LinearLayout is in another activity. what you can do is.. save the color of the background or settings in a Sharedpreferences file.. then call it again in the main activity to change the color...

 if (checkBoxValue) 
         {
            SharedPreferences sp = getSharedPreferences("settings", Context.MODE_PRIVATE);
            Editor edit = sp.edit();
            edit.putString("COLOR", "0xffffffff")
         }

then in your main check the value of the sharedPreferences...

...
SharedPreferences sp = getSharedPreferences("settings", Context.MODE_PRIVATE);
v.setBackgroundColor(sp.getString("COLOR"), Color.WHITE); // here check if the value available, if not put the color to default.. maybe white?...

this is untested code.. I wrote it roughly.. but I hope you got the idea. Please give me a feedback

answered on Stack Overflow Mar 12, 2014 by Coderji
0

You can't access the layout view of the main activity from another activity. The way to do it would be to add an extra to the intent that launches the main activity again, or you could use SharedPreferences.

answered on Stack Overflow Mar 12, 2014 by ElectronicGeek

User contributions licensed under CC BY-SA 3.0