何时保存活动的实例并将其重新加载到listview按钮上?

时间:2017-04-12 11:42:40

标签: android android-activity alarm savestate

所以这是我的提醒应用程序的一部分,当我保存一个警报并且它保存为一行时,我希望能够在点击该行时编辑警报但是如何保存活动的状态并重新加载当我点击行本身时呢?

公共类MainActivity扩展了AppCompatActivity {

private Button setReminder;
private ListView listview;

private DatabaseActivity dba;
private ArrayList<MyAlarm> dbalarms= new ArrayList<>();
private AlarmAdapter alarmAdapter;



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


    listview = (ListView) findViewById(R.id.listView);
    refreshData();




    setReminder = (Button) findViewById(R.id.button);

    final ArrayList<HashMap<String, String>> list = new ArrayList<>();


    setReminder.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {



                startActivity(new Intent(MainActivity.this, AlarmChooser.class));


        }


    });




}

private void refreshData() {
    dbalarms.clear();
    dba = new DatabaseActivity(getApplicationContext());
    ArrayList<MyAlarm> alarmsFromDB = dba.getAlarms();
    for(int temp=0;temp<alarmsFromDB.size();temp++){

        String title = alarmsFromDB.get(temp).getTitle();
        String content= alarmsFromDB.get(temp).getContent();
        String dateText= alarmsFromDB.get(temp).getRecordDate();
        String timeText= alarmsFromDB.get(temp).getRecordTime();

        MyAlarm myAlarm= new MyAlarm();
        myAlarm.setTitle(title);
        myAlarm.setContent(content);
        myAlarm.setRecordTime(timeText);
        myAlarm.setRecordDate(dateText);

        dbalarms.add(myAlarm);
    }
    dba.close();
    alarmAdapter = new AlarmAdapter(MainActivity.this, R.layout.remrow, dbalarms);


        listview.setAdapter(alarmAdapter);

        alarmAdapter.notifyDataSetChanged();

}

public class AlarmAdapter extends ArrayAdapter<MyAlarm>{

    Activity activity;
    int layoutResource;
    MyAlarm alarm;
    ArrayList<MyAlarm> mData = new ArrayList<>();

    public AlarmAdapter(Activity act, int resource, ArrayList<MyAlarm> data) {
        super(act, resource, data);
        activity = act;
        layoutResource = resource;
        mData = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public MyAlarm getItem(int position) {
        return mData.get(position);
    }

    @Override
    public int getPosition(MyAlarm item) {
        return super.getPosition(item);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        ViewHolder holder = null;
        if(row==null || row.getTag()==null){
            LayoutInflater inflater = LayoutInflater.from(activity);
            row = inflater.inflate(layoutResource,null);
            holder=new ViewHolder();

            holder.mTitle=(TextView)row.findViewById(R.id.name);
            holder.mDate=(TextView)row.findViewById(R.id.dateText);
            holder.mTime=(TextView)row.findViewById(R.id.timeText);

            row.setTag(holder);
        }else{
            holder = (ViewHolder)row.getTag();
        }



        holder.myAlarm = getItem(position);
        holder.mTitle.setText(holder.myAlarm.getTitle());
        holder.mDate.setText(holder.myAlarm.getRecordDate());
        holder.mTime.setText(holder.myAlarm.getRecordTime());


        final ViewHolder finalHolder = holder;
        holder.mTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String title= finalHolder.myAlarm.getTitle().toString();
                String dateText=finalHolder.myAlarm.getRecordDate().toString();
                String timeText=finalHolder.myAlarm.getRecordTime().toString();




            }
        });

        return row;


    }

    class ViewHolder{

        MyAlarm myAlarm;
        TextView mTitle;
        TextView mDate;
        TextView mTime;
        TextView mContent;
        TextView mID;
    }
}

}  这是我的一个名为TimeDateRem的提醒,它暗示是在特定时间和日期提醒

