How to change the background color of a view from a different activity in android?

Arnab :

I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.

Here is the code :

SetsAdapter.java

public class SetsAdapter extends BaseAdapter {

    private int numOfSets;

    public SetsAdapter(int numOfSets) {
        this.numOfSets = numOfSets;
    }

    @Override
    public int getCount() {
        return numOfSets;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        View view;
        if(convertView == null){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
        }
        else {
            view = convertView;
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
                questionIntent.putExtra("SETNUM", position +1);
                parent.getContext().startActivity(questionIntent);
            }
        });

        ((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));

        return view;
    }
}

SetsActivity.java

public class SetsActivity extends AppCompatActivity {

    private GridView sets_grid;
    private FirebaseFirestore firestore;
    public static int categoryID;
    private Dialog loadingDialog;

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

        Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
        setSupportActionBar(toolbar);
        String title = getIntent().getStringExtra("CATEGORY");
        categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
        getSupportActionBar().setTitle(title);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        sets_grid = findViewById(R.id.sets_gridView);

        loadingDialog = new Dialog(SetsActivity.this);
        loadingDialog.setContentView(R.layout.loading_progressbar);
        loadingDialog.setCancelable(false);
        loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
        loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        loadingDialog.show();

        firestore = FirebaseFirestore.getInstance();
        loadSets();



    }

    private void loadSets() {
        firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot doc = task.getResult();

                    if (doc.exists()) {
                        long sets = (long) doc.get("SETS");
                        SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));


                        sets_grid.setAdapter(adapter);


                    } else {
                        Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
                        finish();

                    }
                } else {
                    Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                }
                loadingDialog.cancel();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId() == android.R.id.home)
            finish();
        return super.onOptionsItemSelected(item);
    }
}

ScoreActivity.java

public class ScoreActivity extends AppCompatActivity {

    private TextView score;
    private Button done;

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

        score = findViewById(R.id.score_tv);
        done = findViewById(R.id.score_activity_done);

        String score_str = getIntent().getStringExtra("SCORE");
        final int setNum = getIntent().getIntExtra("SetNum", 1);
        score.setText(score_str);

        done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Here is the issue I am facing
                View view = findViewById(R.id.setNumber);
                view.setBackgroundColor(Color.GREEN);
                Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
                startActivity(mainIntent);
                ScoreActivity.this.finish();
            }
        });


    }
}

Lalit Fauzdar :

As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.

You've two options to change the color with two different life cycle of the change.

  1. To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.

  2. To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.
    You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:

    //store the value from ScoreActivity after completion as
    
    TinyDB tinyDB = TinyDB(this);
    tinyDB.putBoolean("isSet1Completed",true);
    
    //access the boolean variable in SetsActivity to change the color of any set that 
    //is completed and if it's true, just change the color. 
    
    TinyDB tinyDB = TinyDB(this);
    Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
    

But, it's your choice what way you want to prefer. Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.

  • Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.

    Declare it as public static ImageView imageview;(or TextView) intialize it in the onCreated() as imageView = finViewById(R.id.viewId); in Sets activity.
    Call it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.

  • Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.

I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to dynamically change view background colour from different class

Animate change of view background color on Android

Android: How to get background color of Activity in Java?

How to use animatorSet to change background color of a View

How to change AlertDialog view background color?

Android: Changing Background-Color of the Activity (Main View)

how i change background for all activity android

How can I change the background color of my MainActivity from a second activity using colored buttons as user choices?

Android background color different from expected

How to change the activity background from fragment inside it

How to change layout background from another activity?

How to call canvas in View Class and change it's color from an Activity Class

How to change background/color of the drawable set as background of a view?

How to change background color in android app

How to change background color at image in widget android

How to change Android ViewPager Background Color?

How to change background color of ImageButton in android

How to change text background color of a button in Android?

How to change the background color of the overflow menu in android

How to change Background color of menuItem in android?

How to change background color of datepicker in android

how to change Android Studio terminal background color

How to change the background color of an ExpandableListView in Android?

How change color of Background Status Bar Of Android

How to change editText background color (Android)?

How to change color of drawable set as android:background?

How to Change the background color of Spinner selection in Android

How to change background color popup menu android

How to change imageview background color in a preference in android?