Android应用程序MainActivity保持重置信息

时间:2015-01-29 07:39:26

标签: java android parcelable

我正在开发一个简单的应用程序,它将一个parcelable从一个活动传递到另一个活动。在MainActivity中,我有一个LinkedList,用于保存从parcelable获取的信息。但是,每次返回MainActivity时,都会删除先前存储在LinkedList(Parcelable)中的Object。我究竟做错了什么?在过去的3天里,我一直在努力弄清楚为什么它不能保存任何东西,但逻辑看起来很稳固。所以我更新了使用startActivityForResult,现在MainActivity中的Parcelable为NULL。

public class MainActivity extends Activity {

int tasks;
final static String TASK_KEY = "newTask";
final static String INDEX_KEY = "LLIndex";
Task t;
ScrollView scrollView;
LinearLayout taskHolder;
LinkedList<Task> taskList = new LinkedList<Task>();

@Override
protected void onCreate(Bundle savedInstanceState) {

    Log.d("In onCreate", "here");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tvCounter = (TextView) findViewById(R.id.textView1);

    taskHolder = (LinearLayout) findViewById(R.id.linearScroll);

    //Checks for parcelable
    if(getIntent().hasExtra(Create.TASK_KEY)){
        Log.d("Task", "You've got mail!");
        Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
        taskList.add(t);
        addNewTask(t);

    }

    Log.d("LL size", Integer.toString(tasks));

    tasks = taskList.size();

    tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));

    Button plusButton = (Button) findViewById(R.id.button1);

    plusButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(MainActivity.this, Create.class);
            startActivity(i);
        }
    });
}

    void addNewTask(Task t) {

        tasks++;

        Log.d("In addNewTask method", t.toString());

        LinearLayout newTaskLayout = new LinearLayout(getApplicationContext());
        newTaskLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        newTaskLayout.setLayoutParams(params);
        //int bottom = (int) getResources().getDimension(R.dimen.margin_bottom);
        //int left = (int) getResources().getDimension(R.dimen.margin_left);
        //params.setMargins(left, 0, 0, bottom);

        TextView tvTitle = new TextView(getApplicationContext());
        TextView tvDate =  new TextView(getApplicationContext());
        TextView tvTime =  new TextView(getApplicationContext());

        tvTitle.setTextColor(Color.BLACK);
        tvDate.setTextColor(Color.BLACK);
        tvTime.setTextColor(Color.BLACK);

        tvTitle.setTypeface(tvTitle.getTypeface(), Typeface.BOLD);

        tvTitle.setText(t.getName());
        tvDate.setText(t.getDate());
        tvTime.setText(t.getTime());

        newTaskLayout.addView(tvTitle);
        newTaskLayout.addView(tvDate);
        newTaskLayout.addView(tvTime);  

        //params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        //params.setMargins(0, 0, 0, 0);
        //tvDate.setLayoutParams(params);
        //tvTime.setLayoutParams(params);

        //tvTitle.setTextSize(getResources().getDimension(R.dimen.size_of_text));


        taskHolder.addView(newTaskLayout);


        final int index = ((ViewGroup) newTaskLayout.getParent()).indexOfChild(newTaskLayout);

        newTaskLayout.setOnClickListener(new View.OnClickListener() {//bind listener

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i = new Intent(MainActivity.this,Display.class);
        i.putExtra(TASK_KEY, taskList.get(index));
        i.putExtra(INDEX_KEY, index);
        startActivity(i);
        }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){
            Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
            Log.d("Task", "You've got mail!");

            if(getIntent().hasExtra(Create.TASK_KEY)){
            Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
            taskList.add(t);
            addNewTask(t);
            }
            Log.d("LL size", Integer.toString(tasks));

            tasks = taskList.size();

            tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));

        }
        else{
            Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
        }
        }
    }

创建班级:

public class Create extends Activity{

private int year;
private int month;
private int day;
private String name, date, time, priority;
final static String TASK_KEY = "newTask";
static final int PICK_CONTACT_REQUEST = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);

    final Calendar cal = Calendar.getInstance();

    //Current Date
    year  = cal.get(Calendar.YEAR);
    month = cal.get(Calendar.MONTH);
    day   = cal.get(Calendar.DAY_OF_MONTH);

    final EditText etTitle = (EditText) findViewById(R.id.editText1);
    final EditText etDate  = (EditText) findViewById(R.id.editText2);
    final EditText etTime  = (EditText) findViewById(R.id.editText3);

    final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);

    //int selectedId = rg.getCheckedRadioButtonId();
    //final RadioButton radioSelected = (RadioButton) findViewById(selectedId);

    Button save = (Button) findViewById(R.id.button1);

    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //Get checked radio button
            RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

            // TODO Auto-generated method stub
            name = etTitle.getText().toString();
            date = etDate.getText().toString();
            time = etTime.getText().toString();
            priority = (String) rb.getTag();

            Task t = new Task(name, date, time, priority);

            Log.d("task", t.toString());

            Intent i = new Intent(Create.this, MainActivity.class);
            i.putExtra(TASK_KEY, t);    //Puts new Task object into Intent to send
            setResult(1,i);
            finish();
        }
    });

    etDate.setKeyListener(null);
    etTime.setKeyListener(null);

    final DatePickerDialog.OnDateSetListener datePick = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, monthOfYear);
            cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }

        private void updateLabel() {
            // TODO Auto-generated method stub
            String myFormat = "MM/dd/yy"; //In which you need put here
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

            etDate.setText(sdf.format(cal.getTime()));
        }

    };

    etDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {


            //Do whatever
            new DatePickerDialog(Create.this, datePick, cal.get(Calendar.YEAR), 
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)).show();
        } 
    });

    etTime.setOnClickListener(new View.OnClickListener()  {


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar curTime = Calendar.getInstance();
            int hour = curTime.get(Calendar.HOUR_OF_DAY);
            int minute = curTime.get(Calendar.MINUTE);
            TimePickerDialog tp;

            tp = new TimePickerDialog(Create.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

                    String am_pm;
                    String minuteStr;
                    Log.d("hour", Integer.toString(selectedHour));


                    if (selectedHour == 0){
                        selectedHour = 12;
                        am_pm = "AM";
                    }else if(selectedHour == 12){
                        selectedHour = 12;
                        am_pm = "PM";
                    }else if(selectedHour > 12) {
                       selectedHour -= 12;
                       am_pm = "PM";
                    }else{
                        am_pm = "AM";
                    }

                    if(selectedMinute < 10){
                        minuteStr = "0" + Integer.toString(selectedMinute);
                    }else{
                        minuteStr = Integer.toString(selectedMinute);
                    }

                    etTime.setText( selectedHour + ":" + minuteStr + " " + am_pm);


                }
            }, hour, minute, false);//Yes 24 hour time
            tp.setTitle("Set Time");
            tp.show();
        }
    });

}
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,那么您会在MainActivity中找到一条消息列表,并且您正在启动Create创建新消息的意图。然后,在保存时,您将开始一个新的MainActivity,并将新消息添加到列表中。

这种方法的问题是每次都会创建一个新的MainActivity实例,其中包含一个新的(空)LinkedList。

我会考虑使用startActivityForResult()来运行Create活动,并使用setResult()中的finish()Create来返回新消息。

您还应该在'onSaveInstanceState'中保存列表内容,以处理MainActivity的破坏和重新创建(例如,当用户旋转设备时)。