0

I can pick images from a gallery and assign a image to ImageView. Preference manager keeps the image in place when i leave and return to the activity.

I can change that image by onclick of the ImageView to a new image. What I need is a way to create a new instance of the same activity with only the image in the ImageView to be changed of updated. The layout would be constant and the image in ImageView would be the new variable in the new instance. Thanks for your interest and help. Mike

  Thanks again : Here is Code  

AlarmDetailsActivity.Java:

public class AlarmDetailsActivity extends Activity {

private AlarmDBHelper dbHelper = new AlarmDBHelper(this);

private AlarmModel alarmDetails;

ImageView imageView ;

ImageView imageView2;

private static int RESULT_LOAD_IMAGE ;

private TimePicker timePicker;
private EditText edtName;
private CustomSwitch chkWeekly;
private CustomSwitch chkSunday;
private CustomSwitch chkMonday;
private CustomSwitch chkTuesday;
private CustomSwitch chkWednesday;
private CustomSwitch chkThursday;
private CustomSwitch chkFriday;
private CustomSwitch chkSaturday;
private TextView txtToneSelection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    setContentView(R.layout.activity_details);

    getActionBar().setTitle("Create New Alarm");
    getActionBar().setDisplayHomeAsUpEnabled(true);

    timePicker = (TimePicker)

