我有一个包从一个活动传递到另一个活动。其中包含字符串 n(长度最大为 30)、字符串 ID 和字符串颜色。我需要将这些值作为数组(n、ID、颜色)保存到 ArrayList 中,然后将 ArrayList 保存到 androids 内存中。我一直在寻找一种最好的方法。我已经尝试过数据库,但目前它对我来说很复杂,我认为我不需要这么复杂的东西。我已经尝试过 FileOutputStream (正如这里解释的那样:http: //developer.android.com/guide/topics/data/data-storage.html#pref?)但它对我不起作用,可能是因为我正在做某事错误的。我真的需要创建一个数组的arraylist,还是我可以使用arraylist of bundles,或者任何其他方式..?什么是最好的方法...?请帮忙..
谢谢大家...一直在尝试,但没有运气..我正在发布代码,希望有人可以帮我解决这个问题:
public class MainActivity extends Activity
{
String gotNotes;
String n;
String gotDOW;
String gotID;
public String clrs;
public String id;
public String nts;
String gotHour;
String gotColor;
TextView notes;
public static String FILENAME = "allevents";
String[] newevent;
String[] events;
SharedPreferences sharedPref;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button settings = (Button)findViewById(R.id.settings);
Bundle gotPackage = getIntent().getExtras();
if (gotPackage != null){
gotNotes = gotPackage.getString("AddedNote");
if (gotNotes.equals(" "))
{
n = "Empty";
}
else
{
n = gotNotes;
}
//gotDOW = gotPackage.getString("Day");
//gotHour = gotPackage.getInt("Hour");
gotID = gotPackage.getString("ID");
gotColor = gotPackage.getString("color");
initialize();
}
else{}
settings.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(v.getContext(),Settings.class);
startActivityForResult(i,0);
}
});
}
private void initialize()
{
// TODO Auto-generated method stub
String[] newevent = {n, gotID, gotColor};
ArrayList<String[]> events = new ArrayList<String[]>();
events.add(newevent);
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", events.toString());
editor.commit();
String allData = sharedPref.getString("yourKey", null);
String[] playlists = allData.split(",");
/* for (int number=0;number<events.lastIndexOf(sharedPref);number++)
{
notes = (TextView)findViewById(getResources().getIdentifier(playlists[number], getString(0), allData));
notes.setText(number+1);
}*/
notes = (TextView)findViewById(getResources().getIdentifier(gotID, "id",getPackageName()));
notes.setText(n);
notes.setGravity(Gravity.CENTER_HORIZONTAL);
notes.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
if (gotColor.equals("Blue")){
notes.setBackgroundColor(Color.rgb(99, 184, 255));}else
if(gotColor.equals("Green")){
notes.setBackgroundColor(Color.rgb(189, 252, 201));}else
if(gotColor.equals("Yellow")){
notes.setBackgroundColor(Color.rgb(238, 233, 191));}else
if(gotColor.equals("Grey")){
notes.setBackgroundColor(Color.LTGRAY);}else
if(gotColor.equals("Aqua")){
notes.setBackgroundColor(Color.rgb(151, 255, 255));}else
if(gotColor.equals("White")){}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}