Android - 将自定义对象的ArrayList传递给另一个Activity

时间:2016-08-04 04:05:43

标签: java android gson sharedpreferences

所以,我已经在这方面苦苦挣扎了一段时间,并在这里搜索了几个小时而没有找到任何真正有用的东西。我有一个自定义类Streak。当用户在我的主活动中创建新的Streak时,我希望将该条纹添加到总条纹列表中,然后我将从AllStreaks活动中访问该列表。我尝试过使用Gson,但收到了错误。我下面的内容是暂时工作,但因为我的全局变量必须被声明为新的。我真的不想使用MySQL数据库,因为这些信息需要快速编辑,我不想不断地连接到它,可能只改变一个细节。

对不起,如果我的代码乱七八糟或这没有任何意义,我会意识到我在编程方面真的很糟糕。

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++;
    }
}
}

3 个答案:

答案 0 :(得分:0)

您需要使用ParcelableSerializable界面。

并且意图传递

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

在ResultActivity

中获取它
Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");

检查this帖子以供参考

答案 1 :(得分:0)

Streak课程上执行此操作,然后尝试

Streak implements Parcelable 

由于您的模态类尚未序列化,因此可能无法通过bundle传递。您可以通过实现Parcelable接口来实现。

  1. Parcelable是一个Android特定的界面,您可以在其中实现 自己序列化。它的创建效率要高得多 Serializable,并解决默认Java的一些问题 序列化方案。
  2. Serializable是标准的Java接口。你只需标记一个类 通过实现接口可序列化,而Java将 在某些情况下自动序列化。 Courtsy

答案 2 :(得分:0)

你不能直接传递对象。你必须对它进行parcelable或序列化。但是parecelable是android的一部分,其中序列化是java的一部分所以我建议你使用parcelable。

如果您不想为parcelabel编码,可以将模型类从此链接中分类。

parcelable creator

你可以这样做。

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];
     }
};}

你可以像下面那样传递它。

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

你可以像下面这样得到它:

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