1

I have an ArrayList called refineList, which is created when the application starts and it is populated with data through several methods. This List is used the in custom Adapter which loads different content based in the refineList data.

I have several methods that can rearange the refineList and inside my MainActivity , but in one of the cases I am starting a new Activity via Intent (through the Overridden method onRightCardExit()) and in this new Activity I have a button, which after is pressed by the user I want to rearrange the refineList in MainActivity.

I have created the method in my MainActivity (refineListWithSimular()) , but how can I call it from the other Activity and is there a better solution to this? I read about moving this kind of methods in Utility class, but I didn't figure out how to use it.

Below is my MainActivity

package com.botevplovdiv.foodmatch2;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    // keys for reading data from SharedPreferences
    public static final String FISH = "fishSwitch";
    public static final String MEAT = "meatSwitch";
    public static final String VEGETARIAN = "vegSwitch";
    public static final String PIZZA = "pizzaSwitch";
    public static final String PASTA = "pastaSwitch";
    public static final String RESTAURANTS = "restaurantSwitch";
    public static final String TAKEAWAY = "takeAwaySwitch";

    private MyAppAdapter myAppAdapter;
    private List<FoodDish> dishList;
    private List<FoodDish> refineList;
    private List<FoodDish> dumpList;
    private List<Venue> venues;
    private boolean[] booleans;
    private String[] booleansTags;
    private List<String> searchCriteria;
    private SwipeFlingAdapterView flingContainer;
    public static Map<String, Bitmap> bitmaps = new HashMap<>();
    boolean fishSwitch;
    boolean meatSwitch;
    boolean vegetarianSwitch;
    boolean pizzaSwitch;
    boolean pastaSwitch;
    boolean restaurantSwitch;
    boolean takeAwaySwitch;
    boolean preferenceChanged = true;
    public final static String TAG = "FoodMatch";



    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Log.i(TAG,"Entered onCreate() method in MainActivity");

        flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);


        // set default values in the app's SharedPreferences
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        // register listener for SharedPreferences changes
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(
                preferencesChangeListener);

        fishSwitch = sharedPreferences.getBoolean(FISH,false);
        meatSwitch =  sharedPreferences.getBoolean(MEAT,false);
        vegetarianSwitch =  sharedPreferences.getBoolean(VEGETARIAN,false);
        pizzaSwitch =  sharedPreferences.getBoolean(PIZZA,false);
        pastaSwitch =  sharedPreferences.getBoolean(PASTA,false);
        restaurantSwitch =  sharedPreferences.getBoolean(RESTAURANTS,false);
        takeAwaySwitch =  sharedPreferences.getBoolean(TAKEAWAY,false);

        booleansTags = new String[] {"FISH","MEAT","VEGETARIAN","PIZZA","PASTA","RESTAURANT","TAKE AWAY"};

        dishList = new ArrayList<>();
        searchCriteria = new ArrayList<>();
        refineList = new ArrayList<>();
        dumpList = new ArrayList<>();


        // load initial data
        loadDishes();

        createSearchCriteria(searchCriteria);
        refineDishesList();

        //lock the device to portrait mode
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        myAppAdapter = new MyAppAdapter(this, refineList);
        flingContainer.setAdapter(myAppAdapter);
        flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
            @Override
            public void removeFirstObjectInAdapter()
            {

            }

            @Override
            public void onLeftCardExit(Object dataObject)
            {
                FoodDish current = refineList.get(0);
                refineList.remove(0);
                myAppAdapter.notifyDataSetChanged();
                if (refineList.isEmpty()){
                    if (checkSwitches()){
                        showRestartDialog();
                    }else{
                        Toast.makeText(MainActivity.this,"The combination of switches turned off, won`t show any results",Toast.LENGTH_SHORT).show();
                    }
                }

                //Do something on the left!
                //You also have access to the original object.
                //If you want to use it just cast it (String) dataObject
            }

            @Override
            public void onRightCardExit(Object dataObject)
            {
                FoodDish current = refineList.get(0);
                Intent intent = new Intent(MainActivity.this,LikedProduct.class).putExtra("current",current);
                startActivity(intent);
                refineList.remove(0);
                myAppAdapter.notifyDataSetChanged();

            }

            @Override
            public void onAdapterAboutToEmpty(int itemsInAdapter)
            {

            }

            @Override
            public void onScroll(float scrollProgressPercent) {
                View view = flingContainer.getSelectedView();
                view.findViewById(R.id.background).setAlpha(0);
                view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
                view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
            }
        });


        // Listener for touching events
        flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClicked(int itemPosition, Object dataObject) {

                View view = flingContainer.getSelectedView();
                view.findViewById(R.id.background).setAlpha(0);
                Toast toast = Toast.makeText(MainActivity.this,"test",Toast.LENGTH_SHORT);
                toast.show();
                myAppAdapter.notifyDataSetChanged();
            }
        });

        //floating buttons for remote flipping the cards

        FloatingActionButton yesFAB =
                (FloatingActionButton) findViewById(R.id.acceptButton);
        yesFAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!refineList.isEmpty())
                    flingContainer.getTopCardListener().selectRight();

            }
        });

        FloatingActionButton noFAB =
                (FloatingActionButton) findViewById(R.id.rejectButton);
        noFAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!refineList.isEmpty())
                    flingContainer.getTopCardListener().selectLeft();

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"Entered onResume() method in MainActivity");
        if (refineList.isEmpty()){
            if (checkSwitches()){
                showRestartDialog();
            }else{
                Toast.makeText(MainActivity.this,"The combination of switches turned off, will not return any results",Toast.LENGTH_LONG).show();
            }
        }

    }


    private void refineDishesList() {
        if (this.refineList.size() > 0)
        {
            this.refineList.clear();
        }
        for (FoodDish dish : this.dishList){
            if (this.searchCriteria.contains(dish.getCategory().toUpperCase()) && this.searchCriteria.contains(dish.getVenueType().toUpperCase())){
                this.refineList.add(dish);
            }
        }
    }



    private void createSearchCriteria(List<String> searchCriteria){
        booleans = new boolean[]{fishSwitch,meatSwitch,vegetarianSwitch,pizzaSwitch,pastaSwitch,restaurantSwitch,takeAwaySwitch};
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (searchCriteria.size() >0){
            searchCriteria.clear();
        }

        for (int i = 0;i < booleansTags.length;i++){
            boolean temp = booleans[i];
            if (temp){
                searchCriteria.add(booleansTags[i]);
            }
        }
    }

    private boolean checkSwitches(){
        boolean check = true;
        if ((!fishSwitch && !meatSwitch && !vegetarianSwitch && !pizzaSwitch && !pastaSwitch) || (!restaurantSwitch && !takeAwaySwitch)){
            check = false;
        }
        return check;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent preferencesIntent = new Intent(this, Settings.class);
        startActivity(preferencesIntent);
        return super.onOptionsItemSelected(item);
    }

    public void loadDishes(){
        dishList.add(new FoodDish("Shrimp dish","https://cdn.pixabay.com/photo/2015/04/10/00/41/food-715539_960_720.jpg",getString(R.string.test),"Price : 2,14", "FISH","Restaurant"));
        dishList.add(new FoodDish("Pizza ultra mega qkata rabota","http://www.seattleorganicrestaurants.com/vegan-whole-foods/images/Food-Guidelines.jpg","Test description.This a very tasty dish and you should definitely order it.I don`t know what are you waiting for", "Price: 3,87", "PIZZA","Take Away"));
        dishList.add(new FoodDish("Pasta","http://assets.simplyrecipes.com/wp-content/uploads/2008/03/pasta-tuna-arugula-horiz-a-1600.jpg",getString(R.string.test), "Price: 4,87","PASTA","Restaurant"));
        dishList.add(new FoodDish("Chicken wings","http://cf.yellowblissroad.com/wp-content/uploads/2015/02/Baked-Chicken-Wings.jpg",getString(R.string.test),"Price: 1,23","MEAT","Take Away"));
        dishList.add(new FoodDish("Fish","http://cdn.skim.gs/image/upload/v1456339187/msi/grilled-catfish_izglgf.jpg",getString(R.string.test), "Price: 5,87", "FISH","Take Away"));
        dishList.add(new FoodDish("Spaghetti","http://food.fnr.sndimg.com/content/dam/images/food/fullset/2009/6/12/2/FO1D41_23785_s4x3.jpg.rend.hgtvcom.616.462.jpeg",getString(R.string.test), "Price: 9,23", "PASTA","Restaurant"));
        dishList.add(new FoodDish("Ceasar salad","http://entomofarms.com/wp-content/uploads/2016/04/EF-caesar-salad-cricket-powder.jpg",getString(R.string.test), "Price: 3,45", "VEGETARIAN","Restaurant"));
        dishList.add(new FoodDish("Steak sandwich","http://s3.amazonaws.com/finecooking.s3.tauntonclud.com/app/uploads/2017/04/18125307/051120015-01-steak-sandwich-recipe-main.jpg",getString(R.string.test), "Price: 3,45","MEAT","Take Away"));
        dishList.add(new FoodDish("Lasagna","http://www.weightlossresources.co.uk/img/recipes/vegetarian-dishes.jpg",getString(R.string.test), "Price: 11,45","VEGETERIAN","Restaurant"));
        dishList.add(new FoodDish("Sea Food Risotto","http://www.dvo.com/recipe_pages/healthy/Lemony_Seafood_Risotto.jpg",getString(R.string.test), "Price: 8,45","VEGETERIAN","Take Away"));
    }

    public void refreshContent(){
        createSearchCriteria(searchCriteria);
        refineDishesList();
        flingContainer.removeAllViewsInLayout();
        myAppAdapter.notifyDataSetChanged();
        preferenceChanged = true;
    }

    public void refineListWithSimilar(String simularCategory){
        if (this.refineList.size()>0){
            for (FoodDish dish : this.refineList){
                if (dish.getCategory().toUpperCase().equals(simularCategory.toUpperCase())){
                    this.refineList.add(0,dish);
                }else{
                    this.refineList.add(dish);
                }
            }
        }

        flingContainer.removeAllViewsInLayout();
        myAppAdapter.notifyDataSetChanged();
    }

    public void showRestartDialog(){
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Restart list?")
                .setMessage("Do you want to restart the list?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        createSearchCriteria(searchCriteria);
                        refineDishesList();
                        myAppAdapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }


    private SharedPreferences.OnSharedPreferenceChangeListener preferencesChangeListener =
            new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(
                        SharedPreferences sharedPreferences, String key) {
                    switch (key){
                        case FISH:
                            fishSwitch = sharedPreferences.getBoolean(FISH,false);
                            refreshContent();
                            break;
                        case MEAT:
                            meatSwitch = sharedPreferences.getBoolean(MEAT,false);
                            refreshContent();
                            break;
                        case VEGETARIAN:
                            vegetarianSwitch = sharedPreferences.getBoolean(VEGETARIAN,false);
                            refreshContent();
                            break;
                        case PIZZA:
                            pizzaSwitch = sharedPreferences.getBoolean(PIZZA,false);
                            refreshContent();
                            break;
                        case PASTA:
                            pastaSwitch = sharedPreferences.getBoolean(PASTA,false);
                            refreshContent();
                            break;
                        case RESTAURANTS:
                            restaurantSwitch = sharedPreferences.getBoolean(RESTAURANTS,false);
                            refreshContent();
                            break;
                        case TAKEAWAY:
                            takeAwaySwitch = sharedPreferences.getBoolean(TAKEAWAY,false);
                            refreshContent();
                            break;

                    } //end of switch statement
        }
    };

}