公共类TimeDateRem扩展了AppCompatActivity {

DatePicker pickerDate;
TimePicker pickerTime;
Button buttonSetAlarm, cancelButton, deleteButton;
TextView info, title;
PendingIntent pendingIntent;
AlarmManager alarmManager;
 private DatabaseActivity dba;

final static int RQS_1 = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.reminder_view);
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        onRestoreInstanceState(savedInstanceState);
    } else {

        dba = new DatabaseActivity(getApplicationContext());

        info = (TextView) findViewById(R.id.info);
        title = (EditText) findViewById(R.id.title);
        pickerDate = (DatePicker) findViewById(R.id.pickerdate);
        pickerTime = (TimePicker) findViewById(R.id.pickertime);

        Calendar now = Calendar.getInstance();

        pickerDate.init(
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH),
                null);

        pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
        pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));

        cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelAlarm(pendingIntent);
                startActivity(new Intent(TimeDateRem.this, MainActivity.class));

            }
        });

        deleteButton = (Button) findViewById(R.id.deletealarm);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        buttonSetAlarm = (Button) findViewById(R.id.setalarm);
        buttonSetAlarm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Calendar current = Calendar.getInstance();

                Calendar cal = Calendar.getInstance();
                cal.set(pickerDate.getYear(),
                        pickerDate.getMonth(),
                        pickerDate.getDayOfMonth(),
                        pickerTime.getCurrentHour(),
                        pickerTime.getCurrentMinute(),
                        0);

                if (!title.getText().toString().equals("")) {

                    if (cal.compareTo(current) <= 0) {


                        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
                    } else {


                        setAlarm(cal);
                        saveToDB();
                    }
                } else {
                    Toast.makeText(TimeDateRem.this, "Reminder Name Should Not Be Empty", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}
private void setAlarm(Calendar targetCal){
    SharedPreferences sharedPreferences=getSharedPreferences("MySavedData",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor =sharedPreferences.edit();
    editor.putString("title", title.getText().toString());
    editor.putString("content", info.getText().toString());
    editor.putInt("dateMonth",pickerDate.getMonth());
    editor.putInt("dateYear",pickerDate.getYear());
    editor.putInt("date",pickerDate.getDayOfMonth());


    info.setText("\n\n***\n"
            + "Alarm is set @ " + targetCal.getTime() + "\n"
            + "***\n");

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
private void cancelAlarm(PendingIntent p){
    if ( alarmManager!= null) {
        alarmManager.cancel(p);
    }
}
public void saveToDB(){

  MyAlarm alarm= new MyAlarm();
    alarm.setTitle(title.getText().toString().trim());
    alarm.setRecordDate(pickerDate.getDayOfMonth()+"/"+pickerDate.getMonth()+"/"+pickerDate.getYear());
    alarm.setRecordTime(pickerTime.getCurrentHour()+"/"+pickerTime.getCurrentMinute());

    dba.addAlarms(alarm);
    dba.close();

    info.setText("");

    Intent i = new Intent(TimeDateRem.this, MainActivity.class);
    startActivity(i);
  }

public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    // Save UI state changes to the savedInstanceState.
    // This bundle will be passed to onCreate if the process is
    // killed and restarted.
    savedInstanceState.putString("title", title.getText().toString());
    savedInstanceState.putString("content", info.getText().toString());
    savedInstanceState.putInt("dateMonth",pickerDate.getMonth());
    savedInstanceState.putInt("dateYear",pickerDate.getYear());
    savedInstanceState.putInt("dateDay",pickerDate.getDayOfMonth());
    savedInstanceState.putInt("timeMinute",pickerTime.getCurrentMinute());
    savedInstanceState.putInt("timeHour",pickerTime.getCurrentHour());

}

@Override
protected void onPause() {
    super.onPause();
  /*  super.onSaveInstanceState(savedInstanceState);

    savedInstanceState.putString("title", title.getText().toString());
    savedInstanceState.putString("content", info.getText().toString());
    savedInstanceState.putInt("dateMonth",pickerDate.getMonth());
    savedInstanceState.putInt("dateYear",pickerDate.getYear());
    savedInstanceState.putInt("dateDay",pickerDate.getDayOfMonth());
    savedInstanceState.putInt("timeMinute",pickerTime.getCurrentMinute());
    savedInstanceState.putInt("timeHour",pickerTime.getCurrentHour());*/
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // Restore UI state from the savedInstanceState.
    // This bundle has also been passed to onCreate.
    title.setText(savedInstanceState.getString("title"));
    info.setText( savedInstanceState.getString("content"));

    int myMonth = savedInstanceState.getInt("dateMonth");
    int myYear = savedInstanceState.getInt("dateYear");
    int myDay = savedInstanceState.getInt("dateDay");
    int myMinute = savedInstanceState.getInt("timeMinute");
    int myHour = savedInstanceState.getInt("timeHour");


    pickerDate.init(myYear,myMonth,myDay,null);
    pickerTime.setCurrentHour(myHour);
    pickerTime.setCurrentMinute(myMinute);



}

}

很抱歉代码很多但是有人可以帮忙吗?

编辑:添加数据库类

公共类DatabaseActivity扩展了SQLiteOpenHelper {

private final ArrayList<MyAlarm> alarmList = new ArrayList<>();

public DatabaseActivity(Context context) {

    super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_WISHES_DATABASE = "CREATE TABLE " + Constants.TABLE_NAME +
            " ( " + Constants.KEY_ID + " INTEGER PRIMARY KEY, " + Constants.COLUMN_NAME +
            " TEXT, " + Constants.COLUMN_DESCRIPTION + " TEXT, " + Constants.COLUMN_DATE +
            " LONG, " + Constants.COLUMN_TIME + " LONG); ";

    db.execSQL(CREATE_WISHES_DATABASE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP TABLE IF EXIST " + Constants.TABLE_NAME);

    onCreate(db);
}


 public void addAlarms(MyAlarm alarm) {

     SQLiteDatabase db=this.getWritableDatabase();

     ContentValues values= new ContentValues();
     values.put(Constants.COLUMN_NAME , alarm.getTitle());
     values.put(Constants.COLUMN_DESCRIPTION , alarm.getContent());
     values.put(Constants.COLUMN_DATE , System.currentTimeMillis());
     values.put(Constants.COLUMN_TIME , alarm.getRecordTime());

     db.insert(Constants.TABLE_NAME, null, values);
     db.close();
}

public ArrayList<MyAlarm> getAlarms(){

    String selectQuery= "SELECT * FROM " + Constants.TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(Constants.TABLE_NAME, new String[]{Constants.KEY_ID, Constants.COLUMN_NAME
    ,Constants.COLUMN_DESCRIPTION,Constants.COLUMN_DATE,Constants.COLUMN_TIME},null,null,null,null,Constants.COLUMN_DATE
    + " DESC");

    if(cursor.moveToFirst()){
        do{

            MyAlarm alarm = new MyAlarm();
            alarm.setTitle(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_NAME)));
            alarm.setContent(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_DESCRIPTION)));

            java.text.DateFormat dateFormat=java.text.DateFormat.getDateInstance();
            String dateData= dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.COLUMN_DATE))).getTime());

            alarm.setRecordDate(dateData);

            alarmList.add(alarm);
        }while(cursor.moveToNext());
    }

    return alarmList;
}

}

