2017-05-27 24 views
1

我有一個ArrayList調用refineList,它是在應用程序啓動時創建的,它通過多種方法填充數據。此List用於加載基於refineList數據的不同內容的自定義Adapter中。如何重新排列我的MainActivity中的ArrayList從另一活動

我有幾個方法,可以rearange的refineList和我MainActivity裏面,但在的情況下,一個我開始通過IntentActivity(通過重寫方法onRightCardExit()),並在這個新的Activity我有一個按鈕,在用戶按下後,我想重新編排MainActivity中的refineList

我已經在我的MainActivityrefineListWithSimular())中創建了該方法,但是如何從另一個Activity中調用該方法,是否有更好的解決方法?我讀到了在Utility類中移動這種方法,但我沒有弄清楚如何使用它。

下面是我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 
     } 
    }; 

} 

這是我叫LikedProduct其他Activity。基本上,我想要點擊viewSimular按鈕來調用重新排列我的MainActivity中的refineList的方法。

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"); 
    } 
} 

在此先感謝您的幫助。

UPDATE

我看到了我的問題被標記爲重複的,但其他人有什麼共同點與我的問題。我在問,如何在其他活動中重新安排MainActivity中的ArrayList,然後再返回那裏。

我設法找到一些解決方案,使用startActivityForResult,但我問的是如何訪問列表或MainActivity中的方法,因爲我想重新排列列表,然後再回到它。從我讀的其中一個選項是使方法static,但我必須使Liststatic以及。這是一種很好的做法嗎?有沒有這樣做的缺陷?

+0

使用繼承。 –

+0

活動之間溝通的正確方式是與意圖。請參閱[如何使用Intents將對象從一個Android活動發送到另一個活動?](https://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-另一種使用意圖)和官方教程「活動之間的溝通」 –

+0

您可以使用android應用程序類,以便您可以在應用程序層維護refineList。 –

回答

-1

您可以使用Application類,如下歸檔:

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

,那麼你可以從任何地方修改refineList((MyApplication)getApplication()).getRefineList();

+0

爲什麼要投票?請解釋你的失望原因。 –

+0

我沒有低估它,不知道是誰做的。 –

+0

我決定在我的MainActivity中創建一個靜態getter方法來訪問這個列表,但是因此我不得不讓這個列表成爲靜態的。我將它標記爲private.Is將列表標記爲靜態,在Android中被認爲是不好的做法?謝謝 –

相關問題