And this is my other Activity called LikedProduct. Basically, I want when the viewSimular button is clicked to invoke the method for rearranging the refineList in my MainActivity.

package com.botevplovdiv.foodmatch2;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class LikedProduct extends AppCompatActivity {

    Button smallBackButton;
    Button viewSimilar;
    String TAG = "FoodMatch";



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

        final FoodDish current = getIntent().getExtras().getParcelable("current");

        Glide
                .with(getApplicationContext())
                .load(current.getImagePath())
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                        ImageView image = (ImageView) findViewById(R.id.likedImagePic);
                        image.setImageBitmap(resource);

                    }
                });

        viewSimilar = (Button) findViewById(R.id.view_similar);
        viewSimilar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String similarCategory = current.getCategory();

                //Here I want to use the method to rearrange the refineList and then go back to MainActivity

                onBackPressed();
            }
        });


        smallBackButton = (Button) findViewById(R.id.smallBackButton);
        smallBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                onBackPressed();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"Entered onStart() method in LikedProduct");
    }
}

Thanks in advance for any help.

UPDATE

I saw my question is marked as duplicate, but the other one has nothing in common with my issue. I was asking how I can rearrange an ArrayList in MainActivity from another activity before returning there.

I managed to find some solution with using startActivityForResult, but I was asking how to access the list or a method in MainActivity, because I want to rearrange the list before going back to it. From what I read one of the options is to make the method static, but I have to make the List static as well. Is that a good practice and is there any flaws of doing that?

