简体   繁体   中英

global variables show null outside activityResult method

I have two activities(one fragment and other activtiy) one to set alarm and the other to select tones. I'm using startActivityForResult() method but. in the main activity when I access the result it shows the expected result like this:

@Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1){
            if (resultCode == RESULT_OK){
                songPath = data.getStringExtra("SongName");
                Log.d("Okay","song path :"+songPath);
            }
        }
    }


but when I access the same stored in a global "songPath" variable then it shows null.

Log.d("Okay",""+songPath);

here's the code.

public class HomeFragment extends Fragment implements AlarmRecyclerViewListener,TimePickerDialog.OnTimeSetListener{

    private String songPath;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Getting a writable reference of the Database.
        db = mAlarmsDBhelperClass.getWritableDatabase();

        //Retrieving values from the database and storing them in custom ArrayLists
        boolean isDataEmpty = getAlarm(db);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1){
            if (resultCode == RESULT_OK){
                songPath = data.getStringExtra("SongName");
                Log.d("Okay","song path :"+songPath);
            }
        }
    }
    public void startAlarm(Calendar c,int position,boolean isQuick,int requestCode){
        if (!isQuick) {
            //Getting a System service for the alarm to check the current time with the Alarm set time.
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            //Creating an intent to invoke the onReceive method  in the custom receiver class, just to display notifications.
            Log.d("Okay",""+modeArrayList.get(position)+" "+songPath);
            Intent intent = new Intent(getContext(), AlarmReceiver.class);
            intent.putExtra("mode",modeArrayList.get(position));
            intent.putExtra("songPath",songPath);
            //A pending intent is used to execute some work in the future with our applications permissions.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),requestCodes.get(position),intent,0);
            //Now RTC_WAKEUP means if the device is Switched off turn it on.
            //getTimeInMillis() will get get the time in Milliseconds
            //Schedule an alarm to be delivered precisely at the stated time.In my case it's the calendar's getTimeMillis() method. which is providing the correct time in milliseconds.
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
        } else {
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getContext(), AlarmReceiver.class);
            Log.d("Okay",""+modeArrayList.get(position)+" "+songPath);
            intent.putExtra("mode","quick");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),requestCode,intent,0);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
        }
    }
}
@Override
    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        if (c.getTimeInMillis() < System.currentTimeMillis())
            c.add(Calendar.DAY_OF_YEAR, 1);
        Intent intent = new Intent(getContext(), RingtoneSelector.class);
        startActivityForResult(intent,FRAGMENT_HOME_REQUEST_CODE);
        mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
        startAlarm(c,0,true,quickHour+quickMin+1);
        alarmAdapter.notifyDataSetChanged();
    }

I'm getting null in the log cat when I access the songPath variable in the startAlarm() and onTimeSet() 's Log.d() .

startActivityForResult is not a blocking call.

@Override
    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        if (c.getTimeInMillis() < System.currentTimeMillis())
            c.add(Calendar.DAY_OF_YEAR, 1);
        Intent intent = new Intent(getContext(), RingtoneSelector.class);
        startActivityForResult(intent,FRAGMENT_HOME_REQUEST_CODE); // THIS LINE DOES NOT BLOCK
        mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
        startAlarm(c,0,true,quickHour+quickMin+1);
        alarmAdapter.notifyDataSetChanged();
    }

These three lines:

mAlarmsDBhelperClass.insertAlarm("","⚡","",songPath,hour,minute,"ON",0,db);
startAlarm(c,0,true,quickHour+quickMin+1);
alarmAdapter.notifyDataSetChanged();

Will still be executed straight after startAtivityForResult . Therefore songPath will be null.

You should call startAlarm etc inside of the onActivityResult method.

Is the value of your FRAGMENT_HOME_REQUEST_CODE = 1 . In your onActivityResult method you check if (requestCode == 1) , which should properly be

if (requestCode == FRAGMENT_HOME_REQUEST_CODE)

Be sure to use the same value you used for startActivityForResult method. See if this was the issue. Provided you are managing everything else correctly in the other activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM