【问题标题】:Android - Passing an ArrayList of Custom Objects to Another ActivityAndroid - 将自定义对象的 ArrayList 传递给另一个 Activity
【发布时间】:2016-08-04 04:05:42
【问题描述】:

所以,我已经为此苦苦挣扎了一段时间,在这里搜索了几个小时,但没有找到任何真正有帮助的东西。我有一个自定义类Streak。当用户在我的 Main Activity 中创建一个新的 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++;
    }
}
}

【问题讨论】:

  • 在主要活动中创建 Streak 的数组列表并使用 parcelable 传递意图。意味着将 Streak 类创建为 parcelable 并使用 getIntent().getParcelableArrayExtra() 进行检索。在 AllStreak 活动中。而不是在 AllStreak 类中创建静态 arrylist。
  • 你可以看到我已经发布了它的例子。

标签: java android gson sharedpreferences


【解决方案1】:

您不能直接传递对象。您必须将其打包或序列化。但是在 parcelable 中是 android 的一部分,而序列化是 java 的一部分,所以我建议你使用 parcelable。

如果您不想为 parcelabel 编写代码,您可以通过此链接将模型类设置为 parcelable。

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

【讨论】:

    【解决方案2】:

    您需要使用ParcelableSerializable接口。

    并有目的地传递它

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

    在 ResultActivity 中获取它

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

    检查this线程以供参考

    【讨论】:

    • 这可行,但是我将如何将这些值保存在我的 AllStreaks 类中?它只会向传递给 AllStreaks 的 ArrayList 添加新的 Streaks。如果我终止应用程序并重新打开它,AllStreaks.java 将再次为空,因为我没有添加任何新内容。
    • 如果您需要离线维护这些数据,您可以使用 SQLite 来实现此目的
    【解决方案3】:

    在您的 Streak 班级上执行此操作并尝试,

    Streak implements Parcelable 
    

    由于您的模态类尚未序列化,它可能无法通过捆绑传递。您可以通过实现Parcelable 接口来做到这一点。

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

    【讨论】:

    • 而不是可序列化的parcelable更快。
    • @mcd 是的,你是对的。 Parcelable 是一个 Android 特定的接口,我会更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    相关资源
    最近更新 更多