Micho
  • 3,929
  • 13
  • 37
  • 40
  • using inheritance. – Jaydeep Devda May 27 '17 at 04:02
  • The correct way of communicating between Activities is with Intents. See [How to send an object from one Android Activity to another using Intents?](https://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-using-intents) and the official tutorial "communicating between activities" – David Rawson May 27 '17 at 05:42
  • You can use the android Application class so you can maintain refineList at application lavel. – Pravin Fofariya May 27 '17 at 05:59
  • Do yo mean creating a class extending Application and then instantiating an object of it in the LikedProduct activity and maintain the refineList from there? – Kristiyan Kyosev May 27 '17 at 11:58

1 Answers1

-1

You can use Application class to achieve it as below:

public class MyApplication extends Application{
     private List<YourObject> refineList;
}

then you can modify your refineList from anywhere:

((MyApplication)getApplication()).getRefineList();
halfer
  • 19,824
  • 17
  • 99
  • 186
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
  • I decided to make a static getter method in my MainActivity in order to access the list, but hence I had to make the list static as well.I marked it as private though.Is marking a list as static considered as bad practice in Android? Thanks – Kristiyan Kyosev May 29 '17 at 12:18
  • Yes, it's a bad practice in Android. You should avoid using static. It's easier for coding but worse for real app. If you use static, please make sure to release the resource after using it (like setting the list = null). – Kingfisher Phuoc May 29 '17 at 14:50
  • Well this resource list is used during the whole lifecycle of the app.It is a key point , because it holds the information that should be passed to the other activities.I am not really sure when I have to release it – Kristiyan Kyosev May 29 '17 at 16:41