    findViewById(R.id.alarm_details_time_picker);
    edtName = (EditText) findViewById(R.id.alarm_details_name);
    chkWeekly = (CustomSwitch) 
    findViewById(R.id.alarm_details_repeat_weekly);
    chkSunday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_sunday);
    chkMonday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_monday);
    chkTuesday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_tuesday);
    chkWednesday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_wednesday);
    chkThursday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_thursday);
    chkFriday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_friday);
    chkSaturday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_saturday);
    txtToneSelection = (TextView) 
    findViewById(R.id.alarm_label_tone_selection);

    long id = getIntent().getExtras().getLong("id");

    if (id == -1) {
        alarmDetails = new AlarmModel();
    } else {
        alarmDetails = dbHelper.getAlarm(id);

        timePicker.setCurrentMinute(alarmDetails.timeMinute);
        timePicker.setCurrentHour(alarmDetails.timeHour);

        edtName.setText(alarmDetails.name);

        chkWeekly.setChecked(alarmDetails.repeatWeekly);

chkSunday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.SUNDAY));
chkMonday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.MONDAY));
chkTuesday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.TUESDAY));

  ETC.



        txtToneSelection.setText(RingtoneManager.getRingtone(this,  
    alarmDetails.alarmTone).getTitle(this));
    }

    final LinearLayout ringToneContainer = (LinearLayout)
    findViewById(R.id.alarm_ringtone_container);
    ringToneContainer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new 
    Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            startActivityForResult(intent , 1);
        }
    });
    } 

   @Override
   protected void onActivityResult(int requestCode, int resultCode,  
   Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case 1: {
                alarmDetails.alarmTone =
    data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

    txtToneSelection.setText(RingtoneManager.getRingtone(this,
    alarmDetails.alarmTone).getTitle(this));
                break;
            }
            default: {
                break;
            }
        }
    }





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

    button.setOnClickListener(new Button.OnClickListener(){



        @Override
        public void onClick(View v) {
             Intent i = new Intent(
                        Intent.ACTION_PICK,

      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);

             Toast.makeText(getBaseContext(), "Set Image ",   
      Toast.LENGTH_LONG).show();
        }
      });
      } 


      public void onActivityResult (int requestCode, int resultCode,  
      Intent data, int SELECT_PICTURE, Intent intent, Uri selectedImage,
      Intent intent1 ) {


            if (requestCode == RESULT_LOAD_IMAGE && resultCode == 
           RESULT_OK && null != data) {



                String[] filePathColumn = { MediaStore.Images.Media.DATA
      };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex =
      cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();



                ImageView imageView  = (ImageView)
      findViewById(R.id.imageView2);


      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));


                BitmapFactory.Options options = new
      BitmapFactory.Options();
                options.inSampleSize = 6;
                options.inScaled = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;

      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath,  
      options));



            AlarmManager alarmManager = (AlarmManager)
      getSystemService(ALARM_SERVICE);
            // initializing our pending intent, this is where the magic
      happens :)
            // notice that we're using the intent from above, read more  
      about the method down below
            // notice the FLAG_UPDATE_CURRENT flag here, this will
      update our instance of previous
            // pending intents to the pending intent we have now
            PendingIntent pendingIntent =
      PendingIntent.getBroadcast(getApplicationContext(), 100,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // finally set the alarm manager, I'm using set here, but be
      sure to go through the 
            // documentation as there are other methods like 
      setRepeating(), etc
            // which may satisfy your need
            alarmManager.set(AlarmManager.RTC_WAKEUP,
      System.currentTimeMillis(), pendingIntent);
        }}


     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.alarm_details, menu);
     return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {

     switch (item.getItemId()) {
        case android.R.id.home: {
            finish();
            break;
        }
        case R.id.action_save_alarm_details: {
            updateModelFromLayout();

            AlarmManagerHelper.cancelAlarms(this);

            if (alarmDetails.id < 0) {
                dbHelper.createAlarm(alarmDetails);
            } else {
                dbHelper.updateAlarm(alarmDetails);
            }

            AlarmManagerHelper.setAlarms(this);

            setResult(RESULT_OK);
            finish();
           }
           }

           return super.onOptionsItemSelected(item);
           }

           private void updateModelFromLayout() {       
           alarmDetails.timeMinute =    
           timePicker.getCurrentMinute().intValue();
           alarmDetails.timeHour =   
           timePicker.getCurrentHour().intValue();
           alarmDetails.name = edtName.getText().toString();
           alarmDetails.repeatWeekly = chkWeekly.isChecked();   
           alarmDetails.setRepeatingDay(AlarmModel.SUNDAY,   
           chkSunday.isChecked());  
           alarmDetails.setRepeatingDay(AlarmModel.MONDAY,   
           chkMonday.isChecked());  
    alarmDetails.setRepeatingDay(AlarmModel.TUESDAY,  
    chkTuesday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.WEDNESDAY,  
    chkWednesday.isChecked());  
    alarmDetails.setRepeatingDay(AlarmModel.THURSDAY,
    chkThursday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.FRDIAY,
    chkFriday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.SATURDAY,
    chkSaturday.isChecked());
    alarmDetails.isEnabled = true;
    }

    public static int getRESULT_LOAD_IMAGE() {
    return RESULT_LOAD_IMAGE;
    }

    public static void setRESULT_LOAD_IMAGE(int rESULT_LOAD_IMAGE) {
    RESULT_LOAD_IMAGE = rESULT_LOAD_IMAGE;
    }

   ;}


   activity_details.xml:


  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:isScrollContainer="true" >

  <!--
        <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AlarmDetailsActivity" >
    -->

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".AlarmDetailsActivity" >

    <TimePicker
        android:id="@+id/alarm_details_time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:id="@+id/alarm_details_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/alarm_details_time_picker"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:ems="10"
        android:hint="@string/details_alarm_name" />

      <View
        android:id="@+id/divider2"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_name" />

      <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_weekly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider2"
        android:checked="true"
        android:text="@string/details_repeat_weekly" />

        <View
        android:id="@+id/divider1"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_weekly" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_sunday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider1"
        android:checked="true"
        android:text="@string/details_sunday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_monday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_sunday"
        android:layout_below="@+id/alarm_details_repeat_sunday"
        android:checked="true"
        android:text="@string/details_monday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_tuesday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_monday"
        android:layout_below="@+id/alarm_details_repeat_monday"
        android:checked="true"
        android:text="@string/details_tuesday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_wednesday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_tuesday"
        android:layout_below="@+id/alarm_details_repeat_tuesday"
        android:checked="true"
        android:text="@string/details_wednesday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_thursday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_wednesday"
        android:layout_below="@+id/alarm_details_repeat_wednesday"
        android:checked="true"
        android:text="@string/details_thursday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_friday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_thursday"
        android:layout_below="@+id/alarm_details_repeat_thursday"
        android:checked="true"
        android:text="@string/details_friday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_saturday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_friday"
        android:layout_below="@+id/alarm_details_repeat_friday"
        android:checked="true"
        android:text="@string/details_saturday" />

        <View
        android:id="@+id/divider4"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_saturday" />

        <LinearLayout
        android:id="@+id/alarm_ringtone_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/divider4"
        android:background="@drawable/view_touch_selector"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/alarm_label_tone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/alarm_label_tone_selection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone_default"
            android:textSize="14sp" />
         <View
              android:id="@+id/divider5"
              style="@style/Divider"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/alarm_ringtone_container" />

         <Button
             android:id="@+id/button1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
             android:layout_centerHorizontal="true"
             android:layout_gravity="center"
             android:text="Picture" />

           </LinearLayout>

           <View
           android:id="@+id/divider3"
           style="@style/Divider"
           android:layout_alignParentLeft="true"
           android:layout_below="@+id/alarm_ringtone_container" />
           </RelativeLayout>

           </ScrollView>



           AlarmScreen.java


           public class AlarmScreen extends Activity {

           public final String TAG = this.getClass().getSimpleName();

           private WakeLock mWakeLock;
           private MediaPlayer mPlayer;

           private static final int WAKELOCK_TIMEOUT = 60 * 1000;

           ImageView imageView2;


           @Override
           protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);

           //Setup layout
           this.setContentView(R.layout.activity_alarm_screen);

           String name =     
           getIntent().getStringExtra(AlarmManagerHelper.NAME);
           int timeHour =    
           getIntent().getIntExtra(AlarmManagerHelper.TIME_HOUR, 0);
           int timeMinute =   
           getIntent().getIntExtra(AlarmManagerHelper.TIME_MINUTE, 0);
           String tone = getIntent().get
           StringExtra(AlarmManagerHelper.TONE);

           TextView tvName = (TextView)  
           findViewById(R.id.alarm_screen_name);
           tvName.setText(name);

           TextView tvTime = (TextView)   
           findViewById(R.id.alarm_screen_time);
           tvTime.setText(String.format("%02d : %02d", timeHour,    
           timeMinute));

           Button dismissButton = (Button)   
           findViewById(R.id.alarm_screen_button);
           dismissButton.setOnClickListener(new OnClickListener() {

           @Override
           public void onClick(View view) {
            mPlayer.stop();
            mPlayer.release();
            finish();

            mPlayer = new MediaPlayer();

             mPlayer = MediaPlayer.create(AlarmScreen.this, R.raw.lunch);
                mPlayer.start();
            Intent alarmIntent = new Intent(getBaseContext(),  
            TimerActivity.class);
            alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            getApplication().startActivity(alarmIntent);




            //Play alarm tone
           mPlayer = new MediaPlayer();
           try {
           if (tone != null && !tone.equals("")) {
            Uri toneUri = Uri.parse(tone);
            if (toneUri != null) {
                mPlayer.setDataSource(this, toneUri);
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(true);
                mPlayer.prepare();
                mPlayer.start();
            }
            }
            } catch (Exception e) {
            e.printStackTrace();
             }

            //Ensure wakelock release
            Runnable releaseWakelock = new Runnable() {

           @Override
           public void run() {

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

            if (mWakeLock != null && mWakeLock.isHeld()) {
                mWakeLock.release();
            }
        }
    };

    new Handler().postDelayed(releaseWakelock, WAKELOCK_TIMEOUT);
    }

  protected android.content.Intent AlarmIntent(
        OnClickListener onClickListener, Class<Task> class1) {
    // TODO Auto-generated method stub
    return null;
   }

  protected <MainActivity> Intent Intent(OnClickListener onClickListener,
        Class<MainActivity> class1) {
    // TODO Auto-generated method stub
    return null;
   }

  @SuppressWarnings("deprecation")
    @Override
   protected void onResume() {
    super.onResume();

    // Set the window to keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    // Acquire wakelock
    PowerManager pm = (PowerManager)  
 getApplicationContext().getSystemService(Context.POWER_SERVICE);
    if (mWakeLock == null) {
        mWakeLock = pm.newWakeLock((PowerManager.FULL_WAKE_LOCK |  
  PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
  PowerManager.ACQUIRE_CAUSES_WAKEUP), TAG);
    }

    if (!mWakeLock.isHeld()) {
        mWakeLock.acquire();
        Log.i(TAG, "Wakelock aquired!!");
    }

     }

   @Override
   protected void onPause() {
    super.onPause();

    if (mWakeLock != null && mWakeLock.isHeld()) {
        mWakeLock.release();
    }
    }}

    activity_alarm_screen.xml:


    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res   
    /android"
    android:layout_width="match_parent"
     android:layout_height="match_parent" >

    <TextView
    android:id="@+id/alarm_screen_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp"
    android:text="Alarm!"
    android:textSize="38dp" />

     <TextView
    android:id="@+id/alarm_screen_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/alarm_screen_button"
    android:layout_below="@+id/alarm_screen_title"
    android:layout_marginTop="28dp"
    android:text="00 : 00"
    android:textSize="52dp" />

     <TextView
    android:id="@+id/alarm_screen_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/alarm_screen_time"
    android:layout_centerHorizontal="true"
    android:text="Alarm name" />

    <Button
    android:id="@+id/alarm_screen_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="16dp"
    android:text="Dismiss"
    android:textSize="38dp" />

    <ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/alarm_screen_button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/alarm_screen_name" />

    </RelativeLayout>


    AlarmManagerHelper/BroadcastReceiver.Java:



    public class AlarmManagerHelper extends BroadcastReceiver {

    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String TIME_HOUR = "timeHour";
    public static final String TIME_MINUTE = "timeMinute";
    public static final String TONE = "alarmTone";

    @Override
    public void onReceive(Context context, Intent intent) {
    setAlarms(context);
      intent.getParcelableExtra("my-uri");
     }   


     public static void setAlarms(Context context) {
     cancelAlarms(context);

      AlarmDBHelper dbHelper = new AlarmDBHelper(context);

      List<AlarmModel> alarms =  dbHelper.getAlarms();

      for (AlarmModel alarm : alarms) {
        if (alarm.isEnabled) {

            PendingIntent pIntent = createPendingIntent(context, alarm);

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, alarm.timeHour);
            calendar.set(Calendar.MINUTE, alarm.timeMinute);
            calendar.set(Calendar.SECOND, 00);

            //Find next time to set
            final int nowDay =  
            Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
            final int nowHour =   
            Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
            final int nowMinute = 
            Calendar.getInstance().get(Calendar.MINUTE);
            boolean alarmSet = false;

            //First check if it's later in the week
            for (int dayOfWeek = Calendar.SUNDAY; dayOfWeek <= 
            Calendar.SATURDAY; ++dayOfWeek) {
                if (alarm.getRepeatingDay(dayOfWeek - 1) && dayOfWeek   
             >= nowDay &&
            !(dayOfWeek == nowDay && alarm.timeHour < nowHour) &&
            !(dayOfWeek == nowDay && alarm.timeHour == nowHour &&  
           alarm.timeMinute <= nowMinute)) {
                    calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

                    setAlarm(context, calendar, pIntent);
                    alarmSet = true;
                    break;
                }
            }

            //Else check if it's earlier in the week
            if (!alarmSet) {
                for (int dayOfWeek = Calendar.SUNDAY; dayOfWeek <= 
           Calendar.SATURDAY; ++dayOfWeek) {
                    if (alarm.getRepeatingDay(dayOfWeek - 1) &&
           dayOfWeek <= nowDay && alarm.repeatWeekly) {
                        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
                        calendar.add(Calendar.WEEK_OF_YEAR, 1);

                        setAlarm(context, calendar, pIntent);
                        alarmSet = true;
                        break;
                    }
                }
            }
         }
        }
       }

        @SuppressLint("NewApi")
        private static void setAlarm(Context context, Calendar calendar,
        PendingIntent pIntent) {
        AlarmManager alarmManager = (AlarmManager)
        context.getSystemService(Context.ALARM_SERVICE);
         if (android.os.Build.VERSION.SDK_INT >=  
         android.os.Build.VERSION_CODES.KITKAT) {
         alarmManager.setExact(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis(), pIntent);
          } else {
          alarmManager.set(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis(), pIntent);
         }
         }

         public static void cancelAlarms(Context context) {
        AlarmDBHelper dbHelper = new AlarmDBHelper(context);

         List<AlarmModel> alarms =  dbHelper.getAlarms();

         if (alarms != null) {
        for (AlarmModel alarm : alarms) {
            if (alarm.isEnabled) {
                PendingIntent pIntent = createPendingIntent(context,     
         alarm);

                AlarmManager alarmManager = (AlarmManager)
          context.getSystemService(Context.ALARM_SERVICE);
                 alarmManager.cancel(pIntent);
            }
          }
          }
         }

        private static PendingIntent createPendingIntent(Context   
        context, AlarmModel model) {
        Intent intent = new Intent(context, AlarmService.class);
         intent.putExtra(ID, model.id);
        intent.putExtra(NAME, model.name);
         intent.putExtra(TIME_HOUR, model.timeHour);
         intent.putExtra(TIME_MINUTE, model.timeMinute);
         intent.putExtra(TONE, model.alarmTone.toString());

          return PendingIntent.getService(context, (int) model.id,  
         intent, PendingIntent.FLAG_UPDATE_CURRENT);
         }
          }
Mike
  • 41
  • 1
  • 1
  • 8
  • Every activity has to be defined in android manifest , there is no point in creating new activity every time as it will make your program run slow, its better to just update the imageView every time – Sanjeev Aug 24 '15 at 04:18

2 Answers2

0

You don't need to recreate a new instance of Activity if you want to replace ImageView with user selection from gallery. You can get an Intent to do that for you. You'll have to do a startActivityForResult() and your activity will have to override the onActivityResult() callback.

Basically your code will look similar to this:

view.onClick() {
   Intent intent = new Intent();
   intent.setType("image/*");
   intent.setAction(Intent.ACTION_GET_CONTENT);
   startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

On your onActivityResult() be sure to fetch the Uri for the image.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
    }
}

For more detail, see this

EDIT: To create a new Alarm for every other image, you don't have to create a new instance of the Activity rather set an Alarm via the AlarmManager

manager.setExact(...)

and use the PendingIntent's flag to update/create a Alarm as per need.

Call this method on your onActivityResult() callback.

Edit: To work with Alarms there are two things that you need to do (I'm assuming that you'll be using a BroadcastReceiver):

1) Create a BroadcastReceiver that will intercept the alarm call.

I really love how easy broadcast receivers makes it to handle these types of events.

E.g.

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do things you want here, with the current implementation
        // the alarm manager will invoke the receiver
        // use the intent param to fetch relevant information 
        Uri selectedImageUri = (Uri) intent.getParcelableExtra("my-uri");
    }   
}

Don't forget to register the receiver into your AndroidManifest.xml

2) In your onActivityResult() initialize the AlarmManager

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            Intent intent = new Intent(this, MyReceiver.class);
            // i'm assuming that you'll need to pass to the image Uri to the receiver
            // you can include needed information into the intent as long as they are
            // primitive types, String, Serializable, arrays or Parcelable objects
            // since Uri's are Parcelable you send them through intents
            intent.putExtra("my-uri", selectedImageUri);
            ...

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            // initializing our pending intent, this is where the magic happens :)
            // notice that we're using the intent from above, read more about the method down below
            // notice the FLAG_UPDATE_CURRENT flag here, this will update our instance of previous
            // pending intents to the pending intent we have now
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // finally set the alarm manager, I'm using set here, but be sure to go through the 
            // documentation as there are other methods like setRepeating(), etc
            // which may satisfy your need
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
        }
    }

getBroadcast(...)

Dealing with all these classes and documentations may seem daunting for now, but give it some time and try to understand code.

For more examples on different Apis check out the ApiDemo I'd also like to recommend this app. The app contains most of the ApiDemos giving you a much needed visual aid :)

Community
  • 1
  • 1
Rakeeb Rajbhandari
  • 5,043
  • 6
  • 43
  • 74
  • Thank you Sir for your interest and help. I am still a new learner,I forgot to mention or make clear that the new instance is for alarm intents to be called. My thoughts were that each alarm is a new instance as there will be multiple alarms with different images. Hence the question, as I said the container would be same, just a new image for the new alarm. – Mike Aug 24 '15 at 04:32
  • hmmmm sounds interesting @Mike i'll notify you after I update the answer. and please don't call me sir :) – Rakeeb Rajbhandari Aug 24 '15 at 04:36
  • The above code you sighted is what I am using to pick the image and set the image in that same Class. – Mike Aug 24 '15 at 04:37
  • The images reside in the apps private directory and is referenced via strings. – Mike Aug 24 '15 at 05:30
  • @Mike I updated the post. Could you clarify if there is a need to make a new alarm everytime a image is selected or to update the existing alarm on an updated image? – Rakeeb Rajbhandari Aug 24 '15 at 05:55
  • The alarm intent does not need to have a image,only if the user wants it. – Mike Aug 24 '15 at 12:22
  • @Mike then using a single alarm will suffice? won't it? If so, use the update flag in the pending intent – Rakeeb Rajbhandari Aug 24 '15 at 12:25
  • The alarm intent does not need to have a image,only if the user wants it. During the pick image activitiy first run there is no image,it is placed in ImageView when and only if the user selects a image for that instance and preferences keeps track of the images. And thus this way behaves like an option with every new alarm intent/instance to include or not include a image. – Mike Aug 24 '15 at 12:36
  • So are you saying? all I need is one alarm that is recycled and do not need to create a new instance for a newly added alarm and just use the update flag in the new alarm/pending intent as a instance for the new alarm. I am still learning and a example would be helpful in that case. – Mike Aug 24 '15 at 13:15
  • @Mike checkout the edit, I hope that helps, don't forget to vote and accept if the answer helps you out :) – Rakeeb Rajbhandari Aug 24 '15 at 14:39
  • @ Rakeeb Rajbhandari Thank you! very much, it does seem daunting and though I am not seasoned with respect to development. I can tell by symmetry of your answer that it is likely to be correct or at the very least puts me on the right track. I will work with it and report back the outcome. – Mike Aug 24 '15 at 14:54
  • @ Rakeeb Rajbhandari Clarification? does the onActivityResult() go into the alarm details class where I am setting up my alarm or the pick image class where I am changing my images in ImageView. – Mike Aug 24 '15 at 15:51
  • @Mike you can do so. Invoke an intent to your AlarmDetail class where you'd pass in the image Uri to the other activity. onActivityResult() is just a callback notifying you that the user's selection for the image has arrived. You can do whatever you want after that inside the callback. – Rakeeb Rajbhandari Aug 24 '15 at 15:56
  • @ Rakeeb Rajbhandari I have worked this issue from my vantage point. I see no errors,it compiles everything works but I see no image in the target imageView. I can post the relevant code if needed. What I have done in the activities details(setup) is try seperate the concerns of the onActivityResults one is ringtone and the other is the image in the(target) Alarm activties imageView. Since I am getting the uri via strings as reference,I thought that maybe an issue as the onActivity Result points to only a imageview contatiner with source attribute. Should not be a factor if using Java? – Mike Aug 25 '15 at 21:43
  • @ Rakeeb Rajbhandari I have worked this issue from my vantage point. I see no errors,it compiles everything works but I see no image in the target imageView. I can post the relevant code if needed. What I have done in the activities details(setup) is try seperate the concerns of the onActivityResults one is ringtone and the other is the image in the(target) Alarm activties imageView. Since I am getting the uri via strings as reference,I thought that maybe an issue is the onActivity Result points to only a imageview contatiner with no source attribute. Should not be a factor if using Java? – Mike Aug 25 '15 at 21:51
  • Upload your code then, let's see what you're doing. – Rakeeb Rajbhandari Aug 25 '15 at 22:23
  • @ Rakeeb Rajbhandari Sorry How do I repost I only see a comment window. The window to post or repost I do not see. – Mike Aug 25 '15 at 23:49
  • @ Rakeeb Rajbhandari I just posted the Edit of the relevant code. – Mike Aug 26 '15 at 01:32
  • ImageView1 resides with ActivtyDetails.Java in the pick of the image. ImageView 2 resides with AlarmScreen.Java which is the target activity. – Mike Aug 26 '15 at 01:40
  • @ Rakeeb Rajbhandar My System/Network will be down for about the next 15hrs. starting about a half from now. Will return at that time. Please know your time and effort is really appreciated. This app will help a lot of people. – Mike Aug 26 '15 at 01:51
  • Lastly find the link to the alarm module https://github.com/steventrigg/AlarmClock – Mike Aug 26 '15 at 02:06
  • @ Rakeeb Rajbhandar I have distilled my issue down to the two Classes at the heart of the matter. The imagepicker main activity with preference and imageview(ImageView1) and the alarm screen activity with the imageview to be set the target activity (ImageView2). I made this app module just to try and isolate the problem. Still no succes I can see the two distinct (R.Id's) are assigned but when selecting I hit the button to view it it is not showing. The picker activity is a small bit of code and the alarm activity has no code it is just a place holder for the view of imageview 2. – Mike Aug 26 '15 at 21:31
0

As it turns out the answer was as I thought,solved with preference selection and persistence of the selection.Lastly ImageView target was not clearly set in the receiving activity.

@ Rakeeb Rajbhandari answer proved to be very helpful on how to move foward. Thanks to Rakeeb Rajbhandari and any others that might have had interest in this issue.

Mike
  • 41
  • 1
  • 1
  • 8