编辑:我试图通过不在我的主要活动和我的timedaterem之间显示课程来使读者更容易,但这只会引起混淆,所以我添加了我的警报选择器类

公共类AlarmChooser扩展了Activity {

private ListView listview;


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

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int Width = dm.widthPixels;
    int height = dm.heightPixels;

    getWindow().setLayout( (Width), (int) (height * .55));
    listview = (ListView) findViewById( R.id.smallList );
    final String[] alarms= new String[]{"Time and Date Reminder","Birthday Reminder",
            "HolidayReminder(Lebanon)","HolidayReminder(SaudiArabia)","HolidayReminder(Kuwait)","HolidayReminder(UAE)", "Timer"};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1,android.R.id.text1,alarms);

    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int intposition = i;
            String clickedValue=listview.getItemAtPosition(intposition).toString();
            Toast.makeText(AlarmChooser.this, clickedValue, Toast.LENGTH_SHORT).show();



            if(alarms[0].equals(clickedValue)){
                startActivity(new Intent(getApplicationContext(), TimeDateRem.class));
            }else if(alarms[1].equals(clickedValue)){
                startActivity(new Intent(getApplicationContext(),BirthdayRem.class));
            }else if(alarms[2].equals(clickedValue)){
                startActivity(new Intent(getApplicationContext(),HolidayReminderLebanon.class));
            }else if(alarms[3].equals(clickedValue) ){
                startActivity(new Intent(getApplicationContext(), HolidayReminderSaudiArabia.class));
            }else if(alarms[4].equals(clickedValue)) {
                startActivity(new Intent(getApplicationContext(), HolidayReminderKuwait.class));
            }else if(alarms[5].equals(clickedValue)) {
                startActivity(new Intent(getApplicationContext(), HolidayReminderUAE.class));
            }else if(alarms[6].equals(clickedValue)) {
                startActivity(new Intent(getApplicationContext(), Timer.class));
            }

        }
    });
}

}

2 个答案:

答案 0 :(得分:1)

使用finish()而不是再次启动Activity。以前的活动将保持自己的状态。

public void saveToDB(){

MyAlarm alarm= new MyAlarm();
alarm.setTitle(title.getText().toString().trim());
alarm.setRecordDate(pickerDate.getDayOfMonth()+"/"+pickerDate.getMonth()+"/"+pickerDate.getYear());
alarm.setRecordTime(pickerTime.getCurrentHour()+"/"+pickerTime.getCurrentMinute());

dba.addAlarms(alarm);
dba.close();

info.setText("");

finish();

}

答案 1 :(得分:0)

  

如何保存活动状态

您似乎已经知道如何使用onSaveInstanceState

你不应该为列表视图需要它,但它只是加载数据库

另外,不确定这里有什么问题,但是你想在这里完成活动,例如

   cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cancelAlarm(pendingIntent);
            finish();  // not start a new Activity 
        }
    });
  

我希望能够在点击该行时编辑闹钟

很难知道要警告你什么,只需从字符串的ArrayAdapter进行编辑即可。您想要在使用AlarmAdapter类的ListView上设置您的点击,然后您可以执行类似的操作

// inside onItemClick
MyAlarm alarm = (MyAlarm) adapterView.getItemAtPosition(position);

Class next = null;
if(alarms[0].equals(clickedValue)){
    next = TimeDateRem.class;
}else if(alarms[1].equals(clickedValue)) {
    next = BirthdayRem.class;
}

if (next!=null) {
    next.putExtra("alarm_id", alarm.getId()); // for example 
    startActivity(AlarmChooser.this , next);
} 

How do I pass data between Activities in Android application?

  

点击行本身时重新加载

只要您更新数据库,就会使用这些编辑

创建您的活动数据