简体   繁体   中英

Android - Passing an ArrayList of Custom Objects to Another Activity

So, I've been struggling on this for a while and have searched on here for hours without finding anything that really helped. I have a custom class Streak . When the user creates a new Streak in my Main Activity, I want for that streak to be added to a list of total streaks, which I would then access from an AllStreaks activity. I have tried using Gson, but received errors. What I have below is working for the time being, but since my global variable has to be declared as new. I don't really want to use a MySQL database as this info needs to be quickly editable and I don't want to have to constantly connect to that to potentially change just one detail.

Sorry if my code is a mess or this makes no sense, I'm coming to realize I'm really shitty at programming anyway.

MainActivity.java :

public class MainActivity extends AppCompatActivity {

private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String userID;

private int streakCounter;
private int mainStreakCounter;

private RelativeLayout quickAdd;
private EditText quickSubmitStreak;
private Button quickSubmitButton;
private Button mainStreak1;
private Button mainStreak2;
private Button mainStreak3;
private Button mainStreak4;
private Button allStreaks;
private Button addStreak;

private Dialog pickDialog;

private Button healthButton;
private Button mentalButton;
private Button personalButton;
private Button professionalButton;
private Button socialButton;

private Button submitStreakButton;
private TextView todaysDate;
private EditText chooseDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    /*
        Creates shared preferences and editor
     */
    prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
    editor = prefs.edit();

    // Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs
    if (prefs.getBoolean("firstTime", true)){
        userID = UUID.randomUUID().toString();
        editor.putString("user", userID);
        editor.putBoolean("firstTime", false);
        editor.commit();
    }

    streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later
    mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later
    quickSubmitStreak = (EditText) findViewById(R.id.enter_goal);
    quickSubmitButton = (Button) findViewById(R.id.submit_button);
    mainStreak1 = (Button) findViewById(R.id.main_goal_1);
    mainStreak2 = (Button) findViewById(R.id.main_goal_2);
    mainStreak3 = (Button) findViewById(R.id.main_goal_3);
    mainStreak4 = (Button) findViewById(R.id.main_goal_4);
    allStreaks = (Button) findViewById(R.id.main_goal_5);
    addStreak = (Button) findViewById(R.id.add_streak_button);


    /*
    if (streakCounter > 4){
        quickAdd.setVisibility(View.INVISIBLE);
    }


    mainStreak1.setText(prefs.getString("mainKeyOne", ""));
    mainStreak2.setText(prefs.getString("mainKeyTwo", ""));
    mainStreak3.setText(prefs.getString("mainKeyThree", ""));
    mainStreak4.setText(prefs.getString("mainKeyFour", ""));


    /*
        Sets the text to the lowest unused main streak to the inputted streak name
        Stores the streak name in shared prefs so it will be there for next time app opens
        Increases the total streak count
     */
    quickSubmitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mainStreakCounter < 4){
                switch(mainStreakCounter){
                    case 0:
                        mainStreak1.setText(quickSubmitStreak.getText().toString());
                        editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit();
                        break;
                    case 1:
                        mainStreak2.setText(quickSubmitStreak.getText().toString());
                        editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit();
                        break;
                    case 2:
                        mainStreak3.setText(quickSubmitStreak.getText().toString());
                        editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit();
                        break;
                    case 3:
                        mainStreak4.setText(quickSubmitStreak.getText().toString());
                        editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit();
                        break;
                    default:break;
                }
            }
            mainStreakCounter++;
            AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString()));

            // ADD THESE TO SHARED PREFERENCES AT SOME POINT
        }

    });

    /*
        Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList
     */
    allStreaks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, AllStreaks.class);
            startActivity(intent);
        }
    });

    /*
        Shows an Alert Dialog that allows users to enter in the type of streak they want
     */
    addStreak.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            createCustomDialog();
        }
    });
}

private void createCustomDialog(){
    pickDialog = new Dialog(MainActivity.this);
    pickDialog.setContentView(R.layout.dialog_add_streak);

    final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name);
    healthButton = (Button) pickDialog.findViewById(R.id.dialog_health);
    mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental);
    personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal);
    professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional);
    socialButton = (Button) pickDialog.findViewById(R.id.dialog_social);
    submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button);
    todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today);
    chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date);

    pickDialog.show();

    healthButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editor.putInt("AddCategory", 0).commit();
            editor.putString("Category", "Health");
            editor.commit();
            recolorCategory();
        }
    });

    mentalButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editor.putInt("AddCategory", 1).commit();
            editor.putString("Category", "Mental");
            editor.commit();
            recolorCategory();
        }
    });

    personalButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editor.putInt("AddCategory", 2).commit();
            editor.putString("Category", "Personal");
            editor.commit();
            recolorCategory();
        }
    });

    professionalButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editor.putInt("AddCategory", 3).commit();
            editor.putString("Category", "Professional");
            editor.commit();
            recolorCategory();
        }
    });

    socialButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editor.putInt("AddCategory", 4).commit();
            editor.putString("Category", "Social");
            editor.commit();
            recolorCategory();
        }
    });

    todaysDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            todaysDate.setTextColor(Color.rgb(51,51,255));
            chooseDate.setTextColor(Color.rgb(0,0,0));
            editor.putInt("todayOrChosen", 1).commit();
        }
    });

    chooseDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chooseDate.setTextColor(Color.rgb(51,51,255));
            todaysDate.setTextColor(Color.rgb(0,0,0));
            editor.putInt("todayOrChosen", 2).commit();
        }
    });


    submitStreakButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            /*
                If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate
             */
            if(prefs.getInt("todayOrChosen", 1) == 1){
                //streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
                        //new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
                AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
                        new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
            }
            else {
                //streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
                        //new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
                AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
                        new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
            }

            /*
                Update streakList in Shared Preferences
             */

            /*
                Display an Alert Dialog indicating that a streak has been added
             */
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Streak Added")
                    .setPositiveButton("OK", null)
                    .create()
                    .show();

            pickDialog.dismiss();
        }
    });
}

/*
    Highlights which category is currently chosen
 */
private void recolorCategory(){
    Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton};
    int recolorIndex = prefs.getInt("AddCategory", 0);
    categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255));
    for (int i = 0; i < 5; i++){
        if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102));
    }
}

@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

AllStreaks.java :

public class AllStreaks extends AppCompatActivity {
public static ArrayList<Streak> streakList = new ArrayList<>();

private SharedPreferences prefs;
private SharedPreferences.Editor editor;

private ArrayList<Streak> allStreakList;

private TableLayout mTableLayout;
private TableRow mTableRow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_all_streaks);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    /*
    if (streakList == null){
        Button streakButton = new Button(this);
        streakButton.setText("Try again");
    }
    else{
        for (int j = 0; j < streakList.size(); j++){
            allStreakList.add(streakList.get(j));
        }
    }*/

    prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
    editor = prefs.edit();

    mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);

    int i = 0;
    while (i < streakList.size()){
        if (i % 2 == 0){
            mTableRow = new TableRow(this);
            mTableLayout.addView(mTableRow);
        }
        Button streakButton = new Button(this);
        streakButton.setText(String.valueOf(streakList.get(i).getDaysKept()));
        streakButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
                startActivity(intent);
            }
        });
        mTableRow.addView(streakButton);
        i++;
    }
}
}

You need to use Parcelable or Serializable interface.

and the pass it with intent

Intent mIntent = new Intent(context, ResultActivity.class);
mIntent.putParcelableArrayListExtra("list", mArraylist);
startActivity(mIntent);

fetch it in ResultActivity

Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");

Check this thread for reference

Do this on your Streak class and try,

Streak implements Parcelable 

Since your modal class has not serialized, it may not able to pass via bundle. You can do that by implementing the Parcelable interface.

  1. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
  2. Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations. Courtsy

you cannot pass object directly.you have to parcelable or serialize it. but in parecelable is part of android where serialzation is part of java so i suggest you to use parcelable.

you can make model class to parcelable from this link if you dont want to code for parcelabel.

parcelable creator

you can achieve like this.

class Car implements Parcelable {
public int regId;
public String brand;
public String color;

public Car(Parcel source) {
    regId = source.getInt();
    brand = source.getString();
    color = source.getString();
}

public Car(int regId, String brand, String color) { 
    this.regId = regId;
    this.brand = brand;
    this.color = color;
}

public int describeContents() {
return this.hashCode();
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(regId);
dest.writeString(brand);
dest.writeString(color);
}

public static final Parcelable.Creator CREATOR
         = new Parcelable.Creator() {
     public Car createFromParcel(Parcel in) {
         return new Car(in);
     }

     public Car[] newArray(int size) {
         return new Car[size];
     }
};}

And you can pass it like below.

ArrayList carList = new ArrayList();
carList.add(new Car('1','Honda','Black'); 
carList.add(new Car('2','Toyota','Blue'); 
carList.add(new Car('3','Suzuki','Green'); 
Intent i = new Intent(getApplicationContext(), CarDetailActivity.class);
i.putParcelableArrayListExtra("cars", carList);
this.startActivity(i);

you can get it like below:

Intent i = this.getIntent();
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM