0

I have a jpg image in the drawable resource and I want to pass that image from the MainActivity to the AlarmReceiver class and then to the FakeRinger Activity. I have an option of "place a quick call" in my app and when the user press that option, the quickCall() method triggers which is in the MainActivity. I want to pick that image form the drawable and it should be pass from that method within the MainActivity and send it to the AlarmReceiver class and then to the FakeRinger activity. Here's my code below:

MainActivity:

public class MainActivity extends AppCompatActivity {

    public static final String LOG_TAG = "MainActivity";

    ImageView imageView;
    EditText number, name;
    Button setTimeButton;
    ImageButton imageButton;
    TimePickerDialog timePicker;
    long selectedTimeInMillis;
    String enteredName, enteredNumber;

    private static final int SELECT_IMAGE = 100;

    public static final int REQUEST_CODE_PI = 1001;

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

        PreferenceManager.setDefaultValues(this, R.xml.settings, false);

        imageView = findViewById(R.id.image_view);
        setTimeButton = findViewById(R.id.set_time);
        imageButton = findViewById(R.id.place_call_button);

        number = findViewById(R.id.number);
        name = findViewById(R.id.name);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, SELECT_IMAGE);
            }
        });

        setTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                timePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        calendar.set(Calendar.MINUTE, minute);
                        calendar.set(Calendar.SECOND, 0);
                        calendar.set(Calendar.MILLISECOND, 0);
                        selectedTimeInMillis = calendar.getTimeInMillis();

                        if (hourOfDay > 12) {
                            hourOfDay = hourOfDay - 12;
                        }

                        Toast.makeText(MainActivity.this, hourOfDay + ":" + minute, Toast.LENGTH_SHORT).show();

                        Log.v(LOG_TAG, "Selected time in millis:" + selectedTimeInMillis);
                    }
                }, hour, minute, false);
                timePicker.show();
            }
        });

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enteredName = name.getText().toString().trim();
                enteredNumber = number.getText().toString().trim();
                if (enteredNumber.isEmpty()){
                    Toast.makeText(MainActivity.this, "Please enter  a number", Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent = new Intent(MainActivity.this, AlarmReciever.class);
                intent.putExtra("FAKE_NAME", enteredName);
                intent.putExtra("FAKE_NUMBER", enteredNumber);

                PendingIntent pendingIntent =
                        PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_PI, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                if (alarmManager != null) {
                    alarmManager.set(AlarmManager.RTC_WAKEUP, selectedTimeInMillis, pendingIntent);
                    Toast.makeText(MainActivity.this, "Your call has been placed", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Error: something wrong", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings:
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
                return true;

            case R.id.quick_call:
                quickCall();
                return true;

                default:
                return super.onOptionsItemSelected(item);
        }
    }

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

        if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = null;
            if (selectedImage != null) {
                cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
            }
            if (cursor != null) {
                cursor.moveToFirst();
            }

            int columnIndex = 0;
            if (cursor != null) {
                columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            }
            String picturePath = null;
            if (cursor != null) {
                picturePath = cursor.getString(columnIndex);
            }
            if (cursor != null) {
                cursor.close();
            }

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

        }


    }

    public void quickCall(){
        enteredName = getString(R.string.quick_fake_name);
        enteredNumber = getString(R.string.quick_fake_number);

        Calendar calendar = Calendar.getInstance();
        calendar.get(Calendar.HOUR_OF_DAY);
        calendar.get(Calendar.MINUTE);
        long millis = calendar.getTimeInMillis();

        Intent quickCallIntent = new Intent(MainActivity.this, AlarmReciever.class);
        quickCallIntent.putExtra("FAKE_NAME", enteredName);
        quickCallIntent.putExtra("FAKE_NUMBER", enteredNumber);

        PendingIntent quickCallPendingIntent =
                PendingIntent.getBroadcast(getApplicationContext(), REQUEST_CODE_PI, quickCallIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (alarmManager != null) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, millis + 10000, quickCallPendingIntent);
            Toast.makeText(MainActivity.this, "Your call has been placed", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Error: something wrong", Toast.LENGTH_SHORT).show();
        }
    }
}

AlarmReceiver class:

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String getFakeName = intent.getStringExtra("FAKE_NAME");
        String getFakeNumber = intent.getStringExtra("FAKE_NUMBER");

        Intent fakeRinger = new Intent();
        fakeRinger.setClassName("com.example.mani.fakecall", "com.example.mani.fakecall.FakeRinger");
        fakeRinger.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        fakeRinger.putExtra("USER_FAKE_NAME", getFakeName);
        fakeRinger.putExtra("USER_FAKE_NUMBER", getFakeNumber);
        context.startActivity(fakeRinger);

        if(getFakeName != null){
            Log.v("Fake name is", getFakeName);
        }
        if(getFakeNumber != null){
            Log.v("Fake number is", getFakeNumber);
        }
    }
}

FakeRinger activity:

public class FakeRinger extends AppCompatActivity {

    TextView displayName, displayNumber, displayCarrier;
    ImageButton alarmOffButton;
    String carrierName;
    ImageView displayImage;

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

        displayName = findViewById(R.id.display_name);
        displayNumber = findViewById(R.id.display_number);
        displayCarrier = findViewById(R.id.network_operator);
        displayImage = findViewById(R.id.display_image);

        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            carrierName = telephonyManager.getNetworkOperatorName();
        }

        if (carrierName != null) {
            displayCarrier.setText(getResources().getString(R.string.incoming_call, carrierName));
        } else {
            displayCarrier.setText(getResources().getString(R.string.incoming_call));
        }

        Intent intent = getIntent();
        String userFakeNumber = intent.getStringExtra("USER_FAKE_NUMBER");

        displayNumber.setText(userFakeNumber);

        displayName.setText(getFakeName());

        alarmOffButton = findViewById(R.id.hang_up_call);
        alarmOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                stopService(intent);
                if (alarmManager != null) {
                    alarmManager.cancel(pendingIntent);
                }
            }
        });
    }

    private String getFakeName(){
        String contacName;
        Intent intent = getIntent();
        contacName = intent.getStringExtra("USER_FAKE_NAME");
        if (contacName.isEmpty()){
            contacName = getString(R.string.unknown_name);
        }
        return contacName;
    }
}

I have searched a lot about this problem but still no solution.

mani
  • 39
  • 6

2 Answers2

0

In MainActivity

EDIT

String selectedImagePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //...

            Intent intent = new Intent(MainActivity.this, AlarmReciever.class);
            //...
            intent.putExtra("SELECTED_IMAGE_PATH", selectedImagePath);

            // ...

        }
    }

    //...
}


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

    if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();

        selectedImagePath = selectedImage.toString();

        //...
    }
}   

public void quickCall() {
    //...

    Intent quickCallIntent = new Intent(MainActivity.this, AlarmReciever.class);
    quickCallIntent.putExtra("FAKE_NAME", enteredName);
    quickCallIntent.putExtra("FAKE_NUMBER", enteredNumber);
    // ADD THIS LINE TO YOUR INTENT
    intent.putExtra("SELECTED_IMAGE_PATH", selectedImagePath);
    //...
}

In AlarmReciever

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //...
        String selectedPath = intent.getStringExtra("SELECTED_IMAGE_PATH");

        //...
        fakeRinger.putExtra("SELECTED_IMAGE_PATH", selectedPath);
        //...
    }
}

In FakeRinger

public class FakeRinger extends AppCompatActivity {

    //...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //...

        Intent intent = getIntent();
        String userFakeNumber = intent.getStringExtra("USER_FAKE_NUMBER");
        String path = intent.getStringExtra("SELECTED_IMAGE_PATH");

        Uri imageUri  = Uri.parse(path);
        // See: https://stackoverflow.com/a/4717740/1827254 for more information
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
        // THEN use your bitmap in any ImageView you want
        //...   
}

Note: Please name your variables for them to make sense. For example imageButton should be named callButton.

Eselfar
  • 3,759
  • 3
  • 23
  • 43
  • Your image is a drawable in you drawable resource directory, right. When you reference it in the app you use the id of this resource `R.drawable.my_image`. This id is an int. So just pass it as an intent parameter. Then you retrieve it from the intent as you do for `FAKE_NAME` and `FAKE_NUMBER`. Then you can use this image using the resource id or by getting the drawable directly, doing `context.getResources().getDrawable()` – Eselfar Jan 04 '18 at 18:12
  • Can you write me the full coding steps ? – mani Jan 04 '18 at 18:14
  • Ok wait, this is not exactly what you've described. You are not retrieving the image from the app drawable resources but you ask the user to select an image from the gallery which is completely different. Give me 10min – Eselfar Jan 04 '18 at 18:24
  • I am a total beginner bro, i didn't get your code. Can you make it a bit more easy for me to understand ? – mani Jan 04 '18 at 18:45
  • Basically all the `//...` are the code you've already. So all you need to do is to add my code at the correct places – Eselfar Jan 04 '18 at 18:47
  • It would have be difficult to see what I've added if I had kept all the code. So I tried to keep only the code necessary for you to know where to add mine( if that makes sense) – Eselfar Jan 04 '18 at 18:49
  • I can add some comment later if there are some parts you don't understand. I have to go now – Eselfar Jan 04 '18 at 18:50
  • I have done exactly like you said bro, but it's still not working :( – mani Jan 04 '18 at 18:55
  • `java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mani.fakecall/com.example.mani.fakecall.FakeRinger}: java.lang.NullPointerException: uriString` – mani Jan 05 '18 at 04:58
  • Basically you have to add the path of your selected image to the Intent of the Activity you want to start. Then you retrieve this path from the Intent to use it in the new Activity. I can't write your app for you, you need to understand the logic and ask questions about it if you don't. You can't just say "it's not working". We both try to help you but if you don't make any effort trying to understand what we suggest there is nothing we can do. – Eselfar Jan 05 '18 at 10:02
0

You can try this Way Add this line your quickCall() method and give your correct jpg image name that is in drawable folder.

 quickCallIntent.putExtra("FAKE_IMAGE", "Your Jpg Image Name");

 and Same way get in your AlrmRecevier class and pass to FakeRinger 
 Activity.
 Where do you want to show this image 
 call like this.

 imageView.setBackgrount(getIcon(" pass your jpg image name"));


  private Drawable getIcon(String icon_name) {
    if (!icon_name.equalsIgnoreCase("icon_no_icon")&& 
  !TextUtils.isEmpty(icon_name)) {
        int id = activity.getResources().getIdentifier(icon_name, 
   "drawable", activity.getPackageName());
        Drawable drawable = activity.getResources().getDrawable(id);
        return drawable;
    } else {
        return activity.getDrawable(R.drawable.screen_excision);
    }
}
umesh shakya
  • 237
  • 2
